package com.engine.organization.service.impl;

import com.api.browser.bean.SearchConditionGroup;
import com.api.browser.bean.SearchConditionItem;
import com.cloudstore.eccom.result.WeaResultMsg;
import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.organization.component.OrganizationWeaTable;
import com.engine.organization.entity.DeleteParam;
import com.engine.organization.entity.company.bo.CompBO;
import com.engine.organization.entity.company.po.CompPO;
import com.engine.organization.entity.department.bo.DepartmentBO;
import com.engine.organization.entity.department.po.DepartmentPO;
import com.engine.organization.entity.extend.po.ExtendTitlePO;
import com.engine.organization.entity.hrmresource.param.HrmResourceSearchParam;
import com.engine.organization.entity.hrmresource.vo.HrmResourceVO;
import com.engine.organization.entity.job.bo.JobBO;
import com.engine.organization.entity.job.po.JobPO;
import com.engine.organization.entity.searchtree.SearchTree;
import com.engine.organization.entity.searchtree.SearchTreeParams;
import com.engine.organization.mapper.comp.CompMapper;
import com.engine.organization.mapper.department.DepartmentMapper;
import com.engine.organization.mapper.extend.ExtendTitleMapper;
import com.engine.organization.mapper.job.JobMapper;
import com.engine.organization.service.ExtService;
import com.engine.organization.service.HrmResourceService;
import com.engine.organization.util.MenuBtn;
import com.engine.organization.util.OrganizationAssert;
import com.engine.organization.util.OrganizationFormItemUtil;
import com.engine.organization.util.db.DBType;
import com.engine.organization.util.db.MapperProxyFactory;
import com.engine.organization.util.tree.SearchTreeUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.StringUtil;
import weaver.general.Util;
import weaver.hrm.User;

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

/**
 * @author:dxfeng
 * @createTime: 2022/06/20
 * @version: 1.0
 */
public class HrmResourceServiceImpl extends Service implements HrmResourceService {
    /**
     * 左侧树 类型表示
     * <p>
     * 0：集团
     * 1：分部
     * 2：部门
     * 3：岗位
     */
    private static final String TYPE_COMP = "1";
    private static final String TYPE_DEPT = "2";
    private static final String TYPE_JOB = "3";

    private static final Long GROUP_ID = 4L;

    /**
     * 分组类型
     * 1：分部
     * 2：部门
     * 3：岗位
     * 4：人员
     */
    private static final String EXTEND_TYPE = "4";

    /**
     * 主表表名
     */
    private static final String JCL_ORG_HRM = "JCL_ORG_HRMRESOURCE";
    /**
     * 主表拓展表
     */
    private static final String JCL_ORG_HRMEXT = "JCL_ORG_HRMRESOURCEEXT";
    /**
     * 明细表拓展表
     */
    private static final String JCL_ORG_HRMEXT_DT1 = "JCL_ORG_HRMRESOURCEEXT_DT1";

    private DepartmentMapper getDepartmentMapper() {
        return MapperProxyFactory.getProxy(DepartmentMapper.class);
    }

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

    private JobMapper getJobMapper() {
        return MapperProxyFactory.getProxy(JobMapper.class);
    }

    private ExtendTitleMapper getExtendTitleMapper() {
        return MapperProxyFactory.getProxy(ExtendTitleMapper.class);
    }

    private ExtService getExtService(User user) {
        return ServiceUtil.getService(ExtServiceImpl.class, user);
    }

    @Override
    public Map<String, Object> getSearchTree(SearchTreeParams params) {
        String keyword = params.getKeyword();
        String id = params.getId();
        String type = Util.null2String(params.getType());
        List<SearchTree> treeList = getFilterCompany(id, type, keyword);
        return SearchTreeUtil.getSearchTree(type, treeList);
    }

    @Override
    public Map<String, Object> listPage(HrmResourceSearchParam params) {
        Map<String, Object> resultMap = new HashMap<>();
        OrganizationWeaTable<HrmResourceVO> table = new OrganizationWeaTable<>(user, HrmResourceVO.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 Map<String, Object> getSaveForm() {
        Map<String, Object> apiDatas = new HashMap<>();
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        List<ExtendTitlePO> extendTitles = getExtendTitleMapper().getTitlesByGroupID(GROUP_ID);
        if (CollectionUtils.isNotEmpty(extendTitles)) {
            for (ExtendTitlePO extendTitle : extendTitles) {
                addGroups.add(new SearchConditionGroup(extendTitle.getTitle(), true, getExtService(user).getExtSaveForm(user, EXTEND_TYPE + "", JCL_ORG_HRM, 2, extendTitle.getId() + "", null, null)));
            }
        }
        apiDatas.put("condition", addGroups);
        return apiDatas;
    }

    @Override
    public Long saveBaseForm(Map<String, Object> params) {
        return getExtService(user).updateExtForm(user, EXTEND_TYPE, JCL_ORG_HRM, params, "", null);
    }

    @Override
    public Map<String, Object> getBaseForm(Map<String, Object> params) {
        OrganizationAssert.notNull(params.get("viewAttr"), "请标识操作类型");
        // 2编辑 1查看
        int viewAttr = Integer.parseInt((String) params.get("viewAttr"));
        long id = Long.parseLong((String) params.get("id"));
        String groupId = (String) params.get("viewCondition");

        HashMap<String, Object> buttonsMap = new HashMap<>();
        buttonsMap.put("hasEdit", true);
        buttonsMap.put("hasSave", true);

        List<SearchConditionGroup> addGroups = new ArrayList<>();
        if ("0".equals(groupId)) {
            groupId = GROUP_ID.toString();
        }
        List<ExtendTitlePO> extendTitles = getExtendTitleMapper().getTitlesByGroupID(Long.parseLong(groupId));

        if (CollectionUtils.isNotEmpty(extendTitles)) {
            for (ExtendTitlePO extendTitle : extendTitles) {
                addGroups.add(new SearchConditionGroup(extendTitle.getTitle(), true, getExtService(user).getExtForm(user, EXTEND_TYPE + "", GROUP_ID.equals(Long.parseLong(groupId)) ? JCL_ORG_HRM : JCL_ORG_HRMEXT, viewAttr, id, extendTitle.getId() + "", "")));
            }
        }

        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("buttons", buttonsMap);
        resultMap.put("conditions", addGroups);
        resultMap.put("id", id);
        // 拓展页面分组
        resultMap.put("tabInfo", getExtService(user).getTabInfo(EXTEND_TYPE, JCL_ORG_HRMEXT));
        // 处理明细表
        resultMap.put("tables", getExtService(user).getExtendTables(user, EXTEND_TYPE, Long.parseLong(groupId), JCL_ORG_HRMEXT_DT1, id, viewAttr, false));
        Map<String, Object> apiDatas = new HashMap<>();

        apiDatas.put("result", resultMap);

        return apiDatas;
    }

    @Override
    public int updateForm(Map<String, Object> params) {
        Long id = Long.parseLong((String) params.get("id"));
        String groupId = (String) params.get("viewCondition");
        if ("0".equals(groupId)) {
            groupId = GROUP_ID.toString();
        }
        int updateCount = 0;
        // 更新主表数据
        updateCount += getExtService(user).updateExtForm(user, EXTEND_TYPE, JCL_ORG_HRM, params, "", id);
        // 更新主表拓展表
        updateCount += getExtService(user).updateExtForm(user, EXTEND_TYPE, JCL_ORG_HRMEXT, params, groupId, id);
        //更新明细表
        getExtService(user).updateExtDT(user, EXTEND_TYPE, JCL_ORG_HRMEXT_DT1, params, id);

        return updateCount;
    }

    @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 lastNameItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "姓名", "lastName");
        SearchConditionItem managerIdItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "直接上级", "managerId");
        SearchConditionItem companyIdItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "分部", "161", "companyId", "compBrowser");
        SearchConditionItem departmentIdItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "部门", "161", "departmentId", "deptBrowser");
        SearchConditionItem telephoneItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "办公电话", "telephone");
        SearchConditionItem mobileItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "移动电话", "mobile");
        SearchConditionItem mobileCallItem = OrganizationFormItemUtil.inputItem(user, 2, 16, 2, 50, "其他电话", "mobileCall");
        SearchConditionItem jobTitleItem = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, "岗位", "161", "jobTitle", "jobBrowser");

        conditionItems.add(lastNameItem);
        conditionItems.add(managerIdItem);
        conditionItems.add(companyIdItem);
        conditionItems.add(departmentIdItem);
        conditionItems.add(telephoneItem);
        conditionItems.add(mobileItem);
        conditionItems.add(mobileCallItem);
        conditionItems.add(jobTitleItem);

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

    @Override
    public Map<String, Object> getHasRight() {
        Map<String, Object> btnDatas = new HashMap<>();
        ArrayList<MenuBtn> topMenuList = new ArrayList<>();
        ArrayList<MenuBtn> rightMenuList = new ArrayList<>();
        topMenuList.add(MenuBtn.builder().isBatch("1").isTop("1").menuFun("new").menuIcon("icon-coms-New-Flow").menuName("新建人员").type("BTN_Addnew").build());
        topMenuList.add(MenuBtn.builder().isBatch("1").isTop("1").menuFun("import").menuIcon("icon-coms-leading-in").menuName("导入人员").type("BTN_Import").build());
        topMenuList.add(MenuBtn.builder().isBatch("1").isTop("1").menuFun("export").menuIcon("icon-coms02-coms2-export").menuName("全部导出").type("BTN_Export").build());
        btnDatas.put("topMenu", topMenuList);
        rightMenuList.add(MenuBtn.builder().isBatch("1").isTop("1").menuFun("new").menuIcon("icon-coms-New-Flow").menuName("新建人员").type("BTN_Addnew").build());
        rightMenuList.add(MenuBtn.builder().isBatch("1").isTop("1").menuFun("import").menuIcon("icon-coms-leading-in").menuName("导入人员").type("BTN_Import").build());
        rightMenuList.add(MenuBtn.builder().isBatch("1").isTop("1").menuFun("export").menuIcon("icon-coms02-coms2-export").menuName("全部导出").type("BTN_Export").build());
        rightMenuList.add(MenuBtn.builder().isBatch("0").isTop("0").menuFun("custom").menuIcon("icon-coms-task-list").menuName("显示列定制").type("BTN_COLUMN").build());
        btnDatas.put("rightMenu", rightMenuList);
        return btnDatas;
    }

    /**
     * 查询条件
     *
     * @param params
     * @return
     */
    private String buildSqlWhere(HrmResourceSearchParam params) {
        DBType dbType = DBType.get(new RecordSet().getDBType());
        String sqlWhere = " where t.delete_type ='0' ";
        String lastName = params.getLastName();
        if (StringUtils.isNotBlank(lastName)) {
            sqlWhere += " AND t.last_name " + dbType.like(lastName);
        }
        Long managerId = params.getManagerId();
        if (null != managerId) {
            sqlWhere += " AND t.manager_id = '" + managerId + "'";
        }
        Long companyId = params.getCompanyId();
        if (null != companyId) {
            sqlWhere += " AND t.company_id = '" + companyId + "'";
        }
        Long departmentId = params.getDepartmentId();
        if (null != departmentId) {
            sqlWhere += " AND t.department_id = '" + departmentId + "'";
        }
        String telephone = params.getTelephone();
        if (StringUtils.isNotBlank(telephone)) {
            sqlWhere += " AND t.telephone " + dbType.like(telephone);
        }
        String mobile = params.getMobile();
        if (StringUtils.isNotBlank(mobile)) {
            sqlWhere += " AND t.mobile " + dbType.like(mobile);
        }
        String mobileCall = params.getMobileCall();
        if (StringUtils.isNotBlank(mobileCall)) {
            sqlWhere += " AND t.mobile_call " + dbType.like(mobileCall);
        }
        Long jobTitle = params.getJobTitle();
        if (null != jobTitle) {
            sqlWhere += " AND t.job_title = '" + jobTitle + "'";
        }

        return sqlWhere;
    }

    public List<SearchTree> getFilterCompany(String id, String type, String keyword) {
        List<SearchTree> searchTree = new ArrayList<>();
        // 通过分部、公司 组装数据
        if (StringUtil.isEmpty(id) || TYPE_COMP.equals(type)) {
            Long parentCompId = StringUtil.isEmpty(id) ? null : Long.parseLong(id);
            DepartmentPO departmentBuild = DepartmentPO.builder().deptName(keyword).parentComp(parentCompId).build();
            CompPO compBuild = CompPO.builder().compName(keyword).parentCompany(parentCompId).build();
            // 所属分部下的岗位
            JobPO jobBuild = JobPO.builder().jobName(keyword).parentComp(parentCompId).build();
            searchTree = buildTreeByCompAndDept(departmentBuild, compBuild, jobBuild);
        } else if (TYPE_DEPT.equals(type)) {
            Long parentDeptId = Long.parseLong(id);
            DepartmentPO departmentBuild = DepartmentPO.builder().deptName(keyword).parentDept(parentDeptId).build();
            // 所属分部下的岗位
            JobPO jobBuild = JobPO.builder().jobName(keyword).parentDept(parentDeptId).build();
            searchTree = buildTreeByDeptAndJob(departmentBuild, jobBuild);

        } else if (TYPE_JOB.equals(type)) {
            // 查询部门信息
            List<JobPO> filterDeparts = getJobMapper().listPOsByFilter(JobPO.builder().jobName(keyword).parentJob(Long.parseLong(id)).build());
            Set<JobPO> builderJobs = new HashSet<>();
            for (JobPO departmentPO : filterDeparts) {
                buildParentJobs(departmentPO, builderJobs);
            }
            searchTree = SearchTreeUtil.builderTreeMode(JobBO.buildSetToSearchTree(builderJobs));
        }
        return searchTree;
    }

    /**
     * 分部、部门 组装左侧树
     *
     * @param departmentBuild
     * @param compBuild
     * @param jobBuild
     * @return
     */
    private List<SearchTree> buildTreeByCompAndDept(DepartmentPO departmentBuild, CompPO compBuild, JobPO jobBuild) {
        List<JobPO> jobPOS = getJobMapper().listPOsByFilter(jobBuild);
        List<DepartmentPO> filterDeparts = getDepartmentMapper().listByFilter(departmentBuild, "show_order");
        // 添加父级岗位
        Set<JobPO> builderJobs = new HashSet<>();
        for (JobPO jobPO : jobPOS) {
            buildParentJobs(jobPO, builderJobs);
        }
        // 添加岗位的上级部门或分部
        List<SearchTree> jobTrees = SearchTreeUtil.builderTreeMode(JobBO.buildSetToSearchTree(builderJobs));
        String parentDeptS = jobTrees.stream().map(SearchTree::getParentComp).collect(Collectors.joining(","));
        if (!StringUtil.isEmpty(parentDeptS)) {
            List<DepartmentPO> compsByIds = getDepartmentMapper().getDeptsByIds(DeleteParam.builder().ids(parentDeptS).build().getIds());
            if (CollectionUtils.isNotEmpty(compsByIds)) {
                filterDeparts.addAll(compsByIds);
            }
        }

        // 查询分部信息
        List<CompPO> filterComps = getCompMapper().listByFilter(compBuild, "show_order");
        Set<DepartmentPO> builderDeparts = new HashSet<>();
        for (DepartmentPO departmentPO : filterDeparts) {
            buildParentDepts(departmentPO, builderDeparts);
        }
        List<SearchTree> deptTrees = SearchTreeUtil.builderTreeMode(DepartmentBO.buildSetToSearchTree(builderDeparts, false));
        // 添加部门的上级分部
        String parentCompS = deptTrees.stream().map(SearchTree::getParentComp).collect(Collectors.joining(","));
        if (!StringUtil.isEmpty(parentCompS)) {
            List<CompPO> compsByIds = getCompMapper().getCompsByIds(DeleteParam.builder().ids(parentCompS).build().getIds());
            if (CollectionUtils.isNotEmpty(compsByIds)) {
                filterComps.addAll(compsByIds);
            }
        }
        Set<CompPO> builderComps = new HashSet<>();
        for (CompPO compPO : filterComps) {
            buildParentComps(compPO, builderComps);
        }
        List<SearchTree> searchTrees = SearchTreeUtil.builderTreeMode(deptTrees, jobTrees);
        return SearchTreeUtil.builderTreeMode(CompBO.buildSetToSearchTree(builderComps), searchTrees);
    }

    private List<SearchTree> buildTreeByDeptAndJob(DepartmentPO departmentBuild, JobPO jobBuild) {
        List<JobPO> jobPOS = getJobMapper().listPOsByFilter(jobBuild);
        List<DepartmentPO> filterDeparts = getDepartmentMapper().listByFilter(departmentBuild, "show_order");
        // 添加父级岗位
        Set<JobPO> builderJobs = new HashSet<>();
        for (JobPO jobPO : jobPOS) {
            buildParentJobs(jobPO, builderJobs);
        }
        // 添加岗位的上级部门或分部
        List<SearchTree> jobTrees = SearchTreeUtil.builderTreeMode(JobBO.buildSetToSearchTree(builderJobs));
        String parentDeptS = jobTrees.stream().map(SearchTree::getParentComp).collect(Collectors.joining(","));
        if (!StringUtil.isEmpty(parentDeptS)) {
            List<DepartmentPO> compsByIds = getDepartmentMapper().getDeptsByIds(DeleteParam.builder().ids(parentDeptS).build().getIds());
            if (CollectionUtils.isNotEmpty(compsByIds)) {
                filterDeparts.addAll(compsByIds);
            }
        }

        // 查询分部信息
        Set<DepartmentPO> builderDeparts = new HashSet<>();
        for (DepartmentPO departmentPO : filterDeparts) {
            buildParentDepts(departmentPO, builderDeparts);
        }
        return SearchTreeUtil.builderTreeMode(DepartmentBO.buildSetToSearchTree(builderDeparts, false), jobTrees);
    }

    private void buildParentJobs(JobPO jobPO, Set<JobPO> builderJobs) {
        builderJobs.add(jobPO);
        if (SearchTreeUtil.isTop(jobPO.getParentJob())) {
            return;
        }
        JobPO parentJob = getJobMapper().getJobById(jobPO.getParentJob());
        if (null != parentJob) {
            buildParentJobs(parentJob, builderJobs);
        }
    }

    /**
     * 添加查询元素的父级元素
     *
     * @param departmentPO
     * @param builderDeparts
     */
    private void buildParentDepts(DepartmentPO departmentPO, Set<DepartmentPO> builderDeparts) {
        builderDeparts.add(departmentPO);
        if (SearchTreeUtil.isTop(departmentPO.getParentDept())) {
            return;
        }
        DepartmentPO parentDept = getDepartmentMapper().getDeptById(departmentPO.getParentDept());
        if (null != parentDept) {
            buildParentDepts(parentDept, builderDeparts);
        }
    }

    /**
     * 添加查询元素的父级元素
     *
     * @param compPO
     * @param builderComps
     */
    private void buildParentComps(CompPO compPO, Set<CompPO> builderComps) {
        builderComps.add(compPO);
        if (SearchTreeUtil.isTop(compPO.getParentCompany())) {
            return;
        }
        CompPO parentComp = getCompMapper().listById(compPO.getParentCompany());
        if (null != parentComp) {
            buildParentComps(parentComp, builderComps);
        }
    }
}
