package com.engine.kq.cmd.holidaySet;

import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
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.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 节假日设置--新建时选择的日期范围内是否已经存在设置过的数据
 */
public class HasRepeatDataCmd extends AbstractCommonCommand<Map<String, Object>> {

    public HasRepeatDataCmd(Map<String, Object> params, User user) {
        this.user = user;
        this.params = params;
    }

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

    @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"));//结束日期
        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 hasRepeatData = false;
            RecordSet recordSet = new RecordSet();
            int days = Util.dayDiff(startDate, endDate);
            for (int i = 0; i < days; i++) {
                String holidayDate = getDateDel(startDate, i);
                String sql = "select * from kq_HolidaySet where groupId="+groupId+" and holidayDate='"+holidayDate+"'";
                recordSet.executeQuery(sql);
                if(recordSet.next()){
                    hasRepeatData = true;
                    break;
                }
            }
            resultMap.put("hasRepeatData",hasRepeatData);//为true表示所选的时间范围内有设置过数据，请确认是否覆盖
        }catch (Exception e){
            e.printStackTrace();
        }
        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;
    }
}
