package com.kingdee.eas.hr.affair.app;

import java.sql.Date;
import java.sql.SQLException;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.IObjectValue;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.framework.CoreBaseCollection;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.eas.hr.affair.IPluralityAddBizBillEntry;
import com.kingdee.eas.hr.affair.IPluralityDelBizBill;
import com.kingdee.eas.hr.affair.PluralityAddBizBillEntryFactory;
import com.kingdee.eas.hr.affair.PluralityAddBizBillEntryInfo;
import com.kingdee.eas.hr.affair.PluralityDelBizBillEntryCollection;
import com.kingdee.eas.hr.affair.PluralityDelBizBillEntryInfo;
import com.kingdee.eas.hr.affair.PluralityDelBizBillFactory;
import com.kingdee.eas.hr.affair.PluralityDelBizBillInfo;
import com.kingdee.eas.hr.base.EmpPosOrgRelationFactory;
import com.kingdee.eas.hr.base.EmpPosOrgRelationInfo;
import com.kingdee.eas.hr.base.IEmpPosOrgRelation;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.compensation.CmpEmpORelationFactory;
import com.kingdee.shr.compensation.CmpEmpORelationInfo;
import com.kingdee.shr.compensation.ICmpEmpORelation;

/**
 * 扩展了PluralityDelBizBillControllerBean类，增加了在提交单据后的endDate更新逻辑。
 */
public class PluralityDelBizBillControllerBeanEx extends PluralityDelBizBillControllerBean {

    /**
     * 覆盖父类的_submitEffect方法，在提交单据后更新endDate。
     * @param ctx 上下文对象
     * @param model 单据模型
     * @return 单据主键
     * @throws BOSException 业务基础服务异常
     * @throws EASBizException EAS业务异常
     */
    @Override
    protected IObjectPK _submitEffect(Context ctx, CoreBaseInfo model) throws BOSException, EASBizException {
        // 调用父类的_submitEffect方法获取单据主键
        IObjectPK objectPk = super._submitEffect(ctx, model);
        // 更新endDate
        updateEndDate(ctx, model);
        return objectPk;
    }

    
    /**
     * 覆盖父类的_submit方法，在提交单据后更新endDate。
     * @param ctx 上下文对象
     * @param model 单据模型
     * @return 单据主键
     * @throws BOSException 业务基础服务异常
     * @throws EASBizException EAS业务异常
     */
    @Override
    protected IObjectPK _submit(Context ctx, IObjectValue model) throws BOSException, EASBizException {
        // 调用父类的_submit方法获取单据主键
        IObjectPK objectPk = super._submit(ctx, model);
        // 更新endDate
        updateEndDate(ctx, model);
        return objectPk;
    }

    /**
     * 更新单据中的endDate字段。
     * @param ctx 上下文对象
     * @param model 单据模型
     * @throws EASBizException EAS业务异常
     * @throws BOSException 业务基础服务异常
     */
    public void updateEndDate(Context ctx, IObjectValue model) throws EASBizException, BOSException {
        // 将模型转换为PluralityDelBizBillInfo类型
        PluralityDelBizBillInfo billInfo = (PluralityDelBizBillInfo) model;
        // 获取单据ID
        String billId = billInfo.getId().toString();
        // 获取单据条目集合
        PluralityDelBizBillEntryCollection entrys = billInfo.getEntrys();
        // 如果条目集合不为空且大小大于0，则遍历条目集合
        if (null != entrys && entrys.size() > 0) {
            for (int i = 0; i < entrys.size(); i++) {
                // 获取单据条目信息
                PluralityDelBizBillEntryInfo entryInfo = entrys.get(i);
                // 检查并更新添加单据的endDate
                checkAddBill(ctx, entryInfo.getId().toString(),1);
                //更新变更记录
                checkRelation(ctx,entryInfo.getId().toString(),null,1);

            }
        }
    }

    /**
     * 检查并更新添加单据的endDate。
     * @param ctx 上下文对象
     * @param entryId 单据条目ID
     * @param type  1:审核 ; 0:反审核
     * @throws BOSException 业务基础服务异常
     * @throws EASBizException EAS业务异常
     */
    private Date checkAddBill(Context ctx, String entryId, int type) throws BOSException, EASBizException {
//        // 创建删除单据条目集合
//        CoreBaseCollection delEnCol = new CoreBaseCollection();
        // 构建SQL查询语句
        StringBuilder sbu = new StringBuilder();
        sbu.append(" select  bill.fid addId  , entry.fid  addEnId ,entry.fendDate addEndDate  ");
        // SQL语句中重复的select关键字可能是错误，这里假设应该是逗号
        sbu.append(" ,entry.cfoldEndDate oldAddEDate  , delen.fbizDate  newEDate  ");
        sbu.append(" from T_HR_PluralityAddBizBill  bill ");
        sbu.append(" left join  T_HR_PluralityAddBizBillEntry  entry on bill.FId = entry.fbillid ");
        sbu.append(" left join  T_HR_PluralityDelBizBillEntry  delen   ");
        sbu.append(" on  entry.fpersonid = delen.fpersonid   ");
        
        sbu.append(" and  entry.FBizDate = delen.FBeginDate  ");
        sbu.append(" and  entry.fpositionid = delen.FOldPositionID  ");
        sbu.append(" and   (   ");
        sbu.append(" entry.cfpthwage = delen.cfpthwage   ");
        sbu.append(" OR  ( entry.cfpthwage IS NULL AND delen.cfpthwage IS NULL  ) ");
        sbu.append("  )   ");
        sbu.append(" and   (   ");
        sbu.append(" entry.cfptlmanagerid = delen.cfptlmanagerid   ");
        sbu.append(" OR  ( entry.cfptlmanagerid IS NULL AND delen.cfptlmanagerid IS NULL  ) ");
        sbu.append("  )   ");
        sbu.append(" where  bill.fbillstate = '3'  ");
        sbu.append(" and  delen.fid = '" + entryId + "'");
        //反审核
        if( type == 0 ) {
        	return restoreAddBillEndDate(ctx, sbu.toString());
        }else if( type == 1 ) {
            //审核
        	return updateAddBillEndDate(ctx, sbu.toString());
        }
        return null;
    }



    /**
     * 检查并更新变动记录的endDate。
     * @param ctx 上下文对象
     * @param entryId 单据条目ID
     * @param type  1:审核 ; 0:反审核
     * @throws BOSException 业务基础服务异常
     * @throws EASBizException EAS业务异常
     */
    private Date checkRelation(Context ctx, String entryId, Date newDate , int type) throws BOSException, EASBizException {
        // 构建SQL查询语句
        StringBuilder sbu = new StringBuilder();
        sbu.append(" select   bill.fid  billId   ");
        sbu.append(" , cmpBill.FID  cmpBillId  ");
        sbu.append(" , delen.fbizDate  newEDate  ");
        sbu.append(" from T_HR_EmpOrgRelation  bill ");
        sbu.append(" left join T_HR_SCmpEmpORelation  cmpBill ");
        sbu.append(" on  bill.FID = cmpBill.femporgrelationid   ");
        sbu.append(" left join  T_HR_PluralityDelBizBillEntry  delen   ");
        sbu.append(" on  bill.fpersonid = delen.fpersonid   ");
        
        sbu.append(" and  bill.feffdt = delen.FBeginDate  ");
        sbu.append(" and  bill.fpositionid = delen.FOldPositionID  ");
        sbu.append(" and   (   ");
        sbu.append(" bill.CFLineManagerNameI = delen.cfptlmanagerid   ");
        sbu.append(" OR  ( bill.CFLineManagerNameI IS NULL AND delen.cfptlmanagerid IS NULL  ) ");
        sbu.append("  )   ");
        sbu.append(" where    ");
        sbu.append(" delen.fid = '" + entryId + "'");
        //反审核
        if( type == 0 ) {
            return updateRelationEndDate(ctx, sbu.toString(),newDate,type);
        }else if( type == 1 ) {
            //审核
            return updateRelationEndDate(ctx, sbu.toString(),null,type);
        }
        return  null;
    }








    /**
     * 更新变动记录结束日期
     * @param ctx
     * @param sqlStr
     * @param newEDate
     * @param opType 0,反审核;  1,审核
     * @return
     */
    private  Date  updateRelationEndDate(Context ctx, String sqlStr,Date newEDate,int opType ) {
        // 创建添加单据条目集合
        CoreBaseCollection addEnCol = new CoreBaseCollection();
        try {
            // 获取添加单据条目实例
            IEmpPosOrgRelation  billIns = EmpPosOrgRelationFactory.getLocalInstance(ctx);
            ICmpEmpORelation cmpBillIns = CmpEmpORelationFactory.getLocalInstance(ctx);
            // 执行SQL查询
            IRowSet rowSet = DbUtil.executeQuery(ctx, sqlStr);
            // 遍历查询结果
            while (rowSet.next()) {
                // 获取添加单据条目ID
                String billId = rowSet.getString("billId");
                // 获取薪酬档案记录ID
                String cmpBillId = rowSet.getString("cmpBillId");
                // 获取新的endDate 审核的时候;
                if(opType ==  1){
                    newEDate = rowSet.getDate("newEDate");
                }
                // 变动记录
                EmpPosOrgRelationInfo billInfo = billIns.getEmpPosOrgRelationInfo(new ObjectUuidPK(billId));
                //薪酬 记录
                CmpEmpORelationInfo cmpInfo = cmpBillIns.getCmpEmpORelationInfo(new ObjectUuidPK(cmpBillId));
                if ( null != newEDate) {
                    //结束日期 = 单据创建时的结束日期
                    billInfo.setLEFFDT(newEDate);
                    billInfo.setEndDateTime(newEDate);
                    cmpInfo.setLeffectDate(newEDate);
                }
//                addEnCol.add(billInfo);
                billIns.update(new ObjectUuidPK(billId),billInfo);
                cmpBillIns.update(new ObjectUuidPK(cmpBillId),cmpInfo);
            }
            // 更新 集合
//            billIns.update(addEnCol);
        } catch (BOSException | SQLException | EASBizException e) {
            e.printStackTrace();
        }
        return newEDate;
    }





    
    private  Date  updateAddBillEndDate(Context ctx, String sqlStr) {
        Date newEDate = null;
        // 创建添加单据条目集合
        CoreBaseCollection addEnCol = new CoreBaseCollection();
    	try {
            // 获取添加单据条目实例
            IPluralityAddBizBillEntry addEnIns = PluralityAddBizBillEntryFactory.getLocalInstance(ctx);
            // 执行SQL查询
            IRowSet rowSet = DbUtil.executeQuery(ctx, sqlStr);
            // 遍历查询结果
            while (rowSet.next()) {
            	// 获取添加单据条目ID
            	String addEnId = rowSet.getString("addEnId");
            	// 获取 原兼职单上创建时的日期,第一次写兼职结束时是空的;
            	Date oldAddEDate = rowSet.getDate("oldAddEDate");
            	// 获取oldEDate
            	Date addEndDate = rowSet.getDate("addEndDate");
            	// 获取新的endDate
                newEDate = rowSet.getDate("newEDate");
            	// 如果添加单据条目ID为空，则进行更新操作
            	
            	// 获取兼职单据条目信息
            	PluralityAddBizBillEntryInfo addInfo = addEnIns.getPluralityAddBizBillEntryInfo(new ObjectUuidPK(addEnId));
            	if ( null == oldAddEDate) {
            		//原结束日期 = 单据创建时的结束日期
            		addInfo.put("oldEndDate", addEndDate);
            	}
            	// 设置更新前的endDate
            	addInfo.put("endDate", newEDate);
            	addEnCol.add(addInfo);
            }
         // 更新添加单据条目集合
            addEnIns.update(addEnCol);
        } catch (BOSException | SQLException | EASBizException e) {
            e.printStackTrace();
        }
        return newEDate;
        
    	
    }
    
    
    
    
    
    
    
    
    
    /**
     * 反审核后执行
     */
    @Override
    protected void _untiCheckBizBill(Context ctx, String billId) throws BOSException, EASBizException {
    	super._untiCheckBizBill(ctx, billId);
    	
    	IPluralityDelBizBill delIns = PluralityDelBizBillFactory.getLocalInstance(ctx);
    	PluralityDelBizBillInfo delInfo = delIns.getPluralityDelBizBillInfo(new ObjectUuidPK(billId));
    	PluralityDelBizBillEntryCollection entrys = delInfo.getEntrys();
    	for(int i = 0; i < entrys.size(); i++ ) {
    		PluralityDelBizBillEntryInfo entryInfo = entrys.get(i);
            //恢复兼职但上的结束日期
            Date newDate = checkAddBill(ctx, entryInfo.getId().toString(), 0);
            //更新变更记录
            checkRelation(ctx,entryInfo.getId().toString(),newDate,0);
    	}
    }
    
    
    
    
    /**
     * 反审核之后恢复原时间
     * @param ctx
     * @param sqlStr
     */
    private  Date  restoreAddBillEndDate(Context ctx, String sqlStr) {
        Date oldAddEDate = null;
        // 创建添加单据条目集合
        CoreBaseCollection addEnCol = new CoreBaseCollection();
    	try {
            // 获取添加单据条目实例
            IPluralityAddBizBillEntry addEnIns = PluralityAddBizBillEntryFactory.getLocalInstance(ctx);
            // 执行SQL查询
            IRowSet rowSet = DbUtil.executeQuery(ctx, sqlStr);
            // 遍历查询结果
            while (rowSet.next()) {
            	// 获取添加单据条目ID
            	String addEnId = rowSet.getString("addEnId");
            	// 获取 原兼职单上创建时的日期,第一次写兼职结束时是空的;
                oldAddEDate = rowSet.getDate("oldAddEDate");
            	// 获取兼职单据条目信息
            	PluralityAddBizBillEntryInfo addInfo = addEnIns.getPluralityAddBizBillEntryInfo(new ObjectUuidPK(addEnId));
            	if ( null != oldAddEDate) {
            		// 设置更新前的endDate
                	addInfo.put("endDate", oldAddEDate);
            	}
            	addEnCol.add(addInfo);
            }
         // 更新添加单据条目集合
            addEnIns.update(addEnCol);
        } catch (BOSException | SQLException | EASBizException e) {
            e.printStackTrace();
        }
        return oldAddEDate;
    	
    }
    
    
    
}
