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.api.browser.bean.SearchConditionOption;
import com.cloudstore.eccom.result.WeaResultMsg;
import com.engine.common.service.HrmCommonService;
import com.engine.common.service.impl.HrmCommonServiceImpl;
import com.engine.core.impl.Service;
import com.engine.organization.component.OrganizationWeaTable;
import com.engine.organization.entity.DeleteParam;
import com.engine.organization.entity.detach.param.ManagerDetachParam;
import com.engine.organization.entity.detach.po.ManagerDetachPO;
import com.engine.organization.entity.detach.vo.ManagerDetachVO;
import com.engine.organization.mapper.detach.ManagerDetachMapper;
import com.engine.organization.mapper.employee.EmployeeMapper;
import com.engine.organization.mapper.hrmresource.SystemDataMapper;
import com.engine.organization.service.ManagerDetachService;
import com.engine.organization.util.HasRightUtil;
import com.engine.organization.util.OrganizationFormItemUtil;
import com.engine.organization.util.db.DBType;
import com.engine.organization.util.db.MapperProxyFactory;
import com.weaver.file.ConfigOperator;
import com.weaver.general.BaseBean;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.roles.RolesComInfo;
import weaver.systeminfo.SystemEnv;

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

/**
 * @Author weaver_cl
 * @Description:
 * @Date 2022/10/21
 * @Version V1.0
 **/
public class ManagerDetachServiceImpl extends Service implements ManagerDetachService {


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

    public ManagerDetachMapper getMangeDetachMapper() {
        return MapperProxyFactory.getProxy(ManagerDetachMapper.class);
    }

    public EmployeeMapper getEmployeeMapper() {
        return MapperProxyFactory.getProxy(EmployeeMapper.class);
    }

    public SystemDataMapper getSystemDataMapper() {
        return MapperProxyFactory.getProxy(SystemDataMapper.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;
        }
        String detach = new BaseBean().getPropValue("hrmOrganization", "detach");
        resultMap.put("isDetach", detach);
        OrganizationWeaTable<ManagerDetachVO> table = new OrganizationWeaTable<>(user, ManagerDetachVO.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> getForm(Integer id) {
        Map<String, Object> apiDatas = new HashMap<>();
        RolesComInfo rolesComInfo = new RolesComInfo();
        List<SearchConditionItem> selectItems = new ArrayList<>();
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        List<SearchConditionOption> selectOption = new ArrayList<>();
        SearchConditionOption pOption = new SearchConditionOption("0", SystemEnv.getHtmlLabelName(547205,user.getLanguage()));
        SearchConditionOption rOption = new SearchConditionOption("1", SystemEnv.getHtmlLabelName(547388,user.getLanguage()));
        selectOption.add(pOption);
        selectOption.add(rOption);

        List<SearchConditionOption> selectOptions = new ArrayList<>();
        SearchConditionOption moduleOption = new SearchConditionOption("0", SystemEnv.getHtmlLabelName(547409,user.getLanguage()), true);
        selectOptions.add(moduleOption);
        SearchConditionItem ecManager = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, 547405, "1", "ecManager", "");
        SearchConditionItem roleId = OrganizationFormItemUtil.browserItem(user, 2, 16, 2, false, 547388, "267", "roleId", "");

        SearchConditionItem ecRolelevel = OrganizationFormItemUtil.browserItem(user, 2, 16, 3, false, 547407, "194", "ecRolelevel", "");
        ecRolelevel.setRules("required|string");
        SearchConditionItem module = OrganizationFormItemUtil.selectItem(user, selectOptions, 2, 16, 6, false, 547408, "module");
        module.setViewAttr(1);
        module.setDetailtype(2);
        module.setHasBorder(true);
        SearchConditionItem managerType = OrganizationFormItemUtil.selectItem(user, selectOption, 2, 16, 6, false, 513540, "managerType");
        managerType.setViewAttr(3);
        managerType.setRules("required|string");
        selectItems.add(managerType);

        if (id != null) {
            ManagerDetachPO detachById = getMangeDetachMapper().getDetachById(id);
            managerType.setValue(String.valueOf(detachById.getManagerType()));
            managerType.setViewAttr(1);
            if (detachById.getManagerType() == 0){
                BrowserBean manager = ecManager.getBrowserConditionParam();
                manager.setReplaceDatas(getEmployeeMapper().getBrowserDatas(DeleteParam.builder().ids(String.valueOf(detachById.getEcManager())).build().getIds()));
                ecManager.setBrowserConditionParam(manager);
                selectItems.add(ecManager);
            }else {
                BrowserBean role = roleId.getBrowserConditionParam();
                List<Map<String, Object>> rep = new ArrayList<>();
                Integer rolesId = detachById.getEcManager();
                String rolesname = rolesComInfo.getRolesRemark(String.valueOf(rolesId));
                rep.add(new HashMap<String,Object>(2){{put("name",rolesname);}});
                rep.add(new HashMap<String,Object>(2){{put("id",rolesId);}});
                role.setReplaceDatas(rep);
                roleId.setBrowserConditionParam(role);
                selectItems.add(roleId);
            }
            BrowserBean roleLevel = ecRolelevel.getBrowserConditionParam();
            roleLevel.setReplaceDatas(getSystemDataMapper().getBrowserDatas(DeleteParam.builder().ids(String.valueOf(detachById.getEcRolelevel())).build().getIds()));
            ecRolelevel.setBrowserConditionParam(roleLevel);
        }else {
            selectItems.add(ecManager);
            selectItems.add(roleId);
        }

        selectItems.add(ecRolelevel);
        selectItems.add(module);

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

    @Override
    public int deleteByIds(Collection<Long> ids) {
        return getMangeDetachMapper().deleteByIds(ids);
    }

    @Override
    public int save(ManagerDetachParam param) {
        Integer ecManager = "0".equals(String.valueOf(param.getManagerType())) ? param.getEcManager() : param.getRoleId();
        String noRepeatRoleLevel = param.getEcRolelevel();
        // 判断有无重复数据
        List<ManagerDetachPO> detachListById = getMangeDetachMapper().getDetachListById(ecManager,param.getManagerType());
        if (CollectionUtils.isNotEmpty(detachListById)) {
            Set<String> noRepeatRoleLevels = getNoRepeatRoleLevels(detachListById, param.getId());
            noRepeatRoleLevels.addAll(Arrays.asList(noRepeatRoleLevel.split(",")));
            noRepeatRoleLevel = StringUtils.join(noRepeatRoleLevels, ",");
            List<Long> collect = detachListById.stream().map(ManagerDetachPO::getId).map(Long::valueOf).collect(Collectors.toList());
            getMangeDetachMapper().deleteByIds(collect);
        }
        ManagerDetachPO managerDetachPO = ManagerDetachPO.builder()
                .managerType(param.getManagerType())
                .ecManager(ecManager)
                .jclManager(ecManager)
                .ecRolelevel(noRepeatRoleLevel)
                .jclRolelevel(noRepeatRoleLevel)
                .manageModule("组织管理")
                .creator((long) user.getUID())
                .deleteType(0)
                .createTime(new Date())
                .updateTime(new Date())
                .build();
        getMangeDetachMapper().insertIgnoreNull(managerDetachPO);
        return managerDetachPO.getId();
    }

    @Override
    public int updateDetach(ManagerDetachParam param) {
        Integer ecManager = "0".equals(String.valueOf(param.getManagerType())) ? param.getEcManager() : param.getRoleId();
        String noRepeatRoleLevel = param.getEcRolelevel();
        // 判断有无重复数据
        List<ManagerDetachPO> detachListById = getMangeDetachMapper().getDetachListById(ecManager,param.getManagerType());
        if (CollectionUtils.isNotEmpty(detachListById)) {
            Set<String> noRepeatRoleLevels = getNoRepeatRoleLevels(detachListById,param.getId());
            noRepeatRoleLevels.addAll(Arrays.asList(noRepeatRoleLevel.split(",")));
            noRepeatRoleLevel = StringUtils.join(noRepeatRoleLevels, ",");
            List<Long> collect = detachListById.stream().map(ManagerDetachPO::getId).map(Long::valueOf).collect(Collectors.toList());
            collect.remove(Long.valueOf(param.getId()));
            if(CollectionUtils.isNotEmpty(collect)) {
                getMangeDetachMapper().deleteByIds(collect);
            }
        }
        ManagerDetachPO managerDetachPO = ManagerDetachPO.builder()
                .id(param.getId())
                .ecManager(ecManager)
                .ecRolelevel(noRepeatRoleLevel)
                .jclManager(ecManager)
                .jclRolelevel(noRepeatRoleLevel)
                .build();
        getMangeDetachMapper().updateDetach(managerDetachPO);
        return managerDetachPO.getId();
    }

    @Override
    public String doDetach(String isDetach) {
        ConfigOperator ConfigOperator = new ConfigOperator();
        ConfigOperator.setProp("hrmOrganization.properties", "detach", isDetach);
        return new BaseBean().getPropValue("hrmOrganization", "detach");
    }

    @Override
    public List<Integer> selectManagerDetachByUid() {
        ManagerDetachPO managerDetach = getMangeDetachMapper().selectManagerDetachByUid(user.getUID());
        List<Integer> subCompanyIds = Arrays.stream(managerDetach.getEcRolelevel().split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        return subCompanyIds;
    }

    private String buildSqlWhere(Map<String, Object> params) {
        DBType dbType = DBType.get(new RecordSet().getDBType());
        String sqlWhere = " where delete_type = 0";
        String lastName = Util.null2String(params.get("ecManager"));
        if (StringUtils.isNotBlank(lastName)) {
            List<Long> resourceIds = MapperProxyFactory.getProxy(EmployeeMapper.class).getResourceIds(lastName);
            String ecManager = StringUtils.join(resourceIds, ",");
            sqlWhere += " AND ec_manager in (" + (StringUtils.isBlank(ecManager) ? "''" : ecManager) + ") ";
        }
        String ecRolelevel = (String) params.get("ecRolelevel");
        if (StringUtils.isNotBlank(ecRolelevel)) {
            sqlWhere += " AND " + dbType.concat("ec_rolelevel") + dbType.like("," + ecRolelevel + ",");
        }
        return sqlWhere;
    }


    /**
     * 查询当前人员所辖分部JCL_ID
     *
     * @param uId
     * @return
     */
    public static List<Integer> getJclRoleLevels(Integer uId) {
        List<Integer> ecRoleLevels = new ArrayList<>();
       // ManagerDetachMapper mangeDetachMapper = MapperProxyFactory.getProxy(ManagerDetachMapper.class);
        //人员
        List<ManagerDetachPO> detachListById = new ArrayList<>(MapperProxyFactory.getProxy(ManagerDetachMapper.class).getDetachListById(uId,0));
        //角色
        HrmCommonService hrmCommonService = new HrmCommonServiceImpl();
        List<String> roleIds = new ArrayList<>(Arrays.asList(hrmCommonService.getRoleIds(uId).split(",")));
        List<Integer> integerList  = roleIds.stream()
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        detachListById.addAll(MapperProxyFactory.getProxy(ManagerDetachMapper.class).selectDetachListByManager(integerList));
        for (ManagerDetachPO managerDetachPO : detachListById) {
            List<Integer> ids = Stream.of(managerDetachPO.getJclRolelevel().split(",")).map(Integer::parseInt).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(ids)) {
                ecRoleLevels.addAll(ids);
            }
        }
        return ecRoleLevels.stream()
                .distinct() // 去除重复元素
                .collect(Collectors.toList());
    }


    /**
     * 获得无重复角色级别
     *
     * @param detachList detachList
     * @param id
     * @return return
     */
    private Set<String> getNoRepeatRoleLevels(List<ManagerDetachPO> detachList, Integer id) {
        Set<String> ecRoleLevels = new HashSet<>();
        for (ManagerDetachPO managerDetach : detachList) {
            if (null != id && id.equals(managerDetach.getId())) {
                continue;
            }
            Set<String> ids = Stream.of(managerDetach.getJclRolelevel().split(",")).collect(Collectors.toSet());
            if (CollectionUtils.isNotEmpty(ids)) {
                ecRoleLevels.addAll(ids);
            }
        }
        return ecRoleLevels;
    }
}
