package com.kingdee.eas.custom.compensation.startingsalary.backgroundtransaction;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.basedata.assistant.CurrencyInfo;
import com.kingdee.eas.basedata.org.AdminOrgUnitInfo;
import com.kingdee.eas.basedata.org.HROrgUnitInfo;
import com.kingdee.eas.basedata.org.PositionInfo;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.certification.utils.DateUtil;
import com.kingdee.eas.custom.compensation.startingsalary.ISalaryConfirmation;
import com.kingdee.eas.custom.compensation.startingsalary.SalaryConfirmationCollection;
import com.kingdee.eas.custom.compensation.startingsalary.SalaryConfirmationFactory;
import com.kingdee.eas.custom.compensation.startingsalary.SalaryConfirmationInfo;
import com.kingdee.eas.hr.affair.EmpEnrollBizBillEntryInfo;
import com.kingdee.eas.hr.base.HRBillStateEnum;
import com.kingdee.eas.hr.emp.EmployeeOtherContractFactory;
import com.kingdee.eas.hr.emp.EmployeeOtherContractInfo;
import com.kingdee.eas.hr.emp.IEmployeeOtherContract;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.cmpdesign.BatchAdjustBillEntryInfo;
import com.kingdee.shr.cmpdesign.BatchAdjustBillInfo;
import com.kingdee.shr.cmpdesign.BatchAdjustFacadeFactory;
import com.kingdee.shr.compensation.*;
import com.kingdee.util.StringUtils;
import org.apache.log4j.Logger;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class CreateOtherContractsFacadeControllerBean extends AbstractCreateOtherContractsFacadeControllerBean {
    private static final Logger logger =
            Logger.getLogger("com.kingdee.eas.custom.compensation.startingsalary.backgroundtransaction.CreateOtherContractsFacadeControllerBean");
    BasicSalaryParameters parameters = null;

    @Override
    public void createContracts(Context ctx, String confirmationBillIds, int leadDays, String startDate, String endDate) throws BOSException {
        super.createContracts(ctx, confirmationBillIds, leadDays, startDate, endDate);
        parameters = new BasicSalaryParameters(ctx);
        EntityViewInfo viewInfo = new EntityViewInfo();
        FilterInfo filterInfo = new FilterInfo();
        // 条件分支1：传业务单ID集合，优先根据单据ID精确查询
        if (confirmationBillIds != null && confirmationBillIds.length() > 0) {
            confirmationBillIds = confirmationBillIds.trim();
            String[] split = confirmationBillIds.split(",");
            // 去重存放单据ID
            Set<String> idSet = new HashSet<String>();
            for (String id : split) {
                idSet.add(id.trim());
            }
            filterInfo.getFilterItems().add(new FilterItemInfo("id", idSet, CompareType.INCLUDE));
        }
        // 条件分支2：未传入单据ID，使用向前追溯天数范围查询
        else if (leadDays != 0) {
            Date now = new Date();
            // 创建时间 <= 当前日期
            filterInfo.getFilterItems().add(new FilterItemInfo("createTime", now, CompareType.LESS_EQUALS));
            // 计算追溯起始日期：当前日期向前推leadDays天
            Date before = DateUtil.add(now, -leadDays);
            // 创建时间 >= 追溯起始日期
            filterInfo.getFilterItems().add(new FilterItemInfo("createTime", before, CompareType.GREATER_EQUALS));
        }
        // 条件分支3：未传入单据ID、追溯天数，使用自定义起止日期范围查询
        else if (startDate != null && startDate.length() > 0 && endDate != null && endDate.length() > 0) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date start = null;
            try {
                start = format.parse(startDate);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            Date end = null;
            try {
                end = format.parse(endDate);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            filterInfo.getFilterItems().add(new FilterItemInfo("createTime", start, CompareType.GREATER_EQUALS));
            filterInfo.getFilterItems().add(new FilterItemInfo("createTime", end, CompareType.LESS_EQUALS));
        }
        // 无有效查询条件，抛出异常
        else {
            throw new BOSException("请选择查询的日期范围");
        }
        // 固定过滤条件：单据状态=已审核
        filterInfo.getFilterItems().add(new FilterItemInfo("billState", HRBillStateEnum.AUDITED_VALUE, CompareType.EQUALS));
        // 固定过滤条件：未生成薪酬确认单的记录
        filterInfo.getFilterItems().add(new FilterItemInfo("isGenerateContract", false, CompareType.EQUALS));

        viewInfo.setFilter(filterInfo);

        SelectorItemCollection selectorItemCollection = new SelectorItemCollection();
        selectorItemCollection.add("*");
        selectorItemCollection.add("empEnrollEntry.*");
        selectorItemCollection.add("entrys.*");
        viewInfo.setSelector(selectorItemCollection);
        ISalaryConfirmation iSalaryConfirmation = SalaryConfirmationFactory.getLocalInstance(ctx);
        SalaryConfirmationCollection salaryConfirmationCollection = iSalaryConfirmation.getSalaryConfirmationCollection(viewInfo);
        //T_HR_EmployeeOtherContract

        Map<String, Map<String, String>> transferSalary = parameters.getTransferSalary();
        IEmployeeOtherContract localInstance = EmployeeOtherContractFactory.getLocalInstance(ctx);
        for (int i = 0; i < salaryConfirmationCollection.size(); i++) {
            EmployeeOtherContractInfo otherContractInfo = new EmployeeOtherContractInfo();
            SalaryConfirmationInfo salaryConfirmationInfo = salaryConfirmationCollection.get(i);
            EmpEnrollBizBillEntryInfo empEnrollEntry = salaryConfirmationInfo.getEmpEnrollEntry();
            PersonInfo person = empEnrollEntry.getPerson();
            otherContractInfo.setEmployee(person);// 员工
            Date enrollDate = empEnrollEntry.getEnrollDate();//入职日期
            otherContractInfo.setRecordDate(enrollDate);// 记录日期
            otherContractInfo.setEffectDate(enrollDate);// 生效日期
            otherContractInfo.setContractLimitType(parameters.getContractLimitType());// 合同期限类型
            otherContractInfo.setContractTemplet(parameters.getContractTempletInfo());// 合同模版
            Object o = empEnrollEntry.get("ldhtzt");// 获取劳动合同主题
            for (Map.Entry<String, Map<String, String>> entry : transferSalary.entrySet()) {
                String key = entry.getKey();
                Map<String, String> value = entry.getValue();
                System.out.println("key:" + key);
                System.out.println("value:" + value);
                for (Map.Entry<String, String> entry1 : value.entrySet()) {
                    String key1 = entry1.getKey();
                    String value1 = entry1.getValue();
                    System.out.println("key1:" + key1);
                    System.out.println("value1:" + value1);
                    otherContractInfo.put(value1, salaryConfirmationInfo.get(value1));//写入薪酬项目值
                }
            }
            try {
                IObjectPK save = localInstance.save(otherContractInfo);
                salaryConfirmationInfo.setIsGenerateContract(true);
                salaryConfirmationInfo.setOtherContractBill(otherContractInfo);
                try {
                    //生成电子签
                    SalaryUtilsFacadeFactory.getLocalInstance(ctx).sendBatchEmployeeOtherSign(save.toString());
                    salaryConfirmationInfo.setIsGenerateSignature(true);
                } catch (Exception e) {
                    e.printStackTrace();
                    salaryConfirmationInfo.setIsGenerateSignature(false);
                }
                salaryConfirmationInfo.put("isBatchAdjustBill", false);
                iSalaryConfirmation.save(salaryConfirmationInfo);
            } catch (EASBizException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }

    }

}