package com.engine.kq.bean;

import com.engine.kq.biz.KQLeaveRulesComInfo;
import com.engine.kq.biz.KQLeaveRulesDetailComInfo;
import com.engine.kq.biz.KQUsageHistoryBiz;
import com.engine.kq.entity.KQUsageHistoryEntity;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 假期余额--用于Excel导入
 */
public class KQBalanceOfLeave extends BaseBean {

    /**
     * 人员ID
     */
    private String resourceId;
    /**
     * 编号
     */
    private String workcode ;

    /**
     * 人员姓名
     */
    private String lastName;
    /**
     * 假期类型ID
     */
    private String leaveRulesId;
    /**
     * 所属年份
     */
    private String belongYear;
    /**
     * (混合模式下为法定年假)假期余额基数
     */
    private double baseAmount = 0.00;
    /**
     * (混合模式下为法定年假)已使用的假期余额
     */
    private double usedAmount = 0.00;
    /**
     * (混合模式下为法定年假)额外的假期余额
     */
    private double extraAmount = 0.00;
    /**
     * (仅混合模式下使用，为福利年假)假期余额基数
     */
    private double baseAmount2 = 0.00;
    /**
     * (仅混合模式下使用，为福利年假)已使用的假期余额
     */
    private double usedAmount2 = 0.00;
    /**
     * (仅混合模式下使用，为福利年假)额外的假期余额
     */
    private double extraAmount2 = 0.00;
    /**
     * 用户语言
     */
    private int userlanguage = 7;
    /**
     * 导入Excel的操作者
     */
    private String operator;

    /**
     * 验证模板数据有效性--用于Excel导入
     *
     * @return
     */
    public String valExcelData() {
        String errorInfo = "";
        if (!isExist(resourceId, lastName)) {
            errorInfo = SystemEnv.getHtmlLabelName(389985, userlanguage);//ID和姓名不匹配
            return errorInfo;
        }

        if (this.baseAmount < 0) {
            errorInfo = "基数不能为负数";
            return errorInfo;
        }
        if (this.extraAmount < 0) {
            errorInfo = "额外不能为负数";
            return errorInfo;
        }
        if (this.usedAmount < 0) {
            errorInfo = ""+ SystemEnv.getHtmlLabelName(10005288,weaver.general.ThreadVarLanguage.getLang())+"";
            return errorInfo;
        }
        double _totalAmount = this.baseAmount+this.extraAmount;
        if (_totalAmount < this.usedAmount) {
            errorInfo = ""+ SystemEnv.getHtmlLabelName(508124,weaver.general.ThreadVarLanguage.getLang())+"";
            return errorInfo;
        }

        if (this.baseAmount2 < 0) {
            errorInfo = "福利基数不能为负数";
            return errorInfo;
        }
        if (this.extraAmount2 < 0) {
            errorInfo = "福利额外不能为负数";
            return errorInfo;
        }
        if (this.usedAmount2 < 0) {
            errorInfo = "福利已休不能大于总数";
            return errorInfo;
        }
        double _totalAmount2 = this.baseAmount2+this.extraAmount2;
        if (_totalAmount2 < this.usedAmount2) {
            errorInfo = ""+ SystemEnv.getHtmlLabelName(508124,weaver.general.ThreadVarLanguage.getLang())+"";
            return errorInfo;
        }

        return errorInfo;
    }

    /**
     * 保存数据
     *
     * @return
     */
    public String save() {
        String resultStr = "false";
        try {
            /*获取当前日期，当前时间*/
            Calendar today = Calendar.getInstance();
            String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-" +
                    Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-" +
                    Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
            String currentTime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":" +
                    Util.add0(today.get(Calendar.MINUTE), 2) + ":" +
                    Util.add0(today.get(Calendar.SECOND), 2);

            /********************************************************************************************************/

            /*获取人员的相关信息*/
            ResourceComInfo resourceComInfo = new ResourceComInfo();

            /*分部ID*/
            String subcompanyId = resourceComInfo.getSubCompanyID(this.resourceId);

            /*入职日期*/
            String companyStartDate = resourceComInfo.getCompanyStartDate(this.resourceId);

            /********************************************************************************************************/

            /*获取假期类型的相关设置*/
            KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo();

            /*请假最小单位*/
            String minimumUnit = rulesComInfo.getMinimumUnit(this.leaveRulesId);

            /********************************************************************************************************/

            /*获取假期规则(一个假期类型下可能存在多个假期规则)的相关设置*/
            KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo();

            /*请假时长计算方式：1-按工作日计算请假时长、2-按自然日计算请假时长*/
            int distributionMode = Util.getIntValue(detailComInfo.getDistributionMode(this.leaveRulesId, subcompanyId), 1);

            /*有效期规则：0-永久有效、1-按自然年（1月1日-12月31日）、2-按入职日期起12个月、3-自定义次年失效日期*/
            int validityRule = validityRule = Util.getIntValue(detailComInfo.getValidityRule(this.leaveRulesId, subcompanyId), 0);
            ;

            /*失效日期--月（当有效期规则选择4-自定义次年失效日期时有效）*/
            String expirationMonth = detailComInfo.getExpirationMonth(this.leaveRulesId, subcompanyId);

            /*失效日期--日（当有效期规则选择4-自定义次年失效日期时有效）*/
            String expirationDay = detailComInfo.getExpirationDay(this.leaveRulesId, subcompanyId);

            /*允许延长有效期：0-不允许、1-允许*/
            int extensionEnable = Util.getIntValue(detailComInfo.getExtensionEnable(this.leaveRulesId, subcompanyId), 0);

            /*允许超过有效期天数*/
            int extendedDays = Util.getIntValue(detailComInfo.getExtendedDays(this.leaveRulesId, subcompanyId), 0);

            /********************************************************************************************************/

            /*员工假期余额变更记录*/
            String insertOrUpdate = "";
            KQUsageHistoryEntity usageHistoryEntity = new KQUsageHistoryEntity();//员工假期余额变更记录实体类
            List<KQUsageHistoryEntity> usageHistoryEntityList = new ArrayList<KQUsageHistoryEntity>();//员工假期余额变更记录集合

            /********************************************************************************************************/

            double oldBaseAmount = 0.00;
            double oldUsedAmount = 0.00;
            double oldExtraAmount = 0.00;
            double oldBaseAmount2 = 0.00;
            double oldUsedAmount2 = 0.00;
            double oldExtraAmount2 = 0.00;

            double newBaseAmount = 0.00;
            double newUsedAmount = 0.00;
            double newExtraAmount = 0.00;
            double newBaseAmount2 = 0.00;
            double newUsedAmount2 = 0.00;
            double newExtraAmount2 = 0.00;
            int status = 0;
            String expirationDate = "";

            /*计算有效期 start*/
            if (validityRule == 0) {
                /*不限制有效期，默认永久有效*/
                status = 0;
            } else if (validityRule == 1) {
                /*按自然年（1月1日-12月31日）*/
                if (extensionEnable == 1) {
                    /*允许延长有效期*/
                    expirationDate = DateUtil.addDate(this.belongYear + "-12-31", extendedDays);
                    if (Util.dayDiff(expirationDate, currentDate) > 1) {
                        status = 1;
                    }
                } else {
                    expirationDate = this.belongYear + "-12-31";
                    if (Util.dayDiff(expirationDate, currentDate) > 1) {
                        status = 1;
                    }
                }
            } else if (validityRule == 2) {
                /*按入职日期起12个月*/
                if (companyStartDate.equals("")) {
                    status = 1;
                } else if (extensionEnable == 1) {
                    /*允许延长有效期*/
                    expirationDate = DateUtil.addDate((Util.getIntValue(this.belongYear) + 1) + companyStartDate.substring(4), extendedDays);
                    if (Util.dayDiff(expirationDate, currentDate) > 1) {
                        status = 1;
                    }
                } else {
                    expirationDate = (Util.getIntValue(this.belongYear) + 1) + companyStartDate.substring(4);
                    if (Util.dayDiff(expirationDate, currentDate) > 1) {
                        status = 1;
                    }
                }
            } else if (validityRule == 3) {
                /*自定义次年失效日期*/
                if (extensionEnable == 1) {
                    /*允许延长有效期*/
                    expirationDate = DateUtil.addDate((Util.getIntValue(this.belongYear) + 1) + "-" + expirationMonth + "-" + expirationDay, extendedDays);
                    if (Util.dayDiff(expirationDate, currentDate) > 1) {
                        status = 1;
                    }
                } else {
                    expirationDate = (Util.getIntValue(this.belongYear) + 1) + "-" + expirationMonth + "-" + expirationDay;
                    if (Util.dayDiff(expirationDate, currentDate) > 1) {
                        status = 1;
                    }
                }
            }
            /*计算有效期 end*/

            newBaseAmount = this.baseAmount;
            newExtraAmount = this.extraAmount;
            newUsedAmount = this.usedAmount;
            if (distributionMode == 6) {
                newBaseAmount2 = this.baseAmount2;
                newExtraAmount2 = this.extraAmount2;
                newUsedAmount2 = this.usedAmount2;
            }

            boolean flag = true;//记录SQL操作是否成功
            String searchSql = "select * from kq_BalanceOfLeave where leaveRulesId=? and resourceId=? and belongYear=?";
            String updateSql = "update kq_BalanceOfLeave set baseAmount=?,extraAmount=?,usedAmount=?,baseAmount2=?,extraAmount2=?,usedAmount2=?,status=?,expirationDate=? where leaveRulesId=? and resourceId=? and belongYear=?";
            String insertSql = "insert into kq_BalanceOfLeave(baseAmount,extraAmount,usedAmount,baseAmount2,extraAmount2,usedAmount2,status,expirationDate,leaveRulesId,resourceId,belongYear) values(?,?,?,?,?,?,?,?,?,?,?) ";
            RecordSet recordSet = new RecordSet();
            recordSet.executeQuery(searchSql, this.leaveRulesId, this.resourceId, this.belongYear);
            if (recordSet.next()) {
                oldBaseAmount = Util.getDoubleValue(recordSet.getString("baseAmount"), 0.00);
                oldExtraAmount = Util.getDoubleValue(recordSet.getString("extraAmount"), 0.00);
                oldUsedAmount = Util.getDoubleValue(recordSet.getString("usedAmount"), 0.00);
                if (distributionMode == 6) {
                    oldBaseAmount2 = Util.getDoubleValue(recordSet.getString("baseAmount2"), 0.00);
                    oldExtraAmount2 = Util.getDoubleValue(recordSet.getString("extraAmount2"), 0.00);
                    oldUsedAmount2 = Util.getDoubleValue(recordSet.getString("usedAmount2"), 0.00);
                }

                /*更新员工假期余额 start*/
                flag = recordSet.executeUpdate(updateSql, String.format("%.2f", newBaseAmount), String.format("%.2f", newExtraAmount), String.format("%.2f", newUsedAmount), String.format("%.2f", newBaseAmount2), String.format("%.2f", newExtraAmount2), String.format("%.2f", newUsedAmount2), status, expirationDate, this.leaveRulesId, this.resourceId, this.belongYear);
                resultStr = String.valueOf(flag);
                if (!flag) {
                    resultStr = "false";
                    return resultStr;
                }
                /*更新员工假期余额 end*/

                insertOrUpdate = "update";
            } else {
                /*新增员工假期余额 start*/
                flag = recordSet.executeUpdate(insertSql, String.format("%.2f", newBaseAmount), String.format("%.2f", newExtraAmount), String.format("%.2f", newUsedAmount), String.format("%.2f", newBaseAmount2), String.format("%.2f", newExtraAmount2), String.format("%.2f", newUsedAmount2), status, expirationDate, this.leaveRulesId, this.resourceId, this.belongYear);
                resultStr = String.valueOf(flag);
                if (!flag) {
                    return resultStr;
                }
                /*新增员工假期余额 end*/

                insertOrUpdate = "insert";
            }

            /*员工假期余额变更记录 start*/
            usageHistoryEntity = new KQUsageHistoryEntity();
            usageHistoryEntity.setLeaveRulesId(this.leaveRulesId);
            usageHistoryEntity.setRelatedId(this.resourceId);
            usageHistoryEntity.setWfRequestId("");
            usageHistoryEntity.setOperator(this.operator);
            usageHistoryEntity.setOperateDate(currentDate);
            usageHistoryEntity.setOperateTime(currentTime);
            usageHistoryEntity.setOperateType("7");
            usageHistoryEntity.setBelongYear(this.belongYear);
            usageHistoryEntity.setOldBaseAmount(String.format("%.2f", oldBaseAmount));
            usageHistoryEntity.setNewBaseAmount(String.format("%.2f", newBaseAmount));
            usageHistoryEntity.setOldExtraAmount(String.format("%.2f", oldExtraAmount));
            usageHistoryEntity.setNewExtraAmount(String.format("%.2f", newExtraAmount));
            usageHistoryEntity.setOldUsedAmount(String.format("%.2f", oldUsedAmount));
            usageHistoryEntity.setNewUsedAmount(String.format("%.2f", newUsedAmount));
            usageHistoryEntity.setOldBaseAmount2(String.format("%.2f", oldBaseAmount2));
            usageHistoryEntity.setNewBaseAmount2(String.format("%.2f", newBaseAmount2));
            usageHistoryEntity.setOldExtraAmount2(String.format("%.2f", oldExtraAmount2));
            usageHistoryEntity.setNewExtraAmount2(String.format("%.2f", newExtraAmount2));
            usageHistoryEntity.setOldUsedAmount2(String.format("%.2f", oldUsedAmount2));
            usageHistoryEntity.setNewUsedAmount2(String.format("%.2f", newUsedAmount2));
            usageHistoryEntity.setOldMinimumUnit(minimumUnit);
            usageHistoryEntity.setNewMinimumUnit(minimumUnit);
            usageHistoryEntity.setInsertOrUpdate(insertOrUpdate);

            usageHistoryEntityList.add(usageHistoryEntity);
            KQUsageHistoryBiz usageHistoryBiz = new KQUsageHistoryBiz();
            flag = usageHistoryBiz.save(usageHistoryEntityList);
            resultStr = String.valueOf(flag);
            if (!flag) {
                return resultStr;
            }
            /*员工假期余额变更记录 end*/
        } catch (Exception e) {
            writeLog(e);
        }
        return resultStr;
    }

    /**
     * 判断ID和姓名是否匹配，系统中是否存在此人员
     *
     * @param resourceId
     * @param lastName
     * @return
     */
    private boolean isExist(String resourceId, String lastName) {
        String sql = "select 1 from HrmResource where id=? ";
        RecordSet recordSet = new RecordSet();
        recordSet.executeQuery(sql, resourceId);
        if (recordSet.next()) {
            return true;
        } else {
            return false;
        }
    }

    public String getResourceId() {
        return resourceId;
    }

    public void setResourceId(String resourceId) {
        this.resourceId = resourceId;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getLeaveRulesId() {
        return leaveRulesId;
    }

    public void setLeaveRulesId(String leaveRulesId) {
        this.leaveRulesId = leaveRulesId;
    }

    public String getBelongYear() {
        return belongYear;
    }

    public void setBelongYear(String belongYear) {
        this.belongYear = belongYear;
    }

    public double getBaseAmount() {
        return baseAmount;
    }

    public void setBaseAmount(double baseAmount) {
        this.baseAmount = baseAmount;
    }

    public double getUsedAmount() {
        return usedAmount;
    }

    public void setUsedAmount(double usedAmount) {
        this.usedAmount = usedAmount;
    }

    public double getExtraAmount() {
        return extraAmount;
    }

    public void setExtraAmount(double extraAmount) {
        this.extraAmount = extraAmount;
    }

    public double getBaseAmount2() {
        return baseAmount2;
    }

    public void setBaseAmount2(double baseAmount2) {
        this.baseAmount2 = baseAmount2;
    }

    public double getUsedAmount2() {
        return usedAmount2;
    }

    public void setUsedAmount2(double usedAmount2) {
        this.usedAmount2 = usedAmount2;
    }

    public double getExtraAmount2() {
        return extraAmount2;
    }

    public void setExtraAmount2(double extraAmount2) {
        this.extraAmount2 = extraAmount2;
    }

    public void setUserLanguage(String languageId) {
        this.userlanguage = Util.getIntValue(languageId, 7);
    }

    public String getOperator() {
        return operator;
    }

    public void setOperator(String operator) {
        this.operator = operator;
    }

    public String getWorkcode() {
        return workcode;
    }

    public void setWorkcode(String workcode) {
        this.workcode = workcode;
    }
}
