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.dao.IObjectPK;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.basedata.org.AdminOrgUnitInfo;
import com.kingdee.eas.basedata.org.CtrlUnitInfo;
import com.kingdee.eas.basedata.org.HROrgUnitInfo;
import com.kingdee.eas.basedata.org.PositionInfo;
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.EmpHireBizBillEntryCollection;
import com.kingdee.eas.hr.affair.EmpHireBizBillEntryInfo;
import com.kingdee.eas.hr.affair.EmpHireBizBillFactory;
import com.kingdee.eas.hr.affair.EmpHireBizBillInfo;
import com.kingdee.eas.hr.base.*;
import com.kingdee.eas.hr.org.JobGradeFactory;
import com.kingdee.eas.hr.org.JobGradeInfo;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.ats.web.util.SHRBillUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 转正
 */
public class SaveEmpHireBizBillService implements IHRMsfService {
    @Override
    public Object process(Context context, Map map) throws EASBizException, BOSException {
        System.out.println("SaveEmpHireBizBillServiceParam=" + map);
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            //根组织
            String orgTop = "00000000-0000-0000-0000-000000000000CCE7AED4";
            StringBuilder errLog = new StringBuilder();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String personNumber = (String) map.get("personNumber");//编码
            String bizDate = (String)map.get("bizDate");//转正日期

            //非必填
            String description = (String)map.get("description"); //备注
            String rankPosition = (String)map.get("rankPosition");//职位编码
            String employeeType = (String)map.get("employeeType");//用工类型编码
            String grade = (String)map.get("grade");//考核成绩
            String jobGrade = (String)map.get("jobGrade");//转正后职等编码

            String summary = (String)map.get("summary");//工作总结
            if (StringUtils.isBlank(personNumber)) {
                errLog.append("员工工号不能为空;");
            }
            if (StringUtils.isBlank(bizDate)) {
                errLog.append("转正日期不能为空;");
            }

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(" /*dialect*/select pp.FCompanyID,pp.FPersonDep,pp.FPrimaryPositionID,isnull(pp.FEnterDate,p.FEFFDT) FEnterDate, ");
            stringBuilder.append(" p.FEmployeeTypeID,epr.FJobGradeID,er.FTryoutMonth,er.FPlanFormalDate ");
            stringBuilder.append(" from t_bd_person p ");
            stringBuilder.append(" left join T_HR_PERSONPOSITION pp on pp.fpersonid=p.fid ");
            stringBuilder.append(" left join T_HR_EmpPostRank epr on epr.FPersonID=p.fid and epr.fisLatest=1 ");
            stringBuilder.append(" left join T_HR_EmpLaborRelation er on er.FPersonID=p.fid and er.FlEFFDT = '2199-12-20' ");
            stringBuilder.append(" where p.Fnumber= ? ");
            IRowSet rs = DbUtil.executeQuery(context, stringBuilder.toString(),new Object[]{personNumber});
            //入职转正
            EmpHireBizBillInfo billInfo = new EmpHireBizBillInfo();
            billInfo.setBizDate(new Date());
            //制单人
            PersonInfo shrPerson = SHRBillUtil.getCurrPersonInfo();
            billInfo.setApplier(shrPerson);
            billInfo.setApplyDate(new Date());//申请日期
            //控制单元
            CtrlUnitInfo cu = new CtrlUnitInfo();
            //uuid生成规则
            cu.setId(BOSUuid.read(orgTop));
            billInfo.setCU(cu);
            //行政组织
            HROrgUnitInfo hrOrgUnitInfo = new HROrgUnitInfo();
            hrOrgUnitInfo.setId(BOSUuid.read(orgTop));
            billInfo.setHrOrgUnit(hrOrgUnitInfo);
            //转正单分录，集合
            EmpHireBizBillEntryInfo entry = new EmpHireBizBillEntryInfo();
            entry.setBill(billInfo);
            entry.setBizDate(simpleDateFormat.parse(bizDate));//转正日期
            //员工用工关系
            EmpLaborRelationInfo empLaborRelationInfo = null;
            PersonCollection personCollection = PersonFactory.getLocalInstance(context).getPersonCollection("where number='" + personNumber + "'");
            if (personCollection.size() > 0) {
                PersonInfo personInfo = personCollection.get(0);
                entry.setPerson(personInfo);
                EmpLaborRelationCollection empLaborRelationCollection = EmpLaborRelationFactory.getLocalInstance(context).getEmpLaborRelationCollection("where person='" + personInfo.getId() + "'");
                if (empLaborRelationCollection.size() > 0) {
                    empLaborRelationInfo = empLaborRelationCollection.get(0);
                    //获取用工关系状态
                    EmployeeTypeInfo laborRelationState = empLaborRelationInfo.getLaborRelationState();
                    //上一个用工关系状态
                    empLaborRelationInfo.setLastLaborRelaState(laborRelationState);
                    //EmployeeType ,用工关系状态，1正式员工
                    EmployeeTypeInfo employeeTypeInfo = EmployeeTypeFactory.getLocalInstance(context).getEmployeeTypeInfo("where number='001'");
                    //更新用工关系状态
                    empLaborRelationInfo.setLaborRelationState(employeeTypeInfo);
                    //实际转正时间
                    empLaborRelationInfo.setActualFormalDate(simpleDateFormat.parse(bizDate));
                }
            }else {
                errLog.append("未找到员工工号为" + personNumber + "员工信息;");
            }
            if (StringUtils.isNotBlank(description)){
                entry.setDescription(description); //备注
            }

            //申请人员工
            if (rs.next()){
                //员工部门
                String depID = rs.getString("FPersonDep");
                //职位id
                String primaryPositionID = rs.getString("FPrimaryPositionID");
                //员工用工关系
                String employeeTypeID = rs.getString("FEmployeeTypeID");
                String companyID = rs.getString("FCompanyID");
                //入职时间
                Date enterDate = rs.getDate("FEnterDate");
                //职等
                String FJobGradeID = rs.getString("FJobGradeID");
                //预计转入时间
                Date FPlanFormalDate = rs.getDate("FPlanFormalDate");
                //试用期
                int FTryoutMonth = rs.getInt("FTryoutMonth");
                //预计转入时间
                entry.setPlanFormalDate(FPlanFormalDate);
                if (StringUtils.isNotBlank(depID)) { // 部门
                    AdminOrgUnitInfo dep = new AdminOrgUnitInfo();
                    dep.setId(BOSUuid.read(depID));
                    billInfo.setAdminOrg(dep);
                    entry.setAdminOrg(dep);
                    entry.setOldAdminOrg(dep);
                }
                if (StringUtils.isNotBlank(primaryPositionID)) { // 职位
                    PositionInfo positionInfo = new PositionInfo();
                    positionInfo.setId(BOSUuid.read(primaryPositionID));
                    entry.setPosition(positionInfo);
                    entry.setOldPosition(positionInfo);
                }
                if (StringUtils.isNotBlank(FJobGradeID)) { // 职等
                    JobGradeInfo jobGradeInfo = new JobGradeInfo();
                    jobGradeInfo.setId(BOSUuid.read(FJobGradeID));
                    entry.setOldJobGrade(jobGradeInfo);
                }
                //转正单分录，入职时间
                entry.setEnrollDate(enterDate);
                //转正单分录，试用期
                entry.setProbation(FTryoutMonth);
                //单据分录序列号
                entry.setSeq(1);
                //行政组织单元
                AdminOrgUnitInfo company = new AdminOrgUnitInfo();
                //id
                company.setId(BOSUuid.read(companyID));
                //变动前公司
                entry.setOldCompany(company);
                //员工任职
                if (StringUtils.isNotBlank(employeeTypeID)) {
                    EmployeeTypeInfo oldEmployeeType = new EmployeeTypeInfo();
                    oldEmployeeType.setId(BOSUuid.read(employeeTypeID));
                    entry.setOldEmpType(oldEmployeeType);
                }
            }
            if (StringUtils.isNotBlank(rankPosition)) {
                PositionInfo positionInfo = new PositionInfo();
                positionInfo.setId(BOSUuid.read(rankPosition));
                entry.setPosition(positionInfo);//职位编码
            }
            if (StringUtils.isBlank(employeeType)) { //用工类型编码
                employeeType = "001";
            }
            EmployeeTypeInfo employeeTypeInfo = EmployeeTypeFactory.getLocalInstance(context).getEmployeeTypeInfo("where number='" + employeeType + "'");
            entry.setEmpType(employeeTypeInfo);

            if (StringUtils.isNotBlank(grade)) { //考核成绩
                entry.setGrade(grade);
            }
            if (StringUtils.isNotBlank(jobGrade)) { //转正后职等编码
                //职等
                JobGradeInfo jobGradeInfo = JobGradeFactory.getLocalInstance(context).getJobGradeInfo("where number='" + jobGrade + "'");
                entry.setJobGrade(jobGradeInfo);
            }
            if (StringUtils.isNotBlank(summary)) {
                entry.setSummary(summary); //工作总结
            }

            //变动操作编码(非必填)
            String defineInfoNumber = (String)map.get("defineInfoNumber");
            if (StringUtils.isBlank(defineInfoNumber)) {
                defineInfoNumber = "SHR03";
            }
            //单据业务配置,默认转正
            HRBizDefineInfo hrBizDefineInfo = HRBizDefineFactory.getLocalInstance(context).getHRBizDefineInfo("where number='" + defineInfoNumber + "'");
            entry.setHrBizDefine(hrBizDefineInfo);
            //变动类型编码(非必填)
            String actionReasonInfoNumber = (String)map.get("actionReasonInfoNumber");
            if (StringUtils.isBlank(actionReasonInfoNumber)) {
                actionReasonInfoNumber = "0302";
            }
            //变动类型，默认转正
            AffairActionReasonInfo actionReasonInfo = AffairActionReasonFactory.getLocalInstance(context).getAffairActionReasonInfo("where number='" + actionReasonInfoNumber + "'");
            entry.setAffairActionReason(actionReasonInfo);

            //单分录，行政组织
            entry.setEmployerUnit(hrOrgUnitInfo);
            //默认管理关系
            entry.setUseDefault(true);
            //单分录，hr组织
            entry.setHrOrgUnit(hrOrgUnitInfo);
            billInfo.getEntrys().add(entry);

            EmpHireBizBillFactory.getLocalInstance(context).submitEffect(billInfo);
            if (errLog.length() > 0) {
                result.put("msgType", "0");
                result.put("msg", errLog.toString());
            } else {
                // 入职转正 , 员工用工关系 ,  单分录
                //String id = submitEffect(billInfo, empLaborRelationInfo, entryColl, context, uipk);
                result.put("msgType", "1");
                result.put("msg", "success");
                result.put("fnumber", billInfo.getNumber());
            }
        }catch (Exception e){
            e.printStackTrace();
            result.put("msgType", "0");
            result.put("msg", e.getMessage());
        }
        return result;
    }
}
