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.dao.ormapping.ObjectUuidPK;
import com.kingdee.eas.base.permission.UserFactory;
import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.basedata.org.*;
import com.kingdee.eas.basedata.person.PersonFactory;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.framework.ObjectBaseInfo;
import com.kingdee.eas.hr.affair.FluctuationBizBillEntryInfo;
import com.kingdee.eas.hr.affair.FluctuationBizBillFactory;
import com.kingdee.eas.hr.affair.FluctuationBizBillInfo;
import com.kingdee.eas.hr.base.*;
import com.kingdee.eas.hr.emp.PersonPositionFactory;
import com.kingdee.eas.hr.emp.PersonPositionInfo;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.ats.web.util.SHRBillUtil;

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

/**
 * 调动
 */
public class SaveFluctuationBizBillService implements IHRMsfService {

    @Override
    public Object process(Context context, Map<String, Object> map) throws EASBizException, BOSException {
        System.out.println("SaveFluctuationBizBillService" + map);
        StringBuffer reason = new StringBuffer();
        String personNumbe = (String)map.get("personNumber");
        String bizDate = (String)map.get("bizDate");
        String position = (String)map.get("positionName");
        String remarks = (String)map.get("description");
//        String applier = (String)map.get("createPerson");
//        String applyDate = (String)map.get("createDate");
        String variationReason = (String)map.get("variationReasonInfoNumber");
        // 调动后 部门 编码
        String orgUnitNumber = (String)map.get("orgUnitNumber");
        // 直接上级
        String leaderPersonNumber = (String)map.get("leaderPersonNumber");

        if (StringUtils.isBlank(personNumbe)){
            reason.append("调动人员编码不能为空;");
        }
//        if (StringUtils.isBlank(applier)){
//            reason.append("制单人员编码不能为空;");
//        }
        if (StringUtils.isBlank(position)){
            reason.append("调动职位名称不能为空;");
        }
        if (StringUtils.isBlank(bizDate)){
            reason.append("调动日期不能为空;");
        }

        Map<Object, Object> resultMap = this.createFluctuationBizBill(context, personNumbe, bizDate, position, remarks, variationReason, orgUnitNumber,leaderPersonNumber);

        return resultMap;
    }

    /**
     * @param ctx
     * @param personNumbe 员工工号
     * @param bizDate 调动日期
     * @param position 调动职位 名称
     * @param remarks 备注
     * @param variationReason 调岗后工作地点
     * @param orgUnitNumber 调动部门编码
     * @param leaderPersonNumber 直接上级
     * @return
     */
    public Map<Object, Object> createFluctuationBizBill(Context ctx, String personNumbe, String bizDate, String position, String remarks, String variationReason  , String orgUnitNumber,String leaderPersonNumber) {
        Map<Object, Object> returnMap = new HashMap();
        //调动单对象
        FluctuationBizBillInfo info = new FluctuationBizBillInfo();
        //调动单分录对象
        FluctuationBizBillEntryInfo enInfo = new FluctuationBizBillEntryInfo();

        //员工个人信息
        PersonInfo peInfo = new PersonInfo();
        //职位
        PositionInfo oldPoInfo = new PositionInfo();
        //行政组织单元
        AdminOrgUnitInfo oldAdInfo = new AdminOrgUnitInfo();
        AdminOrgUnitInfo oldCompanyInfo = new AdminOrgUnitInfo();
        //用工关系状态
        EmployeeTypeInfo emsInfo = new EmployeeTypeInfo();
        //变动原因
        VariationReasonInfo varInfo = new VariationReasonInfo();
        //职位
        PositionInfo poInfo = new PositionInfo();
        AdminOrgUnitInfo adInfo = new AdminOrgUnitInfo();
        AdminOrgUnitInfo companyInfo = new AdminOrgUnitInfo(); //

        PersonInfo ueInfo = new PersonInfo();
        Date compDates = null;
        boolean isK = false;
        String msg = null;
        String fid = null;
        String fnumber = null;
        StringBuffer reason = new StringBuffer();
        String msgType = null;


        try {
            HROrgUnitInfo hrInfo = HROrgUnitFactory.getLocalInstance(ctx).getHROrgUnitInfo(new ObjectUuidPK("00000000-0000-0000-0000-000000000000CCE7AED4"));
            //hr组织
            info.setHrOrgUnit(hrInfo);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            PersonInfo shrPerson = SHRBillUtil.getCurrPersonInfo();

            info.setApplyDate(new Date());
            Map pe;
            // 取到 制表人 的   员工信息 pe ，用户信息 ue
            pe = this.getPerson(ctx, shrPerson.getNumber()); //制单人工号
            if (pe.get("pe") != null) {
                ueInfo = (PersonInfo)pe.get("pe");
                // 申请人
                info.setApplier(ueInfo);
            } else {
                reason.append("制单人编码有误,请认真检查;");
            }

            pe = this.getPerson(ctx, personNumbe);//调动员工编码
            if (pe.get("pe") != null) {
                //员工个人信息
                peInfo = (PersonInfo)pe.get("pe");
                // 分录 enInfo
                enInfo.setPerson(peInfo);
                // 用工关系
                emsInfo = EmployeeTypeFactory.getLocalInstance(ctx).getEmployeeTypeInfo(new ObjectUuidPK(peInfo.getEmployeeType().getId()));
                enInfo.setOldEmpType(emsInfo);
                enInfo.setEmpType(emsInfo);
            } else {
                reason.append("调动员工编码未能获取员工信息有误,请认真检查;");
            }
            Map ap = this.getPersonAP(ctx, personNumbe);
            if (peInfo != null) {
                // 员工用工关系 ， 入职时间

                String seSql = "SELECT FEnterDate FROM T_HR_EmpLaborRelation where FPERSONID  = '" + peInfo.getId().toString() + "'";
                IRowSet seSet = DbUtil.executeQuery(ctx, seSql);
                if (seSet.next()) {
                    //入职时间
                    compDates = seSet.getDate("FEnterDate");
                }
            }
            //调动者 职位
            if (ap.get("po") != null) {
                // 职位
                oldPoInfo = (PositionInfo)ap.get("po");
                //调动单分录对象 ， 原职位
                enInfo.setOldPosition(oldPoInfo);
            } else {
                reason.append("调动员工职位信息有误,请检查相关员工信息;");
            }
            //调动者 行政组织
            if (ap.get("ad") != null) {
                oldAdInfo = (AdminOrgUnitInfo)ap.get("ad");
                //调动单分录对象 ， 原行政组织
                enInfo.setOldAdminOrg(oldAdInfo);
                oldCompanyInfo = AdminOrgUnitFactory.getLocalInstance(ctx).getAdminOrgUnitInfo(new ObjectUuidPK(oldAdInfo.getCompany().getId()));
                //调动单分录对象 ， 原行政组织
                enInfo.setOldCompany(oldCompanyInfo);
            } else {
                reason.append("调动员工组织信息有误,请检查相关员工信息;");
            }

            // 调动 部门 编码
            boolean isFull = false;
            // 职位编码
            String positionNumber = null;
            if (StringUtils.isNotBlank(orgUnitNumber)){
                AdminOrgUnitCollection adminOrgUnitCollection = AdminOrgUnitFactory.getLocalInstance(ctx).getAdminOrgUnitCollection("where number = '" + orgUnitNumber + "'");
                if (adminOrgUnitCollection.size() > 0){
                    AdminOrgUnitInfo adminOrgUnitInfo = adminOrgUnitCollection.get(0);
                    positionNumber = adminOrgUnitInfo.getNumber();
                    isFull = true;
                }else {
                    reason.append("调动后部门为空,请认真检查;");
                }
                if (isFull){
                    PositionCollection poCOl = PositionFactory.getLocalInstance(ctx).getPositionCollection(" where number  = '" + positionNumber + "'");
                    if (poCOl.size() > 0) {
                        //职位
                        poInfo = poCOl.get(0);
                        //调动单分录对象 ， 职员
                        enInfo.setPosition(poInfo);
                        //行政组织
                        adInfo = AdminOrgUnitFactory.getLocalInstance(ctx).getAdminOrgUnitInfo(new ObjectUuidPK(poInfo.getAdminOrgUnit().getId()));
                        //调动单分录对象 ， 目标组织
                        enInfo.setAdminOrg(adInfo);
                        companyInfo = AdminOrgUnitFactory.getLocalInstance(ctx).getAdminOrgUnitInfo(new ObjectUuidPK(adInfo.getCompany().getId()));
                        //调动单分录对象 ， 公司
                        enInfo.setCompany(companyInfo);

                    }else{
                        reason.append("系统中不存在 职位编码为：" + position + " 的职位;");
                    }
                }else {
                    reason.append("调动后职位与部门编码不匹配;");
                }

            }else {
                PositionCollection poCOl = PositionFactory.getLocalInstance(ctx).getPositionCollection("where number = '" + position + "'");
                if (poCOl.size() > 0) {
                    //职位
                    poInfo = poCOl.get(0);
                    //调动单分录对象 ， 职员
                    enInfo.setPosition(poInfo);
                    //行政组织
                    adInfo = AdminOrgUnitFactory.getLocalInstance(ctx).getAdminOrgUnitInfo(new ObjectUuidPK(poInfo.getAdminOrgUnit().getId()));
                    //调动单分录对象 ， 目标组织
                    enInfo.setAdminOrg(adInfo);
                    companyInfo = AdminOrgUnitFactory.getLocalInstance(ctx).getAdminOrgUnitInfo(new ObjectUuidPK(adInfo.getCompany().getId()));
                    //调动单分录对象 ， 公司
                    enInfo.setCompany(companyInfo);

                }else{
                    reason.append("系统中不存在 职位编码为：" + position + " 的职位;");
                }
            }
            enInfo.setBizDate(format.parse(bizDate));//调动日期(必填)
            //调动单分录对象 ， 备注
            enInfo.setDescription(remarks);// 备注
            //单据业务配置  DawAAAApVj/maL7Z (公司内调动)
            HRBizDefineInfo hrdInfo = HRBizDefineFactory.getLocalInstance(ctx).getHRBizDefineInfo(new ObjectUuidPK("DawAAAApVj/maL7Z"));
            //调动单分录对象 ， 变动操作
            enInfo.setHrBizDefine(hrdInfo);
            //变动类型  7ta1EwaZTZmts8L4z/J0LJYRae4= （调动调出）
            AffairActionReasonInfo affInfo = AffairActionReasonFactory.getLocalInstance(ctx).getAffairActionReasonInfo(new ObjectUuidPK("7ta1EwaZTZmts8L4z/J0LJYRae4="));
            //调动单分录对象 ， 变动类型
            enInfo.setAffairActionReason(affInfo);

            //变动原因编码 ,
            if (StringUtils.isNotBlank(variationReason)) {
                VariationReasonCollection varCol = VariationReasonFactory.getLocalInstance(ctx).getVariationReasonCollection(" where number='" + variationReason + "'");
                if (varCol.size() > 0) {
                    varInfo = varCol.get(0);
                    enInfo.setVariationReason(varInfo);
                } else {
                    reason.append("变动原因有误,请认真检查;");
                }
            } else {// 默认
                VariationReasonCollection varCol = VariationReasonFactory.getLocalInstance(ctx).getVariationReasonCollection(" where number='00101'");
                if (varCol.size() > 0) {

                    varInfo = varCol.get(0);
                    enInfo.setVariationReason(varInfo);
                }
            }
            info.getEntrys().add(enInfo);
            FluctuationBizBillFactory.getLocalInstance(ctx).submitEffect(info);
        } catch (Exception e) {
            e.getMessage();
            reason.append(e.getMessage());
        }
        if (reason.length() > 0) {
            returnMap.put("msgType", "0");
            returnMap.put("msg", reason.toString());
        } else {
            returnMap.put("msgType", "1");
            returnMap.put("msg", "success");
            returnMap.put("fnumber", info.getNumber());
        }
        return returnMap;
    }



    // 员工跟用户之间
    public Map<String, ObjectBaseInfo> getPerson(Context ctx, String number) {
        Map<String, ObjectBaseInfo> map = new HashMap();
        PersonInfo peInfo = null;
        UserInfo ueInfo = null;
        String sql = "SELECT pe.FID PEID , UE.FID  UEID FROM T_BD_PERSON PE LEFT OUTER JOIN T_PM_USER UE ON UE.FPersonId = PE.FID WHERE PE.FNUMBER = '" + number + "'";

        try {
            IRowSet asSet = DbUtil.executeQuery(ctx, sql.toString());
            if (asSet.next()) {
                if (asSet.getString("PEID") != null) {
                    peInfo = PersonFactory.getLocalInstance(ctx).getPersonInfo(new ObjectUuidPK(asSet.getString("PEID")));
                }

                if (asSet.getString("UEID") != null) {
                    ueInfo = UserFactory.getLocalInstance(ctx).getUserInfo(new ObjectUuidPK(asSet.getString("UEID")));
                }
            }
        } catch (BOSException var8) {
            var8.printStackTrace();
        } catch (SQLException var9) {
            var9.printStackTrace();
        } catch (EASBizException var10) {
            var10.printStackTrace();
        }

        map.put("pe", peInfo);
        map.put("ue", ueInfo);
        return map;
    }


    /**
     * 根据调动者number，查询员工职位id，职位id，行政组织id
     * @param ctx
     * @param number
     * @return
     */
    public Map<String, ObjectBaseInfo> getPersonAP(Context ctx, String number) {
        Map<String, ObjectBaseInfo> map = new HashMap();
        //员工职位信息
        PersonPositionInfo psoInfo = null;
        //行政组织单元
        AdminOrgUnitInfo adInfo = null;
        //职位
        PositionInfo poInfo = null;
        //根据调动者number，查询员工职位id，职位id，行政组织id
        String sql = "SELECT PSO.FID PSOID,PO.FID POID,AD.FID ADID FROM T_BD_PERSON PE INNER JOIN T_HR_PERSONPOSITION PSO ON PE.FID = PSO.FPERSONID LEFT OUTER JOIN T_ORG_POSITION PO ON PO.FID = PSO.FPRIMARYPOSITIONID LEFT OUTER JOIN T_ORG_ADMIN AD ON AD.FID = PO.FADMINORGUNITID WHERE PE.FNUMBER = '" + number + "'";

        try {
            IRowSet asSet = DbUtil.executeQuery(ctx, sql.toString());
            if (asSet.next()) {
                //员工职位id
                if (asSet.getString("PSOID") != null) {
                    //调动者，员工职位信息
                    psoInfo = PersonPositionFactory.getLocalInstance(ctx).getPersonPositionInfo(new ObjectUuidPK(asSet.getString("PSOID")));
                }
                //职位id
                if (asSet.getString("POID") != null) {
                    //调动者，职位
                    poInfo = PositionFactory.getLocalInstance(ctx).getPositionInfo(new ObjectUuidPK(asSet.getString("POID")));
                    //行政组织id
                    if (asSet.getString("ADID") != null) {
                        //调动者，行政组织
                        adInfo = AdminOrgUnitFactory.getLocalInstance(ctx).getAdminOrgUnitInfo(new ObjectUuidPK(asSet.getString("ADID")));
                    }
                } else {
                    //查询调动员工历史任职记录，组织，岗位
                    String exSql = "select FAdminOrgID,FPositionID from T_HR_EmpPostExperienceHis where FPersonID = (SELECT FID FROM T_BD_PERSON WHERE FNUMBER = '" + number + "') " + "order by FEndDateTime desc";
                    IRowSet exSet = DbUtil.executeQuery(ctx, exSql.toString());
                    if (exSet.next() && exSet.getString("FPositionID") != null) {
                        //职位
                        poInfo = PositionFactory.getLocalInstance(ctx).getPositionInfo(new ObjectUuidPK(exSet.getString("FPositionID")));
                        if (exSet.getString("FAdminOrgID") != null) {
                            //行政组织
                            adInfo = AdminOrgUnitFactory.getLocalInstance(ctx).getAdminOrgUnitInfo(new ObjectUuidPK(exSet.getString("FAdminOrgID")));
                        }
                    }
                }
            }
        } catch (BOSException var11) {
            var11.printStackTrace();
        } catch (SQLException var12) {
            var12.printStackTrace();
        } catch (EASBizException var13) {
            var13.printStackTrace();
        }
        //调动者number，员工职位id
        map.put("pso", psoInfo);
        //调动者，职位
        map.put("po", poInfo);
        //调动者，行政组织
        map.put("ad", adInfo);
        System.out.println("getPersonAP:" + map);
        return map;
    }
}
