package cn.com.smart.report.service.impl;

import cn.com.smart.bean.SmartResponse;
import cn.com.smart.report.bean.entity.TReportButton;
import cn.com.smart.service.impl.MgrServiceImpl;
import cn.com.smart.web.bean.entity.TNOPAuth;
import com.mixsmart.enums.YesNoType;
import com.mixsmart.utils.CollectionUtils;
import com.mixsmart.utils.LoggerUtils;
import com.mixsmart.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 乌草坡 2019-09-01
 * @since 1.0
 */
@Service
public class ReportButtonService extends MgrServiceImpl<TReportButton> {

    /**
     * 更新按钮，操作方式为：先删除后添加
     * @param reportId 报表ID
     * @param buttons 按钮列表
     */
    public void updateBtns(String reportId, List<TReportButton> buttons) {
        if(StringUtils.isEmpty(reportId)) {
            LoggerUtils.debug(logger, "报表ID为空");
            return;
        }
        Map<String, Object> param = new HashMap<>(1);
        param.put("reportId", reportId);
        super.deleteByField(param);
        if(CollectionUtils.isEmpty(buttons)) {
            return;
        }
        for(TReportButton btn : buttons) {
            btn.setReportId(reportId);
        }
        super.save(buttons);
    }

    /**
     * 获取操作按钮列表
     * @param reportId
     * @param checkedId
     * @return
     */
    public List<TNOPAuth> findOPAuths(String reportId, String checkedId) {
        List<TNOPAuth> opAuths = new ArrayList<>();
        List<String> checkedIds = null;
        if(StringUtils.isNotEmpty(checkedId)) {
            checkedIds = StringUtils.string2List(checkedId, MULTI_VALUE_SPLIT);
        }
        Map<String, Object> param = new HashMap<>(1);
        param.put("reportId", reportId);
        SmartResponse<TReportButton> queryResp = super.findByParam(param);
        if(OP_SUCCESS.equals(queryResp.getResult())) {
            for(TReportButton button : queryResp.getDatas()) {
                TNOPAuth opAuth = new TNOPAuth();
                opAuth.setName(button.getName());
                opAuth.setValue(button.getBtnId());
                opAuth.setSortOrder(button.getSortOrder().doubleValue());
                if (null != checkedIds && checkedIds.contains(button.getBtnId())) {
                    opAuth.setIsChecked(YesNoType.YES.getIndex());
                } else {
                    opAuth.setIsChecked(YesNoType.NO.getIndex());
                }
            }
        }
        return opAuths;
    }
}
