package com.engine.organization.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.engine.core.impl.Service;
import com.engine.organization.entity.hrmresource.po.HrmResourcePO;
import com.engine.organization.entity.map.JclOrgMap;
import com.engine.organization.entity.version.*;
import com.engine.organization.enums.ModuleTypeEnum;
import com.engine.organization.mapper.jclorgmap.JclOrgMapper;
import com.engine.organization.mapper.resource.ResourceMapper;
import com.engine.organization.mapper.version.CompanyVersionMapper;
import com.engine.organization.service.VersionManageService;
import com.engine.organization.util.OrganizationDateUtil;
import com.engine.organization.util.db.MapperProxyFactory;
import org.apache.commons.lang3.StringUtils;
import org.docx4j.wml.U;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;

import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author weaver_cl
 * @Description:
 * @Date 2022/12/8
 * @Version V1.0
 **/
public class VersionManageServiceImpl extends Service implements VersionManageService {


    private CompanyVersionMapper getCompanyVersionMapper() {
        return MapperProxyFactory.getProxy(CompanyVersionMapper.class);
    }

    private JclOrgMapper getJclOrgMapMapper() {
        return MapperProxyFactory.getProxy(JclOrgMapper.class);
    }

    @Override
    public void save(ModuleTypeEnum moduleTypeEnum, Map<String, Object> params, User user) {
        String id = (String) params.get("id");
        JSONObject paramMap = null;

        switch (moduleTypeEnum.getValue()) {
            case 1:
                HrmSubCompanyDto hrmSubComp = getCompanyVersionMapper().getHrmSubComp(id);
                saveSubComToVersion(hrmSubComp, user);
//                saveSubComToMap(paramMap);
                break;
            case 2:
                HrmDepartmentDto hrmDepartmentDto = getCompanyVersionMapper().getHrmDepartment(id);
                saveDeptToVersion(hrmDepartmentDto, user);
//                saveDeptToMap(paramMap);
                break;
            case 4:
                HrmResourceDto hrmResourceDto = getCompanyVersionMapper().getHrmResource(id);
                saveHrmToVersion(hrmResourceDto, user);
//                saveHrmToMap(paramMap);
                break;
        }

    }

    @Override
    public Map<String, Object> getVersion(ModuleTypeEnum moduleTypeEnum, Map<String, Object> params, User user) {
        String operateName = "";
        String id = (String) params.get("id");
        String version = (String) params.get("version");
        String operateTime = "";
        Map<String, Object> resultMap = new HashMap<>();
        List versions = new ArrayList<>();
        List<VersionData> datas = new ArrayList<>();
        switch (moduleTypeEnum.getValue()) {
            case 1:
                List<HrmSubCompanyVersion> list = getCompanyVersionMapper().getSubComVersionList(id, null);

                int size = list.size();
                if (size < 1) {
                    break;
                }
                for (HrmSubCompanyVersion hrmSubCompanyVersion : list) {
                    Map<String, String> map = new HashMap<>();
                    map.put("value", String.format("%.1f", hrmSubCompanyVersion.getVersion()));
                    versions.add(map);
                }
                if (version.equals("1.0")) {
                    version = "1";
                }
                list = getCompanyVersionMapper().getSubComVersionList(id, version);
                for (HrmSubCompanyVersion hrmSubCompanyVersion : list) {
                    datas.add(VersionData.builder().fieldId("分部简称").fieldValue(Util.null2String(hrmSubCompanyVersion.getSubCompanyName())).build());
                    datas.add(VersionData.builder().fieldId("分部全称").fieldValue(Util.null2String(hrmSubCompanyVersion.getSubCompanyDesc())).build());
                    datas.add(VersionData.builder().fieldId("上级分部").fieldValue(Util.null2String(hrmSubCompanyVersion.getSupSubComName())).build());
                    datas.add(VersionData.builder().fieldId("版本号").fieldValue(Util.null2String(String.format("%.1f", hrmSubCompanyVersion.getVersion()))).build());
                    datas.add(VersionData.builder().fieldId("分部编号").fieldValue(Util.null2String(hrmSubCompanyVersion.getSubCompanyCode())).build());
                    datas.add(VersionData.builder().fieldId("排序").fieldValue(Util.null2String(hrmSubCompanyVersion.getShowOrder())).build());
                    operateName = hrmSubCompanyVersion.getOperator();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    operateTime = sdf.format(hrmSubCompanyVersion.getOperateTime());
                }
                break;
            case 2:
                List<HrmDepartmentVersion> deptVersionList = getCompanyVersionMapper().getDeptVersionList(id, null);
                int deptSize = deptVersionList.size();
                if (deptSize < 1) {
                    break;
                }
                for (HrmDepartmentVersion hrmDepartmentVersion : deptVersionList) {
                    Map<String, String> map = new HashMap<>();
                    map.put("value", String.format("%.1f", hrmDepartmentVersion.getVersion()));
                    versions.add(map);
                }
                if (version.equals("1.0")) {
                    version = "1";
                }
                deptVersionList = getCompanyVersionMapper().getDeptVersionList(id, version);
                for (HrmDepartmentVersion hrmDepartmentVersion : deptVersionList) {
                    datas.add(VersionData.builder().fieldId("部门编号").fieldValue(Util.null2String(hrmDepartmentVersion.getDepartmentCode())).build());
                    datas.add(VersionData.builder().fieldId("部门简称").fieldValue(Util.null2String(hrmDepartmentVersion.getDepartmentName())).build());
                    datas.add(VersionData.builder().fieldId("部门全称").fieldValue(Util.null2String(hrmDepartmentVersion.getDepartmentMark())).build());
                    datas.add(VersionData.builder().fieldId("所属分部").fieldValue(Util.null2String(hrmDepartmentVersion.getSubcompanyname())).build());
                    datas.add(VersionData.builder().fieldId("上级部门").fieldValue(Util.null2String(hrmDepartmentVersion.getSupDepName())).build());
                    datas.add(VersionData.builder().fieldId("部门负责人").fieldValue(Util.null2String(hrmDepartmentVersion.getBmfzrName())).build());
                    datas.add(VersionData.builder().fieldId("版本号").fieldValue(Util.null2String(String.format("%.1f", hrmDepartmentVersion.getVersion()))).build());
                    datas.add(VersionData.builder().fieldId("排序").fieldValue(Util.null2String(hrmDepartmentVersion.getShowOrder())).build());
                    operateName = hrmDepartmentVersion.getOperator();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    operateTime = sdf.format(hrmDepartmentVersion.getOperateTime());
                }
                break;
            case 4:
                List<HrmResourceVersion> resVersionList = getCompanyVersionMapper().getResourceVersionList(id, null);
                int resSize = resVersionList.size();
                if (resSize < 1) {
                    break;
                }
                for (HrmResourceVersion hrmResourceVersion : resVersionList) {
                    Map<String, String> map = new HashMap<>();
                    map.put("value", String.format("%.1f", hrmResourceVersion.getVersion()));
                    versions.add(map);
                }
                if (version.equals("1.0")) {
                    version = "1";
                }
                resVersionList = getCompanyVersionMapper().getResourceVersionList(id, version);
                for (HrmResourceVersion hrmResourceVersion : resVersionList) {
                    datas.add(VersionData.builder().fieldId("姓名").fieldValue(Util.null2String(hrmResourceVersion.getLastname())).build());
                    datas.add(VersionData.builder().fieldId("部门").fieldValue(Util.null2String(hrmResourceVersion.getDepartmentname())).build());
                    datas.add(VersionData.builder().fieldId("岗位").fieldValue(Util.null2String(hrmResourceVersion.getJobtitlename())).build());
                    datas.add(VersionData.builder().fieldId("分部").fieldValue(Util.null2String(hrmResourceVersion.getSubcompanyname())).build());
                    datas.add(VersionData.builder().fieldId("版本号").fieldValue(Util.null2String(String.format("%.1f", hrmResourceVersion.getVersion()))).build());
                    operateName = hrmResourceVersion.getOperator();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    operateTime = sdf.format(hrmResourceVersion.getOperateTime());
                }
                break;
            default:
                break;
        }

        resultMap.put("operateName", operateName);
        resultMap.put("operateTime", operateTime);
        resultMap.put("versions", versions);
        resultMap.put("datas", datas);
        if (versions.size() < 1) {
            return null;
        }
        return resultMap;
    }

    /**
     * 分部保存至map表
     */
    void saveSubComToMap(JSONObject params) {
        String currentDate = OrganizationDateUtil.getFormatLocalDate(new java.util.Date());
        String id = params.getString("id");

        JclOrgMap jclOrgMap = new JclOrgMap();
        jclOrgMap.setId(Integer.parseInt(id));
        jclOrgMap.setFType(1);
        jclOrgMap.setFObjId(Integer.parseInt(id));
        jclOrgMap.setFClass(0);
        jclOrgMap.setFClassName("行政维度");
        jclOrgMap.setFName(params.getString("subcompanyname"));
        String supSubComId = params.getString("supsubcomid");
        jclOrgMap.setFParentId(StringUtils.isNotBlank(supSubComId) ? Integer.parseInt(supSubComId) : null);
        jclOrgMap.setFIsVitual(0);
        jclOrgMap.setFDateBegin(new Date(OrganizationDateUtil.stringToDate(currentDate).getTime()));
        jclOrgMap.setFDateEnd(new Date(OrganizationDateUtil.stringToDate("2022-12-31").getTime()));

        JclOrgMap jclOrgMapByFParentId = getJclOrgMapMapper().getSumPlanAndJobByFParentId(jclOrgMap.getFDateBegin(), Util.null2String(jclOrgMap.getId()));
        if (jclOrgMapByFParentId != null) {
            jclOrgMap.setFPlan(jclOrgMapByFParentId.getFPlan());
            jclOrgMap.setFOnJob(jclOrgMapByFParentId.getFOnJob());
        } else {
            jclOrgMap.setFPlan(0);
            jclOrgMap.setFOnJob(0);
        }

        Calendar cal = Calendar.getInstance();
        cal.setTime(jclOrgMap.getFDateBegin());
        Calendar calendar = DateUtil.addDay(cal, -1);
        Date time = new Date(calendar.getTime().getTime());

        getJclOrgMapMapper().deleteMap("1", id, jclOrgMap.getFDateBegin());
        getJclOrgMapMapper().updateMap("1", id, jclOrgMap.getFDateBegin(), time);
        if (!params.getString("canceled").equals("1")) {
            getJclOrgMapMapper().insertMap(jclOrgMap);
        }
    }

    /**
     * 部门保存到map表
     */
    void saveDeptToMap(JSONObject params) {
        String id = params.getString("id");
        int st = 100000000;

        String currentDate = OrganizationDateUtil.getFormatLocalDate(new java.util.Date());

        JclOrgMap jclOrgMap = new JclOrgMap();
        jclOrgMap.setId(st + Integer.parseInt(id));
        jclOrgMap.setFType(2);
        jclOrgMap.setFObjId(Integer.parseInt(id));
        jclOrgMap.setFClass(0);
        jclOrgMap.setFClassName("行政维度");
        String bmfzr = params.getString("bmfzr");
        if (StringUtils.isNotBlank(bmfzr)) {
            jclOrgMap.setFLeader(Integer.parseInt(bmfzr));
            HrmResourcePO hrmResourcePO = MapperProxyFactory.getProxy(ResourceMapper.class).getResourceById(bmfzr);
            jclOrgMap.setFLeaderImg(hrmResourcePO.getResourceImageId());
            jclOrgMap.setFLeaderName(hrmResourcePO.getLastName());
            jclOrgMap.setFLeaderJobId(Math.toIntExact(hrmResourcePO.getJobTitle()));
        }
        jclOrgMap.setFName(params.getString("departmentname"));
        String subCompanyId1 = params.getString("subcompanyid1");
        String supdepid = params.getString("supdepid");
        if (supdepid != null) {
            jclOrgMap.setFParentId(st + Integer.parseInt(supdepid));
        }
        if ("0".equals(supdepid)) {
            jclOrgMap.setFParentId(Integer.parseInt(subCompanyId1));
        }
        jclOrgMap.setFDateBegin(new Date(OrganizationDateUtil.stringToDate(currentDate).getTime()));
        jclOrgMap.setFDateEnd(new Date(OrganizationDateUtil.stringToDate("2022-12-31").getTime()));
        jclOrgMap.setFIsVitual(0);

        JclOrgMap jclOrgMapByFParentId = getJclOrgMapMapper().getSumPlanAndJobByFParentId(jclOrgMap.getFDateBegin(), String.valueOf(jclOrgMap.getId()));
        if (null != jclOrgMapByFParentId) {
            jclOrgMap.setFPlan(jclOrgMapByFParentId.getFPlan());
            jclOrgMap.setFOnJob(jclOrgMapByFParentId.getFOnJob());
        } else {
            jclOrgMap.setFPlan(0);
            jclOrgMap.setFOnJob(0);
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(jclOrgMap.getFDateBegin());
        Calendar calendar = DateUtil.addDay(cal, -1);
        Date time = new Date(calendar.getTime().getTime());

        getJclOrgMapMapper().deleteMap("2", id, jclOrgMap.getFDateBegin());
        getJclOrgMapMapper().updateMap("2", id, jclOrgMap.getFDateBegin(), time);
        if (!params.getString("canceled").equals("1")) {
            getJclOrgMapMapper().insertMap(jclOrgMap);
        }
    }


    /**
     * 人员保存至map
     */
    void saveHrmToMap(JSONObject params) {
        String id = params.getString("id");
        String currentDate = OrganizationDateUtil.getFormatLocalDate(new java.util.Date());
        int sk = 300000000;
        RecordSet rs = new RecordSet();

        JclOrgMap jclOrgMap = new JclOrgMap();
        jclOrgMap.setId(sk + Integer.parseInt(id));
        jclOrgMap.setFType(4);
        jclOrgMap.setFObjId(Integer.parseInt(id));
        jclOrgMap.setFClass(0);
        jclOrgMap.setFClassName("行政维度");
        jclOrgMap.setFName(params.getString("lastname"));
        if (StringUtils.isNotBlank(id)) {
            rs.executeQuery("select messagerurl, lastname, jobtitle from  hrmresource where id=" + id + ";");
            if (rs.next()) {
                jclOrgMap.setFLeaderImg(Util.null2String(rs.getString("messagerurl")));
                jclOrgMap.setFLeaderName(Util.null2String(rs.getString("lastname")));
                jclOrgMap.setFLeaderJobId(Integer.valueOf(rs.getString("jobtitle")));
            }
        }
        String jobtitle = params.getString("jobtitle");
        jclOrgMap.setFParentId(StringUtils.isNotBlank(jobtitle) ? sk + Integer.parseInt(jobtitle) : null);

        jclOrgMap.setFPlan(0);
        jclOrgMap.setFOnJob(0);
        jclOrgMap.setFIsVitual(0);
        jclOrgMap.setFDateBegin(new Date(OrganizationDateUtil.stringToDate(currentDate).getTime()));
        jclOrgMap.setFDateEnd(new Date(OrganizationDateUtil.stringToDate("2022-12-31").getTime()));

        Calendar cal = Calendar.getInstance();
        cal.setTime(jclOrgMap.getFDateBegin());
        Calendar calendar = DateUtil.addDay(cal, -1);
        Date time = new Date(calendar.getTime().getTime());

        getJclOrgMapMapper().deleteMap("4", id, jclOrgMap.getFDateBegin());
        getJclOrgMapMapper().updateMap("4", id, jclOrgMap.getFDateBegin(), time);

        if (!params.getString("canceled").equals("1")) {
            getJclOrgMapMapper().insertMap(jclOrgMap);
        }

    }


    /**
     * 分部保存至版本表
     */
    void saveSubComToVersion(HrmSubCompanyDto hrmSubComp, User user) {
        String currentDate = OrganizationDateUtil.getFormatLocalDateTime(new java.util.Date());
        int id = hrmSubComp.getId();
        HrmSubCompanyVersion hrmSubCompanyVersion = new HrmSubCompanyVersion();
        hrmSubCompanyVersion.setSubComId(id);
        hrmSubCompanyVersion.setSubCompanyDesc(hrmSubComp.getSubcompanydesc());
        hrmSubCompanyVersion.setSubCompanyCode(hrmSubComp.getSubcompanycode());
        hrmSubCompanyVersion.setSubCompanyName(hrmSubComp.getSubcompanyname());
        String supSubComId = hrmSubComp.getSupsubcomid();
        hrmSubCompanyVersion.setSupSubComId(StringUtils.isNotBlank(supSubComId) ? Integer.parseInt(supSubComId) : null);
        String showOrder = hrmSubComp.getShoworder();
        if (showOrder != null && !showOrder.equals("0")) {
            int length = showOrder.indexOf(".");
            if (length>0){
                showOrder = showOrder.substring(0, length);
            }
        }
        hrmSubCompanyVersion.setShowOrder(null == showOrder ? null : Integer.parseInt(showOrder));
        String canceled = hrmSubComp.getCanceled();
        ;
        hrmSubCompanyVersion.setCanceled(StringUtils.isNotBlank(canceled) ? Integer.parseInt(canceled) : null);
        hrmSubCompanyVersion.setDescription(null);
        hrmSubCompanyVersion.setOperator(user.getUsername());
        hrmSubCompanyVersion.setVersion(genVersionId(1, Util.null2String(id)));
        hrmSubCompanyVersion.setOperateTime(new Timestamp(OrganizationDateUtil.stringToDateTime(currentDate).getTime()));
        getCompanyVersionMapper().insertHrmSubComVersion(hrmSubCompanyVersion);
    }

    /**
     * 部门保存至版本
     */
    void saveDeptToVersion(HrmDepartmentDto hrmDepartmentDto, User user) {
        int id = hrmDepartmentDto.getId();
        String currentDate = OrganizationDateUtil.getFormatLocalDateTime(new java.util.Date());

        HrmDepartmentVersion hrmDepartmentVersion = new HrmDepartmentVersion();
        hrmDepartmentVersion.setDepartmentId(id);
        hrmDepartmentVersion.setDepartmentMark(hrmDepartmentDto.getDepartmentmark());
        hrmDepartmentVersion.setDepartmentCode(hrmDepartmentDto.getDepartmentcode());
        hrmDepartmentVersion.setDepartmentName(hrmDepartmentDto.getDepartmentname());
        String subCompanyId1 = hrmDepartmentDto.getSubcompanyid1();
        hrmDepartmentVersion.setSubCompanyId1(StringUtils.isNotBlank(subCompanyId1) ? Integer.parseInt(subCompanyId1) : null);
        String supDepId = hrmDepartmentDto.getSupdepid();
        if (supDepId != null) {
            hrmDepartmentVersion.setSupDepId(Integer.parseInt(supDepId));
        }
        String bmfzr = hrmDepartmentDto.getBmfzr();
        if (!"".equals(bmfzr) && bmfzr != null) {
            hrmDepartmentVersion.setBmfzr(bmfzr);
        }
        String showOrder = hrmDepartmentDto.getShoworder();
        if (showOrder != null && !showOrder.equals("0")) {
            int length = showOrder.indexOf(".");
            if (length>0){
                showOrder = showOrder.substring(0, length);
            }
        }
        hrmDepartmentVersion.setShowOrder(null == showOrder ? null : Integer.parseInt(showOrder));
        String canceled = hrmDepartmentDto.getCanceled();
        hrmDepartmentVersion.setCanceled(StringUtils.isNotBlank(canceled) ? Integer.parseInt(canceled) : null);
        hrmDepartmentVersion.setDescription(null);
        hrmDepartmentVersion.setOperator(user.getLastname());
        hrmDepartmentVersion.setVersion(genVersionId(2, Util.null2String(id)));
        hrmDepartmentVersion.setOperateTime(new Timestamp(OrganizationDateUtil.stringToDateTime(currentDate).getTime()));

        getCompanyVersionMapper().insertHrmDeptVersion(hrmDepartmentVersion);
    }

    /**
     * 人员保存至版本
     */
    void saveHrmToVersion(HrmResourceDto hrmResourceDto, User user) {
        Integer id = hrmResourceDto.getId();
        String currentDate = OrganizationDateUtil.getFormatLocalDateTime(new java.util.Date());

        HrmResourceVersion hrmResourceVersion = new HrmResourceVersion();
        hrmResourceVersion.setResourceid(id);
/*        hrmResourceVersion.setCompanystartdate(new Date(OrganizationDateUtil.stringToDate((String) params.get("companystartdate")).getTime()));
        hrmResourceVersion.setCompanyworkyear(Integer.parseInt((String) params.get("companyworkyear")));
        hrmResourceVersion.setWorkstartdate(new Date(OrganizationDateUtil.stringToDate((String) params.get("workstartdate")).getTime()));*/

        hrmResourceVersion.setDepartmentid(hrmResourceDto.getDepartmentid());
        hrmResourceVersion.setDsporder(Double.valueOf(hrmResourceDto.getDsporder()).intValue());
        hrmResourceVersion.setSubcompanyid1(hrmResourceDto.getSubcompanyid1());
        hrmResourceVersion.setJobtitle(hrmResourceDto.getJobtitle());
        hrmResourceVersion.setMobile(hrmResourceDto.getMobile());
        hrmResourceVersion.setTelephone(hrmResourceDto.getTelephone());
        String managerid = hrmResourceDto.getManagerid();
        hrmResourceVersion.setManagerid(StringUtils.isNotBlank(managerid) ? Integer.parseInt(managerid) : null);
        hrmResourceVersion.setLastname(hrmResourceDto.getLastname());
        hrmResourceVersion.setOperator(user.getLastname());
        hrmResourceVersion.setVersion(genVersionId(4, String.valueOf(id)));
        hrmResourceVersion.setOperateTime(new Timestamp(OrganizationDateUtil.stringToDateTime(currentDate).getTime()));

        getCompanyVersionMapper().insertHrmResourceVersion(hrmResourceVersion);

    }

    /**
     * 版本号生成
     */
    private Double genVersionId(int fType, String sid) {
        // 版本V1.0 + 0.1  (默认字段)
        double id = 1.0;
        switch (fType) {
            case 1:
                HrmSubCompanyVersion hrmSubCompanyVersion = getCompanyVersionMapper().getMaxVersion(sid);
                if (null != hrmSubCompanyVersion) {
                    id = 0.1 + hrmSubCompanyVersion.getVersion();
                }
                break;
            case 2:
                HrmDepartmentVersion hrmDepartmentVersion = getCompanyVersionMapper().getMaxDeptVersion(sid);
                if (null != hrmDepartmentVersion) {
                    id = 0.1 + hrmDepartmentVersion.getVersion();
                }
                break;
            case 4:
                HrmResourceVersion hrmResourceVersion = getCompanyVersionMapper().getMaxHrmVersion(sid);
                if (null != hrmResourceVersion) {
                    id = 0.1 + hrmResourceVersion.getVersion();
                }
                break;
        }
        return id;
    }


}
