package com.engine.organization.service.impl;


import com.api.browser.bean.SearchConditionGroup;
import com.api.browser.bean.SearchConditionItem;
import com.api.hrm.bean.HrmFieldBean;
import com.api.hrm.util.HrmFieldSearchConditionComInfo;
import com.cloudstore.eccom.pc.table.WeaTableColumn;
import com.cloudstore.eccom.result.WeaResultMsg;
import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.hrm.service.impl.OrganizationServiceImpl;
import com.engine.organization.component.OrganizationWeaTable;
import com.engine.organization.entity.TopTab;
import com.engine.organization.entity.company.bo.CompBO;
import com.engine.organization.entity.company.dto.CompListDTO;
import com.engine.organization.entity.company.param.CompParam;
import com.engine.organization.entity.company.po.CompPO;
import com.engine.organization.entity.department.param.DepartmentMoveParam;
import com.engine.organization.enums.LogModuleNameEnum;
import com.engine.organization.enums.OperateTypeEnum;
import com.engine.organization.exception.OrganizationRunTimeException;
import com.engine.organization.mapper.comp.CompMapper;
import com.engine.organization.service.CompService;
import com.engine.organization.thread.OrganizationSyncEc;
import com.engine.organization.util.*;
import com.engine.organization.util.db.MapperProxyFactory;
import com.engine.organization.util.detach.DetachUtil;
import com.engine.organization.util.page.Column;
import com.engine.organization.util.page.PageInfo;
import com.engine.organization.util.page.PageUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.definedfield.HrmDeptFieldManagerE9;
import weaver.hrm.definedfield.HrmFieldComInfo;
import weaver.hrm.definedfield.HrmFieldGroupComInfo;
import weaver.hrm.moduledetach.ManageDetachComInfo;
import weaver.systeminfo.SystemEnv;
import weaver.systeminfo.systemright.CheckSubCompanyRight;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @description:
 * @author:dxfeng
 * @createTime: 2022/05/16
 * @version: 1.0
 */
public class CompServiceImpl extends Service implements CompService {

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

    private static CompMapper getCompMapper() {
        return MapperProxyFactory.getProxy(CompMapper.class);
    }

    @Override
    public Map<String, Object> listPage(CompParam params) {
        Map<String, Object> datas = new HashMap<>();
        boolean hasRight = HasRightUtil.hasRight(user, RIGHT_NAME, true);
        datas.put("hasRight", hasRight);
        if (!hasRight) {
            return datas;
        }
        CompPO companyPO = CompBO.convertParamToPO(params, user.getUID());
        boolean filter = isFilter(companyPO);
        PageInfo<CompListDTO> pageInfos;
        String orderSql = PageInfoSortUtil.getSortSql(params.getSortParams(), " showorder ");
        List<CompPO> allList = getCompMapper().listAll(orderSql);

        new DetachUtil(user).filterCompanyList(allList);

        // 通过子级遍历父级元素
        if (filter) {
            // 根据条件获取元素
            List<CompPO> filterCompPOs = getCompMapper().listByFilter(companyPO, orderSql);
            new DetachUtil(user).filterCompanyList(filterCompPOs);

            // 添加父级元素
            List<CompListDTO> compListDTOS = CompBO.buildCompDTOList(allList, filterCompPOs);
            List<CompListDTO> subList = PageUtil.subList(params.getCurrent(), params.getPageSize(), compListDTOS);
            pageInfos = new PageInfo<>(subList, CompListDTO.class);
            pageInfos.setTotal(compListDTOS.size());
        } else {
            // 组合list
            List<CompListDTO> compListDTOS = CompBO.buildCompDTOList(allList);
            List<CompListDTO> subList = PageUtil.subList(params.getCurrent(), params.getPageSize(), compListDTOS);
            pageInfos = new PageInfo<>(subList, CompListDTO.class);
            pageInfos.setTotal(compListDTOS.size());
        }

        pageInfos.setPageNum(params.getCurrent());
        pageInfos.setPageSize(params.getPageSize());

        OrganizationWeaTable<CompListDTO> table = new OrganizationWeaTable<>(user, CompListDTO.class);
        List<Column> columns = pageInfos.getColumns();
        List<WeaTableColumn> weaTableColumn = columns.stream().map(v -> new WeaTableColumn("100", v.getTitle(), v.getKey())).collect(Collectors.toList());
        table.setColumns(weaTableColumn);
        WeaResultMsg result = new WeaResultMsg(false);
        result.putAll(table.makeDataResult());
        result.success();

        datas.put("pageInfo", pageInfos);
        datas.put("dataKey", result.getResultMap());
        return datas;
    }

    @Override
    public Long saveBaseComp(Map<String, Object> params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        Map<String, Object> syncMap = new OrganizationSyncEc(user, LogModuleNameEnum.COMPANY, OperateTypeEnum.ADD, params).sync();
        String companyId = Util.null2String(syncMap.get("id"));
        OrganizationAssert.isTrue(StringUtils.isNotBlank(companyId), syncMap.get("message").toString());
        return Long.parseLong(companyId);

    }

    @Override
    public int updateForbiddenTagById(CompParam params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        CompPO compPO = CompPO.builder().id(params.getId()).canceled(params.getCanceled() ? 0 : 1).build();
        Map<String, Object> map = new HashMap<>();
        map.put("id", compPO.getId().toString());
        map.put("forbiddenTag", compPO.getCanceled());
        new OrganizationSyncEc(user, LogModuleNameEnum.COMPANY, OperateTypeEnum.CANCELED, map).sync();
        return 1;
    }

    @Override
    public Long updateComp(Map<String, Object> params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        Integer ecCompanyId = Integer.parseInt(Util.null2String(params.get("id")));
        String supSubComId = Util.null2String(params.get("supsubcomid"));
        if (StringUtils.isNotBlank(supSubComId)) {
            Set<Integer> disableIds = new HashSet<>();
            disableIds.add(ecCompanyId);
            List<CompPO> compPOS = getCompMapper().listChild(Collections.singletonList(ecCompanyId));
            if (CollectionUtils.isNotEmpty(compPOS)) {
                addDisableIds(disableIds, compPOS);
            }
            OrganizationAssert.isFalse(disableIds.contains(Integer.parseInt(supSubComId)), "上级分部不能选择分部本身及其下级分部");
        }

        new OrganizationSyncEc(user, LogModuleNameEnum.COMPANY, OperateTypeEnum.UPDATE, params).sync();
        return (long) ecCompanyId;
    }

    @Override
    public Map<String, Object> deleteByIds(Map<String, Object> params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        return ServiceUtil.getService(OrganizationServiceImpl.class, user).delSubCompany(params, user);
    }

    @Override
    public Map<String, Object> getSearchCondition() {
        Map<String, Object> apiDatas = new HashMap<>();
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        List<SearchConditionItem> conditionItems = new ArrayList<>();
        // 编号
        SearchConditionItem subCompanyCodeItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "编号", "subCompanyCode");
        // 名称
        SearchConditionItem subCompanyDescItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "名称", "subCompanyDesc");
        // 简称
        SearchConditionItem subCompanyNameItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "简称", "subCompanyName");
        // 上级公司
        SearchConditionItem supSubComIdItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "所属分部", "164", "supSubComId", "");

        conditionItems.add(subCompanyCodeItem);
        conditionItems.add(subCompanyDescItem);
        conditionItems.add(subCompanyNameItem);
        conditionItems.add(supSubComIdItem);
        addGroups.add(new SearchConditionGroup("高级搜索条件", true, conditionItems));
        apiDatas.put("conditions", addGroups);
        return apiDatas;
    }

    @Override
    public Map<String, List<MenuBtn>> getHasRight() {
        return MenuBtn.getDatasNoBtnColum();
    }

    @Override
    public Map<String, Object> getCompBaseForm(Map<String, Object> params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        Map<String, Object> retMap = new HashMap<>();
        List<SearchConditionGroup> groupList = new ArrayList<>();
        List<SearchConditionItem> itemList;

        String id = Util.null2String(params.get("id"));
        int viewAttr = Integer.parseInt((String) params.get("viewAttr"));

        if (2 == viewAttr) {
            params.put("viewattr", viewAttr);
            groupList = getCompanyConditionGroups(true, params);
        } else {
            HrmFieldGroupComInfo HrmFieldGroupComInfo = new HrmFieldGroupComInfo();
            HrmFieldComInfo HrmFieldComInfo = new HrmFieldComInfo();
            HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo();
            SearchConditionItem searchConditionItem;
            HrmFieldBean hrmFieldBean;
            HrmDeptFieldManagerE9 hfm;
            try {
                hfm = new HrmDeptFieldManagerE9(4);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            hfm.getCustomData(Util.getIntValue(id));
            List lsGroup = hfm.getLsGroup();
            for (int tmp = 0; lsGroup != null && tmp < lsGroup.size(); tmp++) {
                String groupId = (String) lsGroup.get(tmp);
                List lsField = hfm.getLsField(groupId);
                if (lsField.size() == 0) {
                    continue;
                }
                if (hfm.getGroupCount(lsField) == 0) {
                    continue;
                }
                if (!"1".equals(Util.null2String(HrmFieldGroupComInfo.getIsShow(groupId)))) {
                    continue;
                }

                String groupLabel = HrmFieldGroupComInfo.getLabel(groupId);
                itemList = new ArrayList<>();
                for (Object o : lsField) {
                    String fieldId = (String) o;
                    String isUse = HrmFieldComInfo.getIsused(fieldId);
                    if (!"1".equals(isUse)) {
                        continue;
                    }
                    String fieldName = HrmFieldComInfo.getFieldname(fieldId);
                    String fieldLabel = HrmFieldComInfo.getLabel(fieldId);
                    String fieldHtmlType = HrmFieldComInfo.getFieldhtmltype(fieldId);
                    String type = HrmFieldComInfo.getFieldType(fieldId);
                    String dmlUrl = Util.null2String(HrmFieldComInfo.getFieldDmlurl(fieldId));
                    String isSystem = HrmFieldComInfo.getIssystem(fieldId);
                    String fieldValue;
                    if ("1".equals(isSystem)) {
                        fieldValue = hfm.getData(fieldName);
                    } else {
                        fieldValue = hfm.getData("hrmsubcompanydefined", fieldName);
                    }

                    if ("84".equals(fieldId)) {
                        if (user.getUID() != 1) {
                            continue;
                        }
                        fieldValue = "0".equals(fieldValue) ? "" : fieldValue;
                    }

                    if (id.length() > 0 && "subshowid".equals(fieldName)) {
                        fieldValue = id;
                    }

                    hrmFieldBean = new HrmFieldBean();
                    hrmFieldBean.setFieldid(fieldId);
                    hrmFieldBean.setFieldname(fieldName);
                    hrmFieldBean.setFieldlabel(fieldLabel);
                    hrmFieldBean.setFieldhtmltype(fieldHtmlType);
                    hrmFieldBean.setType(type);
                    hrmFieldBean.setIsFormField(true);
                    hrmFieldBean.setFieldvalue(fieldValue);
                    hrmFieldBean.setDmlurl(dmlUrl);
                    hrmFieldBean.setIssystem("1");
                    searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user);
                    if (searchConditionItem.getBrowserConditionParam() != null) {
                        searchConditionItem.getBrowserConditionParam().setViewAttr(viewAttr);
                    }
                    if ("showorder".equals(fieldName)) {
                        searchConditionItem.setPrecision(2);
                    }

                    if ("6".equals(fieldHtmlType)) {//附件
                        Map<String, Object> otherParams1 = new HashMap<>();
                        otherParams1.put("showOrder", false);
                        searchConditionItem.setOtherParams(otherParams1);
                    }

                    searchConditionItem.setViewAttr(viewAttr);
                    itemList.add(searchConditionItem);
                }

                int operateLevel;
                ManageDetachComInfo manageDetachComInfo = new ManageDetachComInfo();
                boolean hrmDetachAble = manageDetachComInfo.isUseHrmManageDetach();
                if (hrmDetachAble) {
                    CheckSubCompanyRight checkSubCompanyRight = new CheckSubCompanyRight();
                    operateLevel = checkSubCompanyRight.ChkComRightByUserRightCompanyId(user.getUID(), "HrmSubCompanyEdit:Edit", Integer.parseInt(id));
                } else {
                    operateLevel = 2;
                }

                if (tmp == 0 && HrmUserVarify.checkUserRight("HrmSubCompanyEdit:Edit", user) && operateLevel > 0) {
                    int resourceNum = 0;

                    String sql;
                    RecordSet rs = new RecordSet();
                    sql = "SELECT COUNT(*) FROM hrmresource WHERE subcompanyid1 = " + id + " and ( status =0 or status = 1 or status = 2 or status = 3)";
                    rs.execute(sql);
                    if (rs.next()) {
                        resourceNum = rs.getInt(1);
                    }
                    //4:解聘 5:离职 6:退休 7:无效
                    int resourceNum1 = 0;
                    sql = "SELECT COUNT(*) FROM hrmresource WHERE subcompanyid1 = " + id + " and status in(4,5,6,7)";
                    rs.execute(sql);
                    if (rs.next()) {
                        resourceNum1 = rs.getInt(1);
                    }
                    hrmFieldBean = new HrmFieldBean();
                    hrmFieldBean.setFieldname("subcomResourceInfo");
                    hrmFieldBean.setFieldlabel("382428");
                    hrmFieldBean.setFieldhtmltype("1");
                    hrmFieldBean.setType("1");
                    hrmFieldBean.setIsFormField(true);
                    hrmFieldBean.setFieldvalue(resourceNum + "/" + resourceNum1);
                    hrmFieldBean.setDmlurl("");
                    searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user);
                    searchConditionItem.setViewAttr(viewAttr);
                    itemList.add(searchConditionItem);
                }
                groupList.add(new SearchConditionGroup(SystemEnv.getHtmlLabelNames(groupLabel, user.getLanguage()), true, itemList));
            }
        }
        HashMap<String, Object> buttonsMap = new HashMap<>();
        buttonsMap.put("hasEdit", true);
        buttonsMap.put("hasSave", true);

        retMap.put("id", id);
        retMap.put("conditions", groupList);
        retMap.put("buttons", buttonsMap);
        List<TopTab> topTabs = new ArrayList<>();
        topTabs.add(TopTab.builder().color("#000000").groupId("4").showcount(false).title("分部信息").viewCondition("4").build());
        retMap.put("tabInfo", topTabs);

        Map<String, Object> apiDatas = new HashMap<>();

        apiDatas.put("result", retMap);
        return apiDatas;
    }


    @Override
    public Map<String, Object> getCompSaveForm(Map<String, Object> params) {
        HasRightUtil.hasRight(user, RIGHT_NAME, false);
        Map<String, Object> apiDatas = new HashMap<>();
        apiDatas.put("condition", getCompanyConditionGroups(false, params));
        return apiDatas;

    }

    @Override
    public List<SearchConditionGroup> getMoveForm() {
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        List<SearchConditionItem> condition = new ArrayList<>();
        SearchConditionItem compBrowserItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "转移到", "164", "company", "compBrowser");
        compBrowserItem.setHelpfulTip("在不选择分部情况下,默认转移到集团下一级分部！！！");
        condition.add(compBrowserItem);
        addGroups.add(new SearchConditionGroup("", true, condition));
        return addGroups;
    }

    @Override
    public int moveCompany(DepartmentMoveParam moveParam) {
        Integer companyId = moveParam.getId();
        Integer targetCompanyId = moveParam.getCompany();
        // 判断目标分部是否为它本身以及子元素
        Set<Integer> disableIds = new HashSet<>();
        disableIds.add(companyId);

        List<CompPO> compPOS = getCompMapper().listChild(Collections.singletonList(companyId));
        if (CollectionUtils.isNotEmpty(compPOS)) {
            addDisableIds(disableIds, compPOS);
        }
        OrganizationAssert.isFalse(disableIds.contains(targetCompanyId), "请勿选择当前分部本身及其子分部");

        Map<String, Object> map = new HashMap<>();
        map.put("id", companyId.toString());
        if (null == targetCompanyId) {
            map.put("supsubcomid", "0");
        } else {
            map.put("supsubcomid", targetCompanyId.toString());
        }
        new OrganizationSyncEc(user, LogModuleNameEnum.COMPANY, OperateTypeEnum.UPDATE, map).sync();
        return companyId;
    }


    /**
     * 是否为搜索查询
     *
     * @param companyPO
     * @return
     */
    private boolean isFilter(CompPO companyPO) {
        return StringUtils.isNotBlank(companyPO.getSubCompanyCode()) || StringUtils.isNotBlank(companyPO.getSubCompanyDesc()) || StringUtils.isNotBlank(companyPO.getSubCompanyName()) || null != companyPO.getSupSubComId();
    }


    /**
     * 添加子元素ID
     *
     * @param disableIds
     * @param compPOS
     */
    private void addDisableIds(Set<Integer> disableIds, List<CompPO> compPOS) {
        for (CompPO compPO : compPOS) {
            disableIds.add(compPO.getId());
            List<CompPO> childCompPOS = getCompMapper().listChild(Collections.singletonList(compPO.getId()));
            addDisableIds(disableIds, childCompPOS);
        }
    }

    private List<SearchConditionGroup> getCompanyConditionGroups(Boolean showAll, Map<String, Object> params) {
        String id = Util.null2String(params.get("id"));
        int viewAttr = Util.getIntValue(Util.null2String(params.get("viewattr")), 1);

        String addType = Util.null2String(params.get("addType"));
        SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
        String supSubComId = "";
        if ("sibling".equals(addType)) {
            supSubComId = subCompanyComInfo.getSupsubcomid(id);
        } else if ("child".equals(addType)) {
            supSubComId = id;
        }
        if (StringUtils.isNotBlank(addType)) {
            id = "";
        }

        HrmFieldGroupComInfo HrmFieldGroupComInfo = new HrmFieldGroupComInfo();
        HrmFieldComInfo HrmFieldComInfo = new HrmFieldComInfo();
        HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo();


        HrmDeptFieldManagerE9 hfm;
        try {
            hfm = new HrmDeptFieldManagerE9(4);
        } catch (Exception e) {
            throw new OrganizationRunTimeException("");
        }
        hfm.isReturnDecryptData(true);
        hfm.getCustomData(Util.getIntValue(id));
        List lsGroup = hfm.getLsGroup();
        List<SearchConditionGroup> groupList = new ArrayList<>();
        int lsSize = 1;
        if (showAll && lsGroup != null) {
            lsSize = lsGroup.size();
        }
        for (int tmp = 0; tmp < lsSize; tmp++) {
            String groupId = (String) lsGroup.get(tmp);
            List lsField = hfm.getLsField(groupId);

            boolean groupHide = lsField.size() == 0 || hfm.getGroupCount(lsField) == 0 || !"1".equals(Util.null2String(HrmFieldGroupComInfo.getIsShow(groupId)));
            String groupLabel = HrmFieldGroupComInfo.getLabel(groupId);
            List<SearchConditionItem> itemList = new ArrayList<>();
            for (Object o : lsField) {
                String fieldId = (String) o;
                String fieldName = HrmFieldComInfo.getFieldname(fieldId);
                String isUse = HrmFieldComInfo.getIsused(fieldId);
                String isSystem = HrmFieldComInfo.getIssystem(fieldId);
                if (!"1".equals(isUse)) {
                    continue;
                }
                int tmpViewAttr = viewAttr;
                String rules = "";
                String fieldLabel = HrmFieldComInfo.getLabel(fieldId);
                String fieldHtmlType = HrmFieldComInfo.getFieldhtmltype(fieldId);
                String type = HrmFieldComInfo.getFieldType(fieldId);
                String dmlUrl = Util.null2String(HrmFieldComInfo.getFieldDmlurl(fieldId));
                String fieldValue = "";
                if (StringUtils.isBlank(addType)) {
                    if ("1".equals(isSystem)) {
                        fieldValue = hfm.getData(fieldName);
                    } else {
                        fieldValue = hfm.getData("hrmsubcompanydefined", fieldName);
                    }
                }

                if (!groupHide && tmpViewAttr == 2 && "1".equals(HrmFieldComInfo.getIsmand(fieldId))) {
                    tmpViewAttr = 3;
                    if ("1".equals(fieldHtmlType) && "2".equals(type)) {
                        rules = "required|integer";
                    } else {
                        rules = "required|string";
                    }
                }

                if ("84".equals(fieldId)) {
                    if (user.getUID() != 1) {
                        continue;
                    }
                    fieldValue = "0".equals(fieldValue) ? "" : fieldValue;
                }
                if (supSubComId.length() > 0 && "supsubcomid".equals(fieldName)) {
                    fieldValue = supSubComId;
                }

                if ("subshowid".equals(fieldName)) {
                    if (StringUtils.isNotBlank(addType)) {
                        continue;
                    } else {
                        fieldValue = id;
                        tmpViewAttr = 1;
                    }
                }

                HrmFieldBean hrmFieldBean = new HrmFieldBean();
                hrmFieldBean.setFieldid(fieldId);
                hrmFieldBean.setFieldname(fieldName);
                hrmFieldBean.setFieldlabel(fieldLabel);
                hrmFieldBean.setFieldhtmltype(fieldHtmlType);
                hrmFieldBean.setType(type);
                hrmFieldBean.setIsFormField(true);
                hrmFieldBean.setFieldvalue(fieldValue);
                hrmFieldBean.setDmlurl(dmlUrl);
                hrmFieldBean.setViewAttr(tmpViewAttr);
                hrmFieldBean.setRules(rules);
                hrmFieldBean.setIssystem("1");
                if ("supsubcomid".equals(hrmFieldBean.getFieldname())) {
                    hrmFieldBean.setHideVirtualOrg(true);
                }
                if ("subcompanycode".equals(hrmFieldBean.getFieldname())) {
                    hrmFieldBean.setMultilang(false);
                }
                SearchConditionItem searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user);
                if (searchConditionItem != null) {
                    searchConditionItem.setLabelcol(8);
                    searchConditionItem.setFieldcol(16);
                    if ("showorder".equals(hrmFieldBean.getFieldname())) {
                        searchConditionItem.setPrecision(2);
                    }
                    if ("subshowid".equals(fieldName)) {
                        Map<String, Object> otherParams = new HashMap<>();
                        otherParams.put("hasBorder", true);
                        searchConditionItem.setOtherParams(otherParams);
                    }

                    if ("6".equals(fieldHtmlType)) {//附件
                        Map<String, Object> otherParams1 = new HashMap<>();
                        otherParams1.put("showOrder", false);
                        searchConditionItem.setOtherParams(otherParams1);
                    }
                    itemList.add(searchConditionItem);

                }
            }
            groupList.add(new SearchConditionGroup(SystemEnv.getHtmlLabelNames(groupLabel, user.getLanguage()), true, itemList));

        }
        return groupList;
    }
}
