package weaver.interfaces.organization.cronjob;

import com.engine.organization.entity.job.po.JobPO;
import com.engine.organization.entity.staff.param.StaffPersonCronParam;
import com.engine.organization.entity.staff.po.StaffPO;
import com.engine.organization.mapper.job.JobMapper;
import com.engine.organization.util.OrganizationAssert;
import com.engine.organization.util.db.MapperProxyFactory;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.interfaces.schedule.BaseCronJob;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author liang.cheng
 * @Date 2024/7/16 11:00 AM
 * @Description: 编制信息在编人数定时任务更新
 * @Version 1.0
 */
public class StaffPersonCron extends BaseCronJob {

    private String planId;

    public String getPlanId() {
        return planId;
    }

    public void setPlanId(String planId) {
        this.planId = planId;
    }

    @Override
    public void execute() {

        //1.查询需要更新的数据
        RecordSet rs = new RecordSet();
        StringBuilder sb = new StringBuilder();
        sb.append("select a.id,a.plan_id,a.ec_company,a.ec_department,a.job_id,a.permanent_num,a.staff_num,a.freeze_num,b.control_dimension \n" +
                " from jcl_org_staff a left join jcl_org_staffplan b on a.plan_id = b.id where a.delete_type = 0 ");

        OrganizationAssert.notNull(planId,"编制方案ID参数必填,多个以逗号隔开");

        sb.append(" and a.plan_id in (").append(planId).append(") ");

        rs.executeQuery(sb.toString());
        List<StaffPersonCronParam> cronParamList = new ArrayList<>();

        while (rs.next()) {
            StaffPersonCronParam build = StaffPersonCronParam.builder()
                    .id(Util.getIntValue(rs.getString("id")))
                    .planId(Util.getIntValue(rs.getString("plan_id")))
                    .ecCompany(Util.getIntValue(rs.getString("ec_company")))
                    .ecDepartment(Util.getIntValue(rs.getString("ec_department")))
                    .jobId(Util.getIntValue(rs.getString("job_id")))
                    .permanentNum(Util.getIntValue(rs.getString("permanent_num")))
                    .staffNum(Util.getIntValue(rs.getString("staff_num")))
                    .freezeNum(Util.getIntValue(rs.getString("freeze_num")))
                    .controlDimension(Util.null2String(rs.getString("control_dimension")))
                    .build();
            cronParamList.add(build);
        }

        OrganizationAssert.notEmpty(cronParamList,"当前编制方案下无编制信息数据更新");
        List<StaffPO> poList = new ArrayList<>();
        cronParamList.forEach(item -> {

            String sql = "select count(1) as num from hrmresource where status < 4";
            if ("1".equals(item.getControlDimension())){
                ArrayList<String> subCompanyList = new ArrayList<>();
                subCompanyList.add(item.getEcCompany().toString());
                new SubCompanyComInfo().getSubCompanyLists(item.getEcCompany().toString(), subCompanyList);
                sql += " and subcompanyid1 in (" + StringUtils.join(subCompanyList, ",") + ")";

            }else if ("2".equals(item.getControlDimension())) {
                ArrayList<String> departmentList = new ArrayList<>();
                departmentList.add(item.getEcDepartment().toString());
                new DepartmentComInfo().getAllChildDeptByDepId(departmentList, item.getEcDepartment().toString());
                sql += " and departmentid in (" + StringUtils.join(departmentList, ",") + ")";

            }else if ("3".equals(item.getControlDimension())) {
                JobPO jobById = MapperProxyFactory.getProxy(JobMapper.class).getJobById(Long.valueOf(item.getJobId()));
                if (null == jobById) {
                    return;
                }
                Integer ecJobTitle = jobById.getEcJobTitle();
                sql += " and subcompanyid1 = "+item.getEcCompany()+" and departmentid = "+item.getEcDepartment()+" and jobtitle = " + ecJobTitle;
            }

            BaseBean bb  = new BaseBean();

            if ("false".equals(bb.getPropValue("hrmOrganization","accountType"))) {
                sql += " and accounttype != 1";
            }

            if ("true".equals(bb.getPropValue("hrmOrganization","filterEnable"))) {
                String usekind = bb.getPropValue("hrmOrganization", "usekind");
                sql += " and usekind not in ("+usekind+") ";
            }

            rs.executeQuery(sql);
            if (rs.next()) {
                StaffPO build = StaffPO.builder().id(Long.valueOf(item.getId())).permanentNum(item.getPermanentNum()).build();
                build.setPermanentNum(-1 == rs.getInt("num") ? 0 : rs.getInt("num"));
                List<Integer> numberF = Arrays.asList(item.getFreezeNum(),build.getPermanentNum());
                int sum = numberF.stream()
                        .mapToInt(Integer::intValue)
                        .sum();
                build.setLackStatus(parseLackStatus(null == item.getStaffNum() ? 0 : item.getStaffNum(),sum));
                poList.add(build);
            }
        });

        //2.更新数据
        poList.forEach(item -> rs.executeUpdate("update jcl_org_staff set permanent_num = ?,lack_status = ? where id = ?",
                item.getPermanentNum(),item.getLackStatus(),item.getId()));

    }

    private static int parseLackStatus(int staffNum, int sums) {
        if (staffNum == sums) {
            return 2;
        }
        if (staffNum > sums) {
            return 1;
        }
        return 3;
    }
}
