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.ResignBizBillEntryInfo;
import com.kingdee.eas.hr.affair.ResignBizBillFactory;
import com.kingdee.eas.hr.affair.ResignBizBillInfo;
import com.kingdee.eas.hr.base.*;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.ats.web.util.SHRBillUtil;

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

/**
 * 离职
 */
public class SaveResignBizBillService implements IHRMsfService {
    @Override
    public Object process(Context context, Map map) throws EASBizException, BOSException {
        System.out.println("SaveResignBizBillService" + map);
        Map<String , Object> result = new HashMap<String,Object>();
        try {
            StringBuilder errLog = new StringBuilder();
            // 根节点
            String orgTop = "00000000-0000-0000-0000-000000000000CCE7AED4";
            // 必填
            String personNumber = (String)map.get("personNumber");
            String bizDate = (String) map.get("bizDate");//离职日期
            String leftCompanyDate = (String) map.get("leftCompanyDate");//最后工作日
            String forbidUserDate = (String) map.get("forbidUserDate");//禁用用户日期
            //非必填
            String description = (String)map.get("description");//备注
            String actionReasonInfoNumber = (String) map.get("actionReasonInfoNumber");//变动类型
            if(StringUtils.isBlank(personNumber)){
                errLog.append("员工工号不能为空;");
            }
            if(StringUtils.isBlank(bizDate)){
                errLog.append("离职日期不能为空!;");
            }
            if(StringUtils.isBlank(leftCompanyDate)){
                errLog.append("最后工作日不能为空;");
            }
            if (StringUtils.isBlank(forbidUserDate)){
                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 ");
            stringBuilder.append(" from t_bd_person p ");
            stringBuilder.append(" left join T_HR_PERSONPOSITION pp on pp.fpersonid=p.fid ");
            stringBuilder.append(" where p.fnumber='" + personNumber + "'");
            IRowSet rs = DbUtil.executeQuery(context,stringBuilder.toString());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat formatDateNum = new SimpleDateFormat("yyyyMMdd-SSS");
            // 离职单
            ResignBizBillInfo billInfo = new ResignBizBillInfo();
            // 业务时间（生成时间）
            billInfo.setBizDate(new Date());
            //制单人
            PersonInfo shrPerson = SHRBillUtil.getCurrPersonInfo();
            billInfo.setApplier(shrPerson);
            billInfo.setApplyDate(new Date());//申请日期

            // 管理单元
            CtrlUnitInfo cu = new CtrlUnitInfo();
            cu.setId(BOSUuid.read(orgTop));
            //控制单元
            billInfo.setCU(cu);

            //HR组织
            HROrgUnitInfo hrOrgUnitInfo = new HROrgUnitInfo();
            hrOrgUnitInfo.setId(BOSUuid.read(orgTop));
            billInfo.setHrOrgUnit(hrOrgUnitInfo);

            //离职单分录
            ResignBizBillEntryInfo entry = new ResignBizBillEntryInfo();
            //设置单据头
            entry.setBill(billInfo);
            entry.setEmpNumber(personNumber);
            //离职员工
            PersonCollection personCollection = PersonFactory.getLocalInstance(context).getPersonCollection("where number='" + personNumber + "'");
            if(personCollection.size() > 0){
                PersonInfo personInfo = personCollection.get(0);
                entry.setPerson(personInfo);
            }

            //离职日期
            entry.setBizDate(simpleDateFormat.parse(bizDate));
            String a = bizDate + " 00:00:00";
            entry.setBizTime(Timestamp.valueOf(a));

            if (StringUtils.isNotBlank(description)){
                entry.setDescription(description);//备注
            }

            if(rs.next()){
                // 所在部门
                String depID = rs.getString("FPersonDep");
                // 主要任职
                String primaryPositionID = rs.getString("FPrimaryPositionID");

                String companyID = rs.getString("FCompanyID");
                // 用户关系
                String employeeTypeID = rs.getString("FEmployeeTypeID");
                //  入职时间， 生效时间
                Date enterDate = rs.getDate("FEnterDate");
                if(StringUtils.isNotBlank(depID)) {
                    // 行政组织单元
                    AdminOrgUnitInfo dep = new AdminOrgUnitInfo();
                    dep.setId(BOSUuid.read(depID));
                    // 离职
                    billInfo.setAdminOrg(dep);
                    // 离职分录
                    entry.setOldAdminOrg(dep);
                    entry.setAdminOrg(dep);
                }

                //职位
                PositionInfo positionInfo = new PositionInfo();
                if(StringUtils.isNotBlank(primaryPositionID)){
                    positionInfo.setId(BOSUuid.read(primaryPositionID));
                }
                // 分录
                entry.setOldPosition(positionInfo);
                entry.setPosition(positionInfo);

                if(StringUtils.isNotBlank(employeeTypeID)){
                    EmployeeTypeInfo oldEmployeeType = new EmployeeTypeInfo();
                    oldEmployeeType.setId(BOSUuid.read(employeeTypeID));
                    entry.setOldEmpType(oldEmployeeType);
                }
                // 离职分录
                entry.setSeq(1); // 单据分录序列号
                entry.setEnterDate(enterDate); //入职时间

                //公司
                AdminOrgUnitInfo company = new AdminOrgUnitInfo();
                company.setId(BOSUuid.read(companyID));
                entry.setCompany(company);
                entry.setOldCompany(company);

            }else {
                errLog.append("未找到员工工号为" + personNumber + "的有效信息;");
            }

            //  单据业务配置   辞职
            HRBizDefineInfo defineInfo = new HRBizDefineInfo();
            defineInfo.setId(BOSUuid.read("DawAAAApViXmaL7Z"));
            //变动操作
            entry.setHrBizDefine(defineInfo);
            // 用工关系
            EmployeeTypeInfo employeeType = new EmployeeTypeInfo();
            //目标员工状态  离职
            employeeType.setId(BOSUuid.read("00000000-0000-0000-0000-000000000007A29E85B3"));
            entry.setEmpType(employeeType);

            if(StringUtils.isBlank(actionReasonInfoNumber)){
                // 变动类型  辞职
                AffairActionReasonInfo actionReasonInfo = new AffairActionReasonInfo();
                actionReasonInfo.setId(BOSUuid.read("+/Fqq82IQ2Cxm2PNypBkD5YRae4="));
                entry.setAffairActionReason(actionReasonInfo);
            }else{
                AffairActionReasonInfo affairActionReasonInfo = AffairActionReasonFactory.getLocalInstance(context).getAffairActionReasonInfo("where number='" + actionReasonInfoNumber + "'");
                entry.setAffairActionReason(affairActionReasonInfo);
            }

            //变动原因
            String variationReasonInfoNumber = (String) map.get("variationReasonInfoNumber");
            if(StringUtils.isBlank(variationReasonInfoNumber)){
                VariationReasonInfo variationReasonInfo = new VariationReasonInfo();
                variationReasonInfo.setId(BOSUuid.read("Y3K05Pu2QNiAxV/oBHXFUuas36w="));
                entry.setVariationReason(variationReasonInfo);
            }else{
                VariationReasonInfo variationReasonInfo = VariationReasonFactory.getLocalInstance(context).getVariationReasonInfo("where number='" + variationReasonInfoNumber + "'");
                entry.setVariationReason(variationReasonInfo);
            }
            // 用工单位
            entry.setEmployerUnit(hrOrgUnitInfo);
            entry.setUseDefault(true);//使用默认管理关系

            entry.setLeftCompanyDate(simpleDateFormat.parse(leftCompanyDate)); //最后工作日
            entry.setForbidUserDate(simpleDateFormat.parse(forbidUserDate)); //禁用用户日期

            billInfo.getEntrys().add(entry);
            ResignBizBillFactory.getLocalInstance(context).submitEffect(billInfo);
            if (errLog.length()>0){
                result.put("msgType","0");
                result.put("msg",errLog.toString());
            }else{
                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;
    }

}
