package com.engine.organization.service.impl;

import com.api.browser.bean.BrowserBean;
import com.api.browser.bean.SearchConditionGroup;
import com.api.browser.bean.SearchConditionItem;
import com.cloudstore.eccom.result.WeaResultMsg;
import com.engine.core.impl.Service;
import com.engine.organization.component.OrganizationWeaTable;
import com.engine.organization.entity.DeleteParam;
import com.engine.organization.entity.TopTab;
import com.engine.organization.entity.sequence.dto.SequenceDTO;
import com.engine.organization.entity.sequence.param.SequenceSearchParam;
import com.engine.organization.entity.sequence.po.SequencePO;
import com.engine.organization.entity.sequence.vo.SequenceTableVO;
import com.engine.organization.mapper.scheme.SchemeMapper;
import com.engine.organization.mapper.sequence.SequenceMapper;
import com.engine.organization.service.SequenceService;
import com.engine.organization.util.*;
import com.engine.organization.util.db.DBType;
import com.engine.organization.util.db.MapperProxyFactory;
import com.engine.organization.util.detach.DetachUtil;
import com.engine.organization.util.excel.ExcelUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.StringUtil;
import weaver.general.Util;
import weaver.systeminfo.SystemEnv;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;


/**
 * @description:
 * @author:dxfeng
 * @createTime: 2022/05/12
 * @version: 1.0
 */
public class SequenceServiceImpl extends Service implements SequenceService {

    // 判断岗位序列导入模板是否存在，不存在则创建该文件
    static {
        try {
            String outPutPath = GCONST.getRootPath() + File.separator + "hrm" + File.separator + "import" + File.separator + "template" + File.separator + "sequence.xls";
            File excelPathFile = new File(outPutPath);
            if (!excelPathFile.exists()) {
                String columns = "编号,名称,等级方案,方案所属分部,描述说明";
                String[] split = columns.split(",");
                List<Object> columnList = new ArrayList<>(Arrays.asList(split));
                // 创建导入模板
                List<List<Object>> excelSheetData = new ArrayList<>();
                excelSheetData.add(columnList);
                XSSFWorkbook sheets = ExcelUtil.genWorkbookV2(excelSheetData, "sequence");
                File excelFile = new File(outPutPath);
                if (!excelFile.exists()) {
                    String substring = outPutPath.substring(0, outPutPath.lastIndexOf(File.separator));
                    File file = new File(substring);
                    if (file.mkdirs()) {
                        boolean newFile = excelPathFile.createNewFile();
                        if (!newFile) {
                            throw new IOException(outPutPath + ",File Creation Failed");
                        }
                    }
                }
                FileOutputStream out = new FileOutputStream(excelPathFile);
                sheets.write(out);
                out.flush();
            }
        } catch (IOException e) {
            new BaseBean().writeLog(e);
            throw new RuntimeException(e);
        }
    }

    private static final String RIGHT_NAME = "Sequence:All";

    private SequenceMapper getSequenceMapper() {
        return MapperProxyFactory.getProxy(SequenceMapper.class);
    }

    private SchemeMapper getSchemeMapper() {
        return MapperProxyFactory.getProxy(SchemeMapper.class);
    }

    @Override
    public Map<String, Object> listPage(Map<String, Object> params) {
        Map<String, Object> resultMap = new HashMap<>();
        boolean hasRight = HasRightUtil.hasRight(user, RIGHT_NAME, true);
        resultMap.put("hasRight", hasRight);
        if (!hasRight) {
            return resultMap;
        }
        // 刷新引用状态
        RefreshIsUsedUtil.RefreshSequence("jcl_org_sequence");
        OrganizationWeaTable<SequenceTableVO> table = new OrganizationWeaTable<>(user, SequenceTableVO.class);
        String sqlWhere = buildSqlWhere(params);
        table.setSqlwhere(sqlWhere);
        WeaResultMsg result = new WeaResultMsg(false);
        result.putAll(table.makeDataResult());
        result.success();
        resultMap.putAll(result.getResultMap());
        return resultMap;
    }


    @Override
    public int saveSequence(SequenceSearchParam param) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        List<SequencePO> list = getSequenceMapper().listByNo(Util.null2String(param.getSequenceNo()));
        OrganizationAssert.isEmpty(list, SystemEnv.getHtmlLabelName(547137, user.getLanguage()));
        SequencePO sequencePO = SequenceDTO.convertParamToPO(param, (long) user.getUID());
        return getSequenceMapper().insertIgnoreNull(sequencePO);
    }

    @Override
    public int updateSequence(SequenceSearchParam param) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        SequencePO sequencePO = SequenceDTO.convertParamToPO(param, (long) user.getUID());
        String oldSequenceNo = getSequenceMapper().getSequenceByID(sequencePO.getId()).getSequenceNo();
        if (!oldSequenceNo.equals(sequencePO.getSequenceNo())) {
            List<SequencePO> list = getSequenceMapper().listByNo(Util.null2String(sequencePO.getSequenceNo()));
            OrganizationAssert.isEmpty(list, SystemEnv.getHtmlLabelName(547137, user.getLanguage()));
        }
        return getSequenceMapper().updateSequence(sequencePO);
    }

    @Override
    public int updateForbiddenTagById(SequenceSearchParam params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        SequencePO sequencePO = SequencePO.builder().id(params.getId()).forbiddenTag(params.getForbiddenTag() ? 0 : 1).build();
        return getSequenceMapper().updateForbiddenTagById(sequencePO);
    }

    @Override
    public int deleteByIds(Collection<Long> ids) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        OrganizationAssert.notEmpty(ids, SystemEnv.getHtmlLabelName(547138,user.getLanguage()));
        return getSequenceMapper().deleteByIds(ids);
    }


    @Override
    public Map<String, Object> getSearchCondition(Map<String, Object> params) {
        Map<String, Object> apiDatas = new HashMap<>();
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        List<SearchConditionItem> conditionItems = new ArrayList<>();
        SearchConditionItem browserItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, 547124, "161", "schemeId", "schemeBrowser");
        SearchConditionItem sequenceNameCondition = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, 547141, "sequenceName");
        conditionItems.add(browserItem);
        conditionItems.add(sequenceNameCondition);
        addGroups.add(new SearchConditionGroup("高级搜索条件", true, conditionItems));
        apiDatas.put("conditions", addGroups);
        return apiDatas;
    }


    @Override
    public Map<String, Object> getSequenceForm(Map<String, Object> params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        Map<String, Object> apiDatas = new HashMap<>();
        List<SearchConditionItem> selectItems = new ArrayList<>();
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        SearchConditionItem sequenceNameCondition = OrganizationFormItemUtil.inputItem(user, 2, 17, 3, 50, 547141, "sequenceName");
        sequenceNameCondition.setRules("required|string");
        SearchConditionItem sequenceNoCondition = OrganizationFormItemUtil.inputItem(user, 2, 17, 3, 50, 547118, "sequenceNo");
        sequenceNoCondition.setRules("required|string");
        SearchConditionItem descriptionCondition = OrganizationFormItemUtil.textareaItem(user, 2, 17, true, 2, 200, 547142, "description");
        SearchConditionItem browserItem = OrganizationFormItemUtil.browserItem(user, 2, 17, 3, false, 547124, "161", "schemeId", "schemeBrowser");
        browserItem.setRules("required|string");

        // 编辑状态下赋值操作
        String id = Util.null2String(params.get("id"));
        if (!StringUtil.isEmpty(id)) {
            SequencePO sequencePO = getSequenceMapper().getSequenceByID(Integer.parseInt(id));
            OrganizationAssert.notNull(sequencePO, SystemEnv.getHtmlLabelName(547154,user.getLanguage()));

            sequenceNameCondition.setValue(sequencePO.getSequenceName());
            sequenceNoCondition.setValue(sequencePO.getSequenceNo());
            descriptionCondition.setValue(sequencePO.getDescription());
            browserItem.setValue(sequencePO.getSchemeId());

            BrowserBean browserBean = browserItem.getBrowserConditionParam();
            List<Map<String, Object>> maps = getSchemeMapper().listSchemesByIds(DeleteParam.builder().ids(sequencePO.getSchemeId().toString()).build().getIds());

            browserBean.setReplaceDatas(maps);
            browserItem.setBrowserConditionParam(browserBean);
            // 编辑状态下,编号只读
            // sequenceNoCondition.setViewAttr(1);
        }

        selectItems.add(sequenceNoCondition);
        selectItems.add(sequenceNameCondition);
        selectItems.add(descriptionCondition);
        selectItems.add(browserItem);
        addGroups.add(new SearchConditionGroup("基本信息", true, selectItems));
        apiDatas.put("condition", addGroups);
        return apiDatas;
    }

    @Override
    public Map<String, List<MenuBtn>> getHasRight() {
        Map<String, List<MenuBtn>> commonBtnDatas = MenuBtn.getCommonBtnDatas(user.getLanguage());
        commonBtnDatas.get("topMenu").add(MenuBtn.builder().isBatch("1").isTop("1").menuFun("importFile").menuIcon("icon-coms-leading-in").menuName(SystemEnv.getHtmlLabelName(547242,user.getLanguage())).type("BTN_BatchImport").build());
        commonBtnDatas.get("rightMenu").add(MenuBtn.builder().isBatch("1").isTop("0").menuFun("importFile").menuIcon("icon-coms-leading-in").menuName(SystemEnv.getHtmlLabelName(547242,user.getLanguage())).type("BTN_BatchImport").build());
        return commonBtnDatas;
    }

    @Override
    public Map<String, Object> getTabInfo() {
        Map<String, Object> apiDatas = new HashMap<>();
        List<TopTab> topTabs = new ArrayList<>();
        topTabs.add(TopTab.builder().color("#000000").groupId("flowAll").showcount(true).title(SystemEnv.getHtmlLabelName(547191,user.getLanguage())).viewCondition("-1").build());
        topTabs.add(TopTab.builder().color("#ff3232").groupId("enable").showcount(true).title(SystemEnv.getHtmlLabelName(547186,user.getLanguage())).viewCondition("0").build());
        topTabs.add(TopTab.builder().color("#fea468").groupId("disable").showcount(true).title(SystemEnv.getHtmlLabelName(547192, user.getLanguage())).viewCondition("1").build());
        apiDatas.put("topTabs", topTabs);

        HashMap<String, Integer> countMap = new HashMap<>();
        countMap.put("flowAll", getSequenceMapper().getCountByTag(-1));
        countMap.put("enable", getSequenceMapper().getCountByTag(0));
        countMap.put("disable", getSequenceMapper().getCountByTag(1));

        apiDatas.put("topTabCount", countMap);
        return apiDatas;
    }

    @Override
    public Map<String, Object> getSchemeInfo(Map<String, Object> params) {
        String sequenceId = Util.null2String(params.get("sequenceId"));
        SequencePO sequencePO = getSequenceMapper().getSequenceByID(Long.parseLong(sequenceId));
        List<Map<String, Object>> maps = getSchemeMapper().listSchemesByIds(DeleteParam.builder().ids(sequencePO.getSchemeId().toString()).build().getIds());
        return maps.get(0);
    }

    /**
     * 查询条件
     *
     * @param params
     * @return
     */
    private String buildSqlWhere(Map<String, Object> params) {
        DBType dbType = DBType.get(new RecordSet().getDBType());
        String sqlWhere = " where t.delete_type ='0' ";
        String sequenceName = (String) params.get("sequenceName");
        if (StringUtils.isNotBlank(sequenceName)) {
            sqlWhere += " AND t.sequence_name " + dbType.like(sequenceName);
        }
        String schemeId = (String) params.get("schemeId");
        if (StringUtils.isNotBlank(schemeId)) {
            sqlWhere += " AND t.scheme_id = '" + schemeId + "'";
        }
        String viewCondition = (String) params.get("viewCondition");
        // -1:全部、0:启用、1:禁用
        if (StringUtils.isNotBlank(viewCondition) && !"-1".equalsIgnoreCase(viewCondition)) {
            sqlWhere += " AND t.forbidden_tag = '" + viewCondition + "'";
        }

        DetachUtil detachUtil = new DetachUtil(user);
        if (detachUtil.isDETACH()) {
            String jclRoleLevels = detachUtil.getJclRoleLevels();
            sqlWhere += " and s.subcompanyid in (" + jclRoleLevels + ")";
        }
        return sqlWhere;
    }

}
