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.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.mapper.resource.ResourceMapper;
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 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 ResourceMapper getResourceMapper() {
        return MapperProxyFactory.getProxy(ResourceMapper.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<>();
        List<SearchConditionItem> selectItems = new ArrayList<>();
        List<SearchConditionGroup> addGroups = new ArrayList<>();
        List<SearchConditionOption> selectOptions = new ArrayList<>();
        SearchConditionOption moduleOption = new SearchConditionOption("0", "组织管理",true);
        selectOptions.add(moduleOption);

        SearchConditionItem ecManager = OrganizationFormItemUtil.browserItem(user, 2, 16, 3, true, "管理员", "1", "ecManager", "");
        ecManager.setRules("required|string");
        SearchConditionItem ecRolelevel = OrganizationFormItemUtil.browserItem(user, 2, 16, 3, false, "可维护机构", "194", "ecRolelevel", "");
        ecRolelevel.setRules("required|string");
        SearchConditionItem module = OrganizationFormItemUtil.selectItem(user, selectOptions, 2, 16, 6, false, "可管理模块", "module");
        module.setViewAttr(1);
        module.setDetailtype(2);
        module.setHasBorder(true);
        if (id != null) {
            ManagerDetachPO detachById = getMangeDetachMapper().getDetachById(id);
            BrowserBean manager = ecManager.getBrowserConditionParam();
            manager.setReplaceDatas(getEmployeeMapper().getBrowserDatas(DeleteParam.builder().ids(String.valueOf(detachById.getEcManager())).build().getIds()));
            ecManager.setBrowserConditionParam(manager);
            BrowserBean roleLevel = ecRolelevel.getBrowserConditionParam();
            roleLevel.setReplaceDatas(getSystemDataMapper().getBrowserDatas(DeleteParam.builder().ids(String.valueOf(detachById.getEcRolelevel())).build().getIds()));
            ecRolelevel.setBrowserConditionParam(roleLevel);
        }
        selectItems.add(ecManager);
        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) {
        ManagerDetachPO managerDetachPO = ManagerDetachPO.builder()
                .managerType(0)
                .ecManager(param.getEcManager())
                .jclManager(param.getEcManager())
                .ecRolelevel(param.getEcRolelevel())
                .jclRolelevel(param.getEcRolelevel())
                .manageModule("组织管理")
                .creator((long)user.getUID())
                .deleteType(0)
                .createTime(new Date())
                .updateTime(new Date())
                .build();

        return getMangeDetachMapper().insertIgnoreNull(managerDetachPO);
    }

    @Override
    public int updateDetach(ManagerDetachParam param) {
        ManagerDetachPO managerDetachPO = ManagerDetachPO.builder()
                .id(param.getId())
                .ecManager(param.getEcManager())
                .ecRolelevel(param.getEcRolelevel())
                .jclManager(param.getEcManager())
                .jclRolelevel(param.getEcRolelevel())
                .build();
        return getMangeDetachMapper().updateDetach(managerDetachPO);
    }

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

    private String buildSqlWhere(Map<String, Object> params) {
        DBType dbType = DBType.get(new RecordSet().getDBType());
        String sqlWhere = " where delete_type = 0";
        String lastName = (String) params.get("ecManager");
        List<Long> resourceIds = MapperProxyFactory.getProxy(EmployeeMapper.class).getResourceIds(lastName);
        String ecManager = StringUtils.join(resourceIds,",");
        if (StringUtils.isNotBlank(lastName)) {
            sqlWhere += " AND ec_manager in ("+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 = mangeDetachMapper.getDetachListById(uId);
        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;
    }
}
