package com.kingdee.eas.custom.attendance.service;

import com.aliyun.odps.utils.StringUtils;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.bsf.service.app.IHRMsfService;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.basedata.hraux.FolkFactory;
import com.kingdee.eas.basedata.hraux.FolkInfo;
import com.kingdee.eas.basedata.org.*;
import com.kingdee.eas.basedata.person.Genders;
import com.kingdee.eas.basedata.person.PersonCollection;
import com.kingdee.eas.basedata.person.PersonFactory;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.hr.affair.*;
import com.kingdee.eas.hr.base.*;
import com.kingdee.eas.hr.emp.*;
import com.kingdee.eas.hr.org.JobGradeInfo;
import com.kingdee.eas.hr.org.JobLevelFactory;
import com.kingdee.eas.hr.org.JobLevelInfo;
import com.kingdee.shr.ats.web.util.SHRBillUtil;
import jodd.util.StringUtil;
import org.apache.log4j.Logger;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 入职
 */
public class SaveEmpEnrollBizBillService implements IHRMsfService {
    private static Logger logger = Logger.getLogger(SHRBillUtil.class);

    @Override
    public Object process(Context context, Map<String, Object> map) throws EASBizException, BOSException {
        Map<String, Object> result = new HashMap<String, Object>();
        StringBuilder errLog = new StringBuilder();
        try {
            System.out.println("SaveEmpEnrollBizBillService" + map);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String orgTop = "00000000-0000-0000-0000-000000000000CCE7AED4";
            //必填
            String createPerson = (String)map.get("createPerson"); //申请人
            String personName = (String)map.get("personName"); //名称
            String gender = (String)map.get("gender"); // 性别
            String positionNumber = (String)map.get("position"); // 职位编码
            String telNum = (String)map.get("telNum"); //电话号码
            String personNumber = (String)map.get("personNumber"); //编码
            String bizDate = (String)map.get("bizData"); //入职日期  bizDate
            String oaUserName = (String)map.get("oaUserName"); //oa用户名
            //选填
            String idCard = (String)map.get("idCard"); // 身份证号码
            String passport = (String)map.get("passport"); // 护照号码
            String isEnrollAgain = (String)map.get("isEnrollAgain"); //是否在入职
            String oldNub = (String)map.get("oldNub"); //再次入职 原员工编码
            //非必填
            String createDate = (String)map.get("createDate"); //申请日期
            String jobLevelNumber = (String)map.get("jobLevelNumber"); //职级
            String empTypeNumber = (String)map.get("empType"); // 用工关系状态
            String cardAddress = (String)map.get("cardAddress"); // 身份证地址
            String probation = (String)map.get("probation"); // 试用月
            String affType = (String)map.get("affType"); // 变动类型
            String hrBizDefine = (String)map.get("hrBizDefine"); // 变动操作
            String varReason = (String)map.get("varReason"); // 变动原因
            String myFolk = (String)map.get("myFolk"); //民族
            String naPlace = (String)map.get("naPlace"); //籍贯
            String email = (String)map.get("email"); //电子邮件
            String jobStrDate = (String)map.get("jobStrDate"); //参加工作日期
            String globAlr = (String)map.get("globAlr"); //国际区号
            String description = (String)map.get("description"); //国际区号

            if (StringUtils.isBlank(createPerson)){
                errLog.append("申请人不能为空！");
            }
            if (StringUtils.isBlank(personName)){
                errLog.append("员工名称不能为空！");
            }
            if (StringUtils.isBlank(gender)){
                errLog.append("性别不能为空！");
            }
            if (StringUtils.isBlank(positionNumber)){
                errLog.append("职位编码不能为空！");
            }
            if (StringUtils.isBlank(telNum)){
                errLog.append("电话号码不能为空！");
            }
            if (StringUtils.isBlank(personNumber)){
                errLog.append("员工工号不能为空！");
            }
            if (StringUtils.isBlank(bizDate)){
                errLog.append("入职日期不能为空！");
            }
            if (StringUtils.isBlank(oaUserName)){
                errLog.append("oa用户名不能为空！");
            }
            if (StringUtils.isBlank(idCard) && StringUtils.isBlank(passport)){
                errLog.append("身份证号码和护照不能同时为空！");
            }
            if (StringUtils.isNotBlank(isEnrollAgain)){
                if (StringUtils.isBlank(oldNub)){
                    errLog.append("再次入职时原员工工号不能为空！");
                }
            }

            if (errLog.length() >0 ){
                result.put("msgType", "0");
                result.put("msg", errLog.toString());
            }else {
                EmpEnrollBizBillInfo billInfo = new EmpEnrollBizBillInfo();
                //申请人工号
                PersonCollection presonCollection = PersonFactory.getLocalInstance(context).getPersonCollection("where number='" + createPerson + "'");
                if (presonCollection.size() > 0){
                    PersonInfo personInfo = presonCollection.get(0);
                    billInfo.setApplier(personInfo);
                }else {
                    errLog.append("制单人工号为" + createPerson + "不存在;");
                }
                //管理单元
                CtrlUnitInfo cu = new CtrlUnitInfo();
                //uuid生成规则
                cu.setId(BOSUuid.read(orgTop));
                billInfo.setCU(cu);
                //hr组织
                HROrgUnitInfo hrOrgUnitInfo = new HROrgUnitInfo();
                hrOrgUnitInfo.setId(BOSUuid.read(orgTop));
                billInfo.setHrOrgUnit(hrOrgUnitInfo);
                billInfo.setBizDate(new Date()); //业务时间
                //入职单分录
                EmpEnrollBizBillEntryInfo entry = new EmpEnrollBizBillEntryInfo();
                entry.setBill(billInfo);
                entry.setEmpName(personName);//姓名
                entry.setEmpNumber(personNumber);//员工编码
                Genders anEnum = Genders.getEnum(Integer.parseInt(gender));
                entry.setGender(anEnum);//性别
                PositionCollection positionCollection = PositionFactory.getLocalInstance(context).getPositionCollection("where number = '" + positionNumber + "'");
                if (presonCollection.size() > 0){
                    PositionInfo positionInfo = positionCollection.get(0);
                    AdminOrgUnitInfo adminOrgUnit = positionInfo.getAdminOrgUnit();
                    JobInfo job = positionInfo.getJob();
                    entry.setPosition(positionInfo);//目标职位
                    entry.setAdminOrg(adminOrgUnit);//目标组织
                    entry.setJob(job);//职务
                    entry.setReplaceAdminOrg(adminOrgUnit);//续存组织
                    billInfo.setAdminOrg(adminOrgUnit); //行政组织
                }else {
                    throw new Exception("入职职位编码" + positionNumber + "不存在;");
                }
                entry.setTelNum(telNum);//电话号码
                entry.setBizDate(simpleDateFormat.parse(bizDate));//生效日期
                entry.setEnrollDate(simpleDateFormat.parse(bizDate));//入职日期
                entry.put("oaUserName",oaUserName);



                if (StringUtils.isNotBlank(createDate)){
                    billInfo.setApplyDate(simpleDateFormat.parse(createDate));//申请日期
                }else {
                    billInfo.setApplyDate(new Date());
                }

                if (StringUtil.isNotBlank(jobLevelNumber)){
                    JobLevelInfo jobLevelInfo = JobLevelFactory.getLocalInstance(context).getJobLevelInfo("where number = '" + jobLevelNumber + "'");
                    JobGradeInfo jobGrade = jobLevelInfo.getJobGrade();
                    entry.setJobLevel(jobLevelInfo);//目标职级
                    entry.setJobGrade(jobGrade);//目标职等
                }
                if (StringUtils.isNotBlank(empTypeNumber)){ //用工关系状态
                    empTypeNumber = "002";
                }
                EmployeeTypeInfo employeeTypeInfo = EmployeeTypeFactory.getLocalInstance(context).getEmployeeTypeInfo("where number = '" + empTypeNumber + "'");
                entry.setEmpType(employeeTypeInfo); //目标员工状态

                if (StringUtils.isNotBlank(idCard)){
                    entry.setIDCardNo(idCard); //身份证
                }
                if (StringUtils.isNotBlank(passport)){
                    entry.setPassportNo(passport);//护照号码
                }
                if (StringUtils.isNotBlank(cardAddress)){
                    entry.setIdCardAddress(cardAddress); //身份证地址
                }
                if (StringUtils.isNotBlank(probation)){// 试用月
                    entry.setProbation(Integer.parseInt(probation));
                    LocalDate parse = LocalDate.parse(bizDate);
                    LocalDate newDate = parse.plusMonths(Integer.parseInt(probation));
                    Date from = Date.from(newDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
                    entry.setPlanFormalDate(from);//预计转正日期
                }

                if (StringUtil.isNotBlank(isEnrollAgain)){
                    if ("1".equals(isEnrollAgain)){
                        entry.setEnrollAgain(false);// 是否再入职
                    }else {
                        entry.setEnrollAgain(true);// 是否再入职
                        PersonCollection pCol = PersonFactory.getLocalInstance(context).getPersonCollection("where number='" + oldNub + "'");
                        if (presonCollection.size() > 0){
                            PersonInfo personInfo = pCol.get(0);
                            PersonPositionInfo ppInfo = getAdminOrgUnitByPersonId(context, personInfo.getId().toString());
                            PersonInfo person = ppInfo.getPerson();
                            entry.setExistPersonID(person.getId());//再入职人员ID
                            entry.setUseOldNumber(false);//再入职应用原员工编码
                            entry.setOldEmpType(person.getEmployeeType());//原员工状态
                            AdminOrgUnitInfo personDep = ppInfo.getPersonDep();
                            entry.setOldAdminOrg(personDep);//原组织
                            PositionInfo primaryPosition = ppInfo.getPrimaryPosition();
                            entry.setOldPosition(primaryPosition);//原职位
                        }else {
                            errLog.append("再次入职原员工工号" + oldNub + "不存在;");
                        }
                    }
                }
                entry.setIsPrimary(true);//是否主要任职
                if (StringUtils.isBlank(affType)){
                    affType = "0101";
                }
                AffairActionReasonInfo affairActionReasonInfo = AffairActionReasonFactory.getLocalInstance(context).getAffairActionReasonInfo("where number ='" + affType + "'");
                entry.setAffairActionReason(affairActionReasonInfo);//变动类型

                if (StringUtils.isBlank(hrBizDefine)){
                    hrBizDefine = "SHR01";
                }
                HRBizDefineInfo hrBizDefineInfo = HRBizDefineFactory.getLocalInstance(context).getHRBizDefineInfo("where number ='" + hrBizDefine + "'");
                entry.setHrBizDefine(hrBizDefineInfo);// 变动操作

                if (StringUtils.isBlank(varReason)){
                    varReason = "RZ08";
                }
                VariationReasonInfo variationReasonInfo = VariationReasonFactory.getLocalInstance(context).getVariationReasonInfo("where number ='" + varReason + "'");
                entry.setVariationReason(variationReasonInfo);// 变动原因


                if (StringUtils.isNotBlank(myFolk)){
                    FolkInfo folkInfo = FolkFactory.getLocalInstance(context).getFolkInfo("where number ='" + myFolk + "'");
                    entry.setMyFolk(folkInfo);//民族
                }
                if (StringUtils.isNotBlank(naPlace)){
                    entry.setNativePlace(naPlace);//籍贯
                }
                if (StringUtils.isNotBlank(email)){
                    entry.setEmail(email);//电子邮件
                }
                if (StringUtils.isNotBlank(jobStrDate)){
                    entry.setJobStartDate(simpleDateFormat.parse(jobStrDate));//参加工作日期
                }
                entry.setEmployerUnit(hrOrgUnitInfo);//用工单位
                //entry.setCompany(hrOrgUnitInfo); //公司
                //entry.setHrBizDefine(hrBizDefineInfo);//HR组织
                entry.setIdCardLongEffect(true);//身份证是否长期有效
                entry.setNCell(telNum);
                entry.setGlobalRoaming(globAlr); //国际区号
                String a = bizDate + " 00:00:00";
                entry.setBizTime(Timestamp.valueOf(a));//生效日期(时区)
                billInfo.getEntrys().add(entry);
                EmpEnrollBizBillFactory.getLocalInstance(context).submitEffect(billInfo);
                result.put("msgType", "1");
                result.put("msg", "success");
                result.put("fnumber", billInfo.getNumber());
            }
        } catch (Exception e) {
            errLog.append(e.getMessage());
            result.put("msgType", "0");
            result.put("msg", errLog.toString());
        }

        return result;
    }



    public static PersonPositionInfo getAdminOrgUnitByPersonId(Context ctx, String personID) {
        if (personID == null) {
            return null;
        } else {
            PersonPositionInfo personPositionInfo = null;
            StringBuffer oqlb = new StringBuffer();
            oqlb.append("select ");
            oqlb.append("id,");
            oqlb.append("person.number,");
            oqlb.append("person.name,");
            oqlb.append("personDep.id,");
            oqlb.append("personDep.name,");
            oqlb.append("personDep.number,");
            oqlb.append("personDep.employeeType,");
            oqlb.append("personDep.longnumber,");
            oqlb.append("personDep.displayName,");
            oqlb.append("primaryPosition.id,");
            oqlb.append("primaryPosition.name,");
            oqlb.append("primaryPosition.number");
            oqlb.append(" where person.id='");
            oqlb.append(personID);
            oqlb.append("'");
            PersonPositionCollection c = null;

            try {
                c = PersonPositionFactory.getLocalInstance(ctx).getPersonPositionCollection(oqlb.toString());
            } catch (BOSException var6) {
                logger.error("SHRBillUtil.getAdminOrgUnit err", var6);
            }

            if (c != null && c.size() > 0) {
                personPositionInfo = c.get(0);
            }

            return personPositionInfo;
        }
    }

}
