package weaver.interfaces.organization.action;

import cn.hutool.core.collection.CollectionUtil;
import com.engine.organization.entity.hrmresource.po.ResourcePO;
import com.engine.organization.entity.job.po.JobPO;
import com.engine.organization.entity.staff.po.StaffPO;
import com.engine.organization.enums.DeleteTypeEnum;
import com.engine.organization.mapper.job.JobMapper;
import com.engine.organization.mapper.staff.StaffMapper;
import com.engine.organization.util.db.MapperProxyFactory;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.job.JobTitlesComInfo;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.util.*;

/**
 * @Author liang.cheng
 * @Date 2024/9/25 2:03 PM
 * @Description: 流程明细编制信息操作初始化
 * @Version 1.0
 */
public class WorkflowStaffOperateAction implements Action {

    @Override
    public String execute(RequestInfo requestInfo) {

        String requestid = requestInfo.getRequestid();
        int formid = Math.abs(requestInfo.getRequestManager().getFormid());

        RecordSet rs = new RecordSet();

        String mainTable = String.format("%s%s", "formtable_main_", formid);

        String detaiTable = String.format("%s%s",mainTable,"_dt1");

        //1.获取表单数据
        rs.executeQuery("select a.bzfa,b.fb,b.bm,b.gw,b.bzs,b.zzs from "+mainTable+" as a \n" +
                "right join "+detaiTable+" as b on a.id = b.mainid where a.requestid = ?",requestid);

        List<StaffPO> staffList = new ArrayList<>();

        while (rs.next()) {
            StaffPO build = StaffPO.builder()
                    .planId(Util.getIntValue(rs.getString("bzfa")))
                    .compId(Util.getIntValue(rs.getString("fb")))
                    .deptId(Util.getIntValue(rs.getString("bm")))
                    .jobId(Util.getIntValue(rs.getString("gw")))
                    .staffNum(Util.getIntValue(rs.getString("bzs")))
                    .permanentNum(Util.getIntValue(rs.getString("zzs")))
                    .build();
            staffList.add(build);
        }

        if (CollectionUtil.isEmpty(staffList)) {
            requestInfo.getRequestManager().setMessagecontent("未找到明细数据");
            return Action.FAILURE_AND_CONTINUE;
        }

        Integer planId = staffList.get(0).getPlanId();

        //2.数据处理，Ec岗位id替换为聚才林岗位id 不存在情况下新增岗位数据
        buildJobTitle(staffList);

        //3.根据方案id获取当前已有编制信息与流程明细比较；已存在的更新，未存在的新增
        List<StaffPO> hStaffList = new ArrayList<>();
        rs.executeQuery("select id,comp_id,dept_id,job_id,freeze_num from jcl_org_staff where plan_id = ? and delete_type = 0",planId);
        while (rs.next()) {
            StaffPO build = StaffPO.builder()
                    .id((long) Util.getIntValue(rs.getString("id")))
                    .compId(Util.getIntValue(rs.getString("comp_id")))
                    .deptId(Util.getIntValue(rs.getString("dept_id")))
                    .jobId(Util.getIntValue(rs.getString("job_id")))
                    .freezeNum(Util.getIntValue(rs.getString("freeze_num")))
                    .build();
            hStaffList.add(build);
        }

        //新增的编制信息数据List
        List<StaffPO> iStaffList = new ArrayList<>();

        Map<String, StaffPO> hStaffMap = new HashMap<>();

        for (StaffPO staff : hStaffList) {
            String key = staff.getCompId() + "_" + staff.getDeptId() + "_" + staff.getJobId();
            hStaffMap.put(key, staff);
        }

        for (StaffPO staff : staffList) {
            String key = staff.getCompId() + "_" + staff.getDeptId() + "_" + staff.getJobId();
            if (hStaffMap.containsKey(key)) {
                StaffPO matchedStaff = hStaffMap.get(key);
                matchedStaff.setPermanentNum(staff.getPermanentNum());
                matchedStaff.setStaffNum(staff.getStaffNum());
            }else {
                iStaffList.add(staff);
            }
        }

        //更新
        hStaffList.forEach(item -> {
            //todo 冻结数还原为0根据需求而定
            buildStaffPO(item);
            rs.executeUpdate("update jcl_org_staff set staff_num = ?,permanent_num = ?,lack_status = ? where id = ?",
                    item.getStaffNum(),item.getPermanentNum(),item.getLackStatus(),item.getId());
        });

        //插入
        iStaffList.forEach(staffPO -> {
            staffPO.setFreezeNum(0);
            staffPO.setControlPolicy(1);
            staffPO.setDeleteType(0);
            staffPO.setCreateTime(new Date());
            staffPO.setUpdateTime(new Date());
            staffPO.setCreator(1L);
            buildStaffPO(staffPO);
            MapperProxyFactory.getProxy(StaffMapper.class).insertIgnoreNull(staffPO);
        });

        return Action.SUCCESS;
    }


    /**
     * Ec岗位转换聚才林岗位
     * @param staffList
     */
    private void buildJobTitle(List<StaffPO> staffList) {
        JobTitlesComInfo jb = new JobTitlesComInfo();
        staffList.forEach(item -> {
            ResourcePO resourcePo = ResourcePO.builder().subcompanyid1(item.getCompId()).departmentid(item.getDeptId()).jobtitle(item.getJobId()).build();
            JobPO jobByResource = MapperProxyFactory.getProxy(JobMapper.class).getJobByResource(resourcePo);
            if (jobByResource == null) {
                //岗位不存在新增
                JobPO jobPO = JobPO.builder()
                        .ecCompany(resourcePo.getSubcompanyid1())
                        .ecDepartment(resourcePo.getDepartmentid())
                        .ecJobTitle(resourcePo.getJobtitle())
                        .isKey(0)
                        .deleteType(DeleteTypeEnum.NOT_DELETED.getValue())
                        .createTime(new Date())
                        .updateTime(new Date())
                        .build();
                String jobTitlescode = jb.getJobTitlescode(String.valueOf(resourcePo.getJobtitle()));
                if (!"".equals(jobTitlescode)) {
                    jobPO.setJobNo(jobTitlescode+"-"+resourcePo.getDepartmentid());
                }
                MapperProxyFactory.getProxy(JobMapper.class).insertIgnoreNull(jobPO);
                item.setJobId(Math.toIntExact(jobPO.getId()));
            }else {
                item.setJobId(Math.toIntExact(jobByResource.getId()));
            }


        });
    }


    private static void  buildStaffPO(StaffPO staffPO) {
        List<Integer> number = Arrays.asList(staffPO.getPermanentNum(),staffPO.getFreezeNum());
        Integer sums = number.stream()
                .mapToInt(Integer::intValue)
                .sum();
        Integer a = staffPO.getStaffNum();
        staffPO.setLackStatus((a.compareTo(sums) < 0) ? 3 : ((a.compareTo(sums) == 0) ? 2 : 1));
    }
}
