package com.engine.kq.cmd.holidaySet;

import com.api.browser.bean.SearchConditionOption;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.BizLogSmallType4Hrm;
import com.engine.common.constant.BizLogType;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.*;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 */
public class AddHolidaySetCmd extends AbstractCommonCommand<Map<String, Object>> {

    private SimpleBizLogger logger;

    public AddHolidaySetCmd(Map<String, Object> params, User user) {
        this.user = user;
        this.params = params;
        this.logger = new SimpleBizLogger();

        String groupId = Util.null2String(params.get("groupId"));//考勤组ID
        String syncGroupIds = Util.null2String(params.get("syncGroupIds"));//需要同步的考勤组ID
        String groupIds = groupId + (syncGroupIds.equals("") ? "" : ("," + syncGroupIds));
        BizLogContext bizLogContext = new BizLogContext();
        bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型
        bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_KQ_HOLIDAYSET);//所属大类型
        bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_KQ_HOLIDAYSET);//当前小类型
        bizLogContext.setParams(params);//当前request请求参数
        logger.setUser(user);//当前操作人
        String mainSql = "select * from kq_HolidaySet where groupId in (" + groupIds + ")";
        logger.setMainSql(mainSql, "id");//主表sql
        logger.setMainPrimarykey("id");//主日志表唯一key
        logger.setMainTargetNameMethod("com.engine.kq.util.KQTransMethod.getTargetName4HolidaySet","column:groupId+column:holidayDate+"+user.getLanguage());//当前targetName对应的列（对应日志中的对象名）
        logger.before(bizLogContext);
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public List<BizLogContext> getLogContexts() {
        return logger.getBizLogContexts();
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String groupId = Util.null2String(params.get("groupId"));//考勤组ID
        String startDate = Util.null2String(params.get("startDate"));//开始日期
        String endDate = Util.null2String(params.get("endDate"));//结束日期
        String changeType = Util.null2String(params.get("changeType"));//类型：1-公众假日、2-调配工作日、3-调配休息日
        String holidayDesc = Util.null2String(params.get("holidayDesc"));//说明
        int relatedDay = Util.getIntValue((String) params.get("relatedDay"), -1);//对应工作日：0-星期一、1-星期二、2-星期三、3-星期四、4-星期五、5-星期六、6-星期日
        String isSync = Util.null2String(params.get("isSync"));//是否需要同步到其他考勤组
        String syncGroupIds = Util.null2String(params.get("syncGroupIds"));//需要同步的考勤组ID

        try {
            boolean canAdd = HrmUserVarify.checkUserRight("KQHolidaySetAdd:Add", user);
            if (!canAdd) {
                resultMap.put("status", "-1");
                resultMap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
                return resultMap;
            }

            boolean flag = true;

            String deleteSql = "delete from kq_HolidaySet where groupId=? and holidayDate=?";
            String insertSql = " insert into kq_HolidaySet(groupId,holidayDate,changeType,holidayDesc,relatedDay) values(?,?,?,?,?)";
            RecordSet recordSet = new RecordSet();
            int days = Util.dayDiff(startDate, endDate);
            for (int i = 0; i < days; i++) {
                String holidayDate = getDateDel(startDate, i);
                /**
                 * 如果这一天已经设置过数据，删除掉后再重新插入
                 */
                recordSet.executeUpdate(deleteSql, groupId, holidayDate);

                flag = recordSet.executeUpdate(insertSql, groupId, holidayDate, changeType, holidayDesc, relatedDay);
                if (flag) {
                    resultMap.put("sign", "1");
                    resultMap.put("message", SystemEnv.getHtmlLabelName(83551, user.getLanguage()));//保存成功
                } else {
                    resultMap.put("sign", "-1");
                    resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败
                    return resultMap;
                }


                /**
                 * 同步到其他考勤组
                 * 如果这一天已经设置过数据，删除掉后再重新插入
                 */
                KQGroupComInfo kqGroupComInfo = new KQGroupComInfo();
                if (isSync.equals("1") || isSync.equals("true")) {
                    List<String> syncGroupIdList = Util.TokenizerString(syncGroupIds, ",");
                    for (int j = 0; j < syncGroupIdList.size(); j++) {
                        String tempGroupId = syncGroupIdList.get(j);

                        if (Util.null2String(kqGroupComInfo.getKqtype(tempGroupId)).equals("2") && changeType.equals("2")) {
                            continue;
                        }
                        recordSet.executeUpdate(deleteSql, tempGroupId, holidayDate);
                        flag = recordSet.executeUpdate(insertSql, tempGroupId, holidayDate, changeType, holidayDesc, relatedDay);
                        if (!flag) {
                            resultMap.put("sign", "-1");
                            resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败
                            return resultMap;
                        }
                    }
                }
            }

            if (flag) {
                resultMap.put("sign", "1");
                resultMap.put("message", SystemEnv.getHtmlLabelName(83551, user.getLanguage()));//保存成功
            } else {
                resultMap.put("sign", "-1");
                resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败
            }
        } catch (Exception e) {
            resultMap.put("sign", "-1");
            resultMap.put("message", SystemEnv.getHtmlLabelName(382661, user.getLanguage()));
            writeLog(e);
        } finally {
            /*刷新缓存*/
            KQHolidaySetComInfo holidaySetComInfo = new KQHolidaySetComInfo();
            holidaySetComInfo.removeCache();

            /*刷新报表*/
            List<String> groupIdList = new ArrayList<String>();
            if (isSync.equals("1") || isSync.equals("true")) {
                groupIdList = Util.TokenizerString(syncGroupIds, ",");
                if (groupIdList == null) {
                    groupIdList = new ArrayList<String>();
                }
            }
            groupIdList.add(groupId);
            List<String> holidayDateList = new ArrayList<String>();
            boolean isEnd = false;
            for (String holidayDate = startDate; !isEnd; holidayDate = DateUtil.getDate(holidayDate, 1)) {
                if (holidayDate.equals(endDate)) {
                    isEnd = true;
                }
                if (!holidayDateList.contains(holidayDate)) {
                    holidayDateList.add(holidayDate);
                }
            }
            new KQHolidaySetThread(groupIdList,holidayDateList).start();
        }
        return resultMap;
    }

    /**
     * 获取与data相隔num天的日期
     *
     * @param date
     * @param num
     * @return
     */
    private static String getDateDel(String date, int num) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        Date tempDate = null;
        try {
            tempDate = simpleDateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        calendar.setTime(tempDate);
        calendar.add(Calendar.DATE, num);
        tempDate = calendar.getTime();
        date = simpleDateFormat.format(tempDate);
        return date;
    }
}
