package com.ho.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.ho.business.entity.*;
import com.ho.business.feignclient.FileCenterFeignClient;
import com.ho.business.mapper.PeakShavingMapper;
import com.ho.business.mapper.PlanningCurveMapper;
import com.ho.business.service.PeakShavingService;
import com.ho.business.service.PlanningCurveIssueService;
import com.ho.business.service.StationService;
import com.ho.business.vo.Holiday;
import com.ho.business.vo.PolicyConfigPlanVo;
import com.ho.business.vo.req.PolicyConfigData;
import com.ho.common.tools.constant.DefineConstant;
import com.ho.common.tools.entity.UserDetailRespVO;
import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.zip.CRC32;

@Service
public class PeakShavingServiceImpl implements PeakShavingService {
    @Autowired
    private PeakShavingMapper peakShavingMapper;

    @Autowired
    private StationService stationService;

    @Autowired
    private PlanningCurveIssueService issueService;

    @Autowired
    FileCenterFeignClient fileCenterFeignClient;

    @Autowired
    private PlanningCurveMapper planningMapper;

    public static final String DEVICE_TYPE = "plan";

    public static final Integer INTERVAL = 1;


    public static final String HOLIDAY_TYPE = "holiday";
    public static final String WEEKDAY_TYPE = "weekDay";

    @Override
    public Map<String, Object> addPlanningCurveTemplate(PlanningCurveTemplate template) {
        Map<String, Object> result = new HashMap<String, Object>(0);
        result.put("code", 200);
        result.put("msg", DefineConstant.PeakShaving.ADD_TEMPLATE_SUCCESS);
        try {
            if (null != template) {

                if (template.getPlanningCurves().size() <= 0) {
                    result.put("code", 500);
                    result.put("msg", DefineConstant.PeakShaving.TEMPLATE_CHECK_SIZE);
                    return result;
                }

                int id = peakShavingMapper.getSeq();
                template.setTemId(id);
                Map<String, Object> check = this.checkData(template, id);
                if (null != check) {
                    return check;
                }
                //在入库前查询配了几段，将模板之外的剩余的值改为0
                int line = 0;
                List<PlanningCurve> curves = template.getPlanningCurves();
                if (curves.size() > 0) {
                    peakShavingMapper.addPlanningCurveTemplate(template);
                    line = peakShavingMapper.addPlanningCurve(curves, id);
                }
            } else {
                result.put("code", 500);
                result.put("msg", DefineConstant.PeakShaving.TEMPLATE_DATA_NOT_EXIST);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", DefineConstant.PeakShaving.ADD_TEMPLATE_FAIL);
        }
        return result;
    }

    private Map<String, Object> checkData(PlanningCurveTemplate template, Integer temId) {
        Map<String, Object> result = new HashMap<String, Object>(0);

        // 对模板编号和名称进行校验
        int i = 0;
        if (null != template.getTemplateNo() && !template.getTemplateNo().equals("")) {
            i = peakShavingMapper.checkNo(template.getTemplateNo(), template.getStationId(), temId);
        } else {
            result.put("code", 400);
            result.put("msg", DefineConstant.PeakShaving.TEMPLATE_NO_NOT_NULL);
            return result;
        }

        if (i > 0) {
            result.put("code", 400);
            result.put("msg", DefineConstant.PeakShaving.TEMPLATE_NO_NOT_REPEAT);
            return result;
        }

        if (null != template.getTemplateNo() && !template.getTemplateNo().equals("")) {
            i = peakShavingMapper.checkName(template.getTemplateName(), template.getStationId(), temId);
        } else {
            result.put("code", 400);
            result.put("msg", DefineConstant.PeakShaving.TEMPLATE_NAME_NOT_NULL);
            return result;
        }

        if (i > 0) {
            result.put("code", 400);
            result.put("msg", DefineConstant.PeakShaving.TEMPLATE_NAME_NOT_REPEAT);
            return result;
        }

        if (null != template.getTemplateNo() && template.getTemplateNo().length() > 10) {
            result.put("code", 400);
            result.put("msg", DefineConstant.PeakShaving.TEMPLATE_NO_TOO_LONG);
            return result;
        }

        if (null != template.getTemplateName() && template.getTemplateName().length() > 10) {
            result.put("code", 400);
            result.put("msg", DefineConstant.PeakShaving.TEMPLATE_NAME_TOO_LONG);
            return result;
        }

        if (null != template.getTemP() && template.getTemP() > 99999999) {
            result.put("code", 400);
            result.put("msg", DefineConstant.PeakShaving.TEMPLATE_P_ERROR);
            return result;
        }

        if (null != template.getSocUpper() && template.getSocUpper() > 99999999) {
            result.put("code", 400);
            result.put("msg", DefineConstant.PeakShaving.TEMPLATE_SOC_UPPER_ERROR);
            return result;
        }

        if (null != template.getSocLower() && template.getSocLower() > 99999999) {
            result.put("code", 400);
            result.put("msg", DefineConstant.PeakShaving.TEMPLATE_SOC_LOWER_ERROR);
            return result;
        }

        if (null != template.getCapacity() && template.getCapacity() > 99999999) {
            result.put("code", 400);
            result.put("msg", DefineConstant.PeakShaving.TEMPLATE_CAPACITY_ERROR);
            return result;
        }
        return null;
    }

    @Override
    public Map<String, Object> modifyPlanningCurveTemplate(PlanningCurveTemplate template) {
        String msg = DefineConstant.PeakShaving.EDIT_TEMPLATE_FAIL;
        Map<String, Object> result = new HashMap<String, Object>(0);
        result.put("code", 200);
        result.put("msg", DefineConstant.PeakShaving.EDIT_TEMPLATE_SUCCESS);
        try {
            if (null != template && null != template.getTemId()) {
                Integer templateId = template.getTemId();
                Map<String, Object> check = this.checkData(template, templateId);
                if (null != check) {
                    return check;
                }

                if (template.getPlanningCurves().size() <= 0) {
                    result.put("code", 500);
                    result.put("msg", DefineConstant.PeakShaving.TEMPLATE_CHECK_SIZE);
                    return result;
                }
                if( template.getStatus() == 0){
                    int count = checkUse(template);
                    if( count > 0 ){
                        msg = BaseResponseCode.CANNOT_BE_DISPLAY.getMsg();
                        throw new BusinessException(BaseResponseCode.CANNOT_BE_DISPLAY);
                    }
                }
                int modifyLine = peakShavingMapper.modifyPlanningCurveTemplate(template);
                if (modifyLine > 0) {
                    int deleteLine = peakShavingMapper.deleteCurves(templateId);
                }
                int addLine = 0;
                List<PlanningCurve> curves = template.getPlanningCurves();
                if (curves.size() > 0) {
                    addLine = peakShavingMapper.addPlanningCurve(curves, templateId);
                }
            } else {
                result.put("code", 500);
                result.put("msg", DefineConstant.PeakShaving.TEMPLATE_DATA_NOT_EXIST);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", msg);
        }
        return result;
    }

    @Override
    public Map<String, Object> deletePlanningCurveTemplates(PlanningCurveTemplate template) {
        Map<String, Object> result = new HashMap<String, Object>(0);
        result.put("code", "200");
        result.put("msg", DefineConstant.PeakShaving.DELETE_SUCCESS);
        // 判断计划曲线模板是否是禁用状态,如果不是则不让删除
        // 启用状态 0：不启用 1：启用
        int status = peakShavingMapper.queryTemplateStatus(template);
        if( status == 1 ){
            result.put("code", BaseResponseCode.CANNOT_BE_DELETED.getCode());
            result.put("msg", BaseResponseCode.CANNOT_BE_DELETED.getMsg());
            throw new BusinessException(BaseResponseCode.CANNOT_BE_DELETED);
        }
        int i = peakShavingMapper.deleteTemplateById(template.getTemId());
        if (i > 0) {
            i = peakShavingMapper.deleteCurves(template.getTemId());
        } else {
            throw new BusinessException(BaseResponseCode.DELETE_ERROR);
        }
        return result;
    }

    /**
     * 判断是否使用
     * @param template
     * @return
     */
    @Override
    public int checkUse(PlanningCurveTemplate template) {
        int i = peakShavingMapper.checkUse(template);
        int i2 = peakShavingMapper.checkUse2(template);
        return i+i2;
    }

    @Override
    public List<PolicyConfigData> queryPolicyConifg(PolicyConfig policyConfig) {
        return peakShavingMapper.queryPolicyConifg(policyConfig);
    }

    @Override
    public List<PolicyConfig> queryPolicyConifgMonth(PolicyConfig policyConfig) {
        return peakShavingMapper.queryPolicyConifgMonth(policyConfig);
    }

    @Override
    public List<PlanningCurveTemplate> getPlanningCurveTemplates(PlanningCurveTemplate template) {
        return peakShavingMapper.getPlanningCurveTemplates(template);
    }

    @Override
    public List<PlanningCurveTableTemplate> getTableTemplates(PlanningCurveTemplate template) {
        return peakShavingMapper.getPlanningCurveTableTemplates(template);
    }

    @Override
    public PlanningCurveTemplate getPlanningCurveTemplate(PlanningCurveTemplate template) {
        PlanningCurveTemplate planningCurveTemplate = peakShavingMapper.getPlanningCurveTemplate(template);
        if (null != planningCurveTemplate && null != planningCurveTemplate.getStationId() ) {
            Station station = stationService.selectById(planningCurveTemplate.getStationId());
            planningCurveTemplate.setRatePower(station.getRatePower());
        }
        return planningCurveTemplate;
    }

    @Override
    public List<List<PlanningCurve>> queryTemplateCurves(PlanningCurveTemplate template) {
        List<List<PlanningCurve>> result = new ArrayList<>(0);
        // 先查询电站能看到哪些计划曲线,根据能看到的计划曲线模板查询计划曲线数据
        List<Integer> templateIds = peakShavingMapper.getTemplateIds(template.getStationId());
        if( templateIds != null && templateIds.size() > 0 ){
            for (Integer templateId : templateIds) {
                List<PlanningCurve> planningCurves = peakShavingMapper.queryTemplateCurves(templateId);
                List<PlanningCurve> processData = processData(planningCurves);
                result.add(processData);
            }
        }
        return result;
    }

    /**
     * 处理查询到的数据,改成1分钟一个点
     * @param planningCurves
     * @return
     */
    private List<PlanningCurve> processData(List<PlanningCurve> planningCurves){
        List<PlanningCurve> result = new ArrayList<>(0);
        List<String> min = this.getMin(INTERVAL);
        int index = 0;
        for (int i = 0; i < planningCurves.size(); i++) {
            PlanningCurve next = null;
            if( i+1 < planningCurves.size() ){
                next = planningCurves.get(i+1);
            }
            PlanningCurve planningCurve = planningCurves.get(i);
            for (int j = index; j < min.size(); j++) {
                String m = min.get(j);
                // 如果不存在则插入值,但是需要判断是否满足下一次的条件了
                if( next != null && next.getStartTime().equals(m) ){
                    index = j;
                    break;
                }
                PlanningCurve newCurveBean = new PlanningCurve();
                BeanUtil.copyProperties(planningCurve, newCurveBean);
                newCurveBean.setStartTime(m);
                result.add(newCurveBean);
            }
        }
        return result;
    }

    /**
     * 根据输入的间隔时间,生成一天所有的时间点集合
     * @param interval 一个整数
     * @return  返回值格式HH:mm:ss
     */
    private List<String> getMin(int interval) {
        Date startDate = DateUtil.beginOfDay(DateUtil.yesterday());
        Date endDate = DateUtil.endOfDay(DateUtil.yesterday());
        List<String> allMin = new ArrayList<>();
        Calendar t1 = Calendar.getInstance();
        t1.setTime(startDate);//开始时间
        Calendar t2 = Calendar.getInstance();
        t2.setTime(endDate);//结束时间
        for (; t1.compareTo(t2) < 0; t1.add(Calendar.MINUTE, interval)) {
            allMin.add(DateUtil.format(t1.getTime(),"HH:mm:ss"));
        }
        return allMin;
    }

    /**
     *
     * @param type 数据类型1:日 2:月
     */
//    @Override
//    public void sendData(Integer type) {
//        // 获取明天的日期做为查询条件
//        DateTime tomorrow = DateUtil.tomorrow();
//        int month = DateUtil.month(tomorrow)+1;
//        int day = DateUtil.dayOfMonth(tomorrow);
//        List<PlanningIssueVo> issueDevice = peakShavingMapper.getIssueDevice(DEVICE_TYPE);
//        if( issueDevice != null && issueDevice.size() > 0 ){
//            for (PlanningIssueVo planningIssueVo : issueDevice) {
//                if( planningIssueVo.getStationId() == null ){
//                    continue;
//                }
////                if( !planningIssueVo.getStationId().equals(482)  ){
////                    continue;
////                }
//                PolicyConfigVo vo = new PolicyConfigVo();
//                if ( type == 1 ) {
//                    vo.setDay(day);
//                }
//                vo.setMonth(month);
//
//                vo.setStationId(planningIssueVo.getStationId());
//                vo.setType(type);
//                PolicyConfigVo policyConfigVo = peakShavingMapper.queryPolicyConfigByParam(vo);
//                if( policyConfigVo == null ){
//                    continue;
//                }
//                planningIssueVo.setTemId(policyConfigVo.getTemId());
//                // 根据查询到的设备以及电站id查询需要用到的策略配置信息,然后根据策略配置信息查询需要用到的模型数据
//                List<Map<String, Object>> issueDatas = issueService.getIssueDatas(planningIssueVo);
//                if( issueDatas!= null && issueDatas.size() > 0 ){
//                    PlanningIssueQueryVo issueQueryVo = new PlanningIssueQueryVo();
//                    issueQueryVo.setSrcId(planningIssueVo.getSrcId());
//                    issueQueryVo.setStationId(planningIssueVo.getStationId());
//                    issueQueryVo.setDeviceType(planningIssueVo.getDeviceType());
//                    /** start */
//                    /** todo: 生效时间设置,0为线上要使用,测试修改成当前时间10分钟之后 */
//                    issueQueryVo.setPlanRefreshH(0);
//                    issueQueryVo.setPlanRefreshM(0);
//                    issueQueryVo.setPlanControlModel(0);
//
////                    LocalDateTime now = LocalDateTime.now();
////                    issueQueryVo.setPlanRefreshH(now.getHour());
////                    issueQueryVo.setPlanRefreshM(now.getMinute()+10);
////                    issueQueryVo.setPlanControlModel(0);
//                    /** end */
//                    List<Map<String, Object>> planCurveIssueData = issueService.getPlanCurveIssueData(issueQueryVo);
//                    if ( planCurveIssueData != null && planCurveIssueData.size() > 0 ) {
//                        issueDatas.addAll(planCurveIssueData);
//                    }
//                    OrderIssuedReqVO orderIssuedReqVO = processParam(issueDatas,planningIssueVo.getSn());
//                    System.out.println(orderIssuedReqVO);
//                    DataResult<HeartbeatResp> heartbeatRespDataResult = fileCenterFeignClient.orderIssued(orderIssuedReqVO);
//                }
//            }
//        }
//    }

    /**
     * 查询出来的结果组装成下发需要的对象
     * @param issueDatas
     * @return
     */
    public OrderIssuedReqVO processParam(List<Map<String, Object>> issueDatas,String sn){
        OrderIssuedReqVO vo = new OrderIssuedReqVO();
        List<OrderIssuedVO> list = new ArrayList<>(0);
        OrderIssuedVO orderIssued =null;
        for (Map<String, Object> issueData : issueDatas) {
            orderIssued = new OrderIssuedVO();
            orderIssued.setCol(issueData.get("col").toString());
            orderIssued.setMaxValue(new BigDecimal(issueData.get("maxValue").toString()));
            orderIssued.setMinValue(new BigDecimal(issueData.get("minValue").toString()));
            orderIssued.setSrcId(Integer.valueOf(issueData.get("srcId").toString()));
            orderIssued.setModifyValue(new BigDecimal(issueData.get("modifyValue").toString()));
            orderIssued.setSn(issueData.get("sn").toString());
            orderIssued.setStationId(Integer.valueOf(issueData.get("stationId").toString()));
            list.add(orderIssued);
        }
        vo.setSn(sn);
        vo.setList(list);
        return vo;
    }

    @Override
    public Integer queryIssueDevice(Integer stationId) {
        return peakShavingMapper.queryIssueDevice(stationId);
    }

    @Override
    public String getSnByStationId(Integer stationId) {
        return peakShavingMapper.getSnByStationId(stationId);
    }

    @Override
    public String getJson(PlanningCurveTemplate template, UserDetailRespVO userDetail) {
        List<PlanningCurveTemplate> planningCurveTemplates = planningMapper.getPlanningCurveTemplate(template);
        StringBuilder sb = new StringBuilder();
        String version = "V1";
        sb.append("{");
        List<Map<String,Object>> data = new ArrayList<Map<String,Object>>(0);
        Map<String,Object> dataMap = null;
        LinkedList<LinkedHashMap<String,String>> curve = null;
        for (PlanningCurveTemplate planningCurveTemplate : planningCurveTemplates) {
            curve = new LinkedList<>();
            dataMap = new HashMap<>(0);
            List<PlanningCurve> planningCurves = planningCurveTemplate.getPlanningCurves();
            LinkedHashMap<String,String> map = null;
            for (int i = 0; i < planningCurves.size(); i++) {
                dataMap.put("temNo",planningCurves.get(i).getPlanningTemplateId());
                map = new LinkedHashMap<>(0);
                map.put("s",""+(i+1));
                String startTime = planningCurves.get(i).getStartTime();
                map.put("startHid",startTime.substring(0,2));
                map.put("startMid",startTime.substring(3,5));
                map.put("actvalueid",planningCurves.get(i).getP().toString());
                map.put("reavalueid",planningCurves.get(i).getQ().toString());
                curve.add(map);
            }
            if( curve.size() < 16 ){
                for (int i = curve.size()+1; i <= 16; i++) {
                    map = new LinkedHashMap<String,String>(0);
                    map.put("s",""+i);
                    map.put("startHid","0");
                    map.put("startMid","0");
                    map.put("actvalueid","0");
                    map.put("reavalueid","0");
                    curve.add(map);
                }
            }
            dataMap.put("curve",curve);
            data.add(dataMap);
        }
        String dataStr = JSON.toJSONString(data);
        // 文件版本号
        sb.append("\"version\":\""+version+"\",");
        // 当前时间(生成文件时间)
        sb.append("\"date\":\""+ DateUtil.now() +"\",");
        // 操作人(当前登陆人)
        if ( userDetail != null ) {
            sb.append("\"operator\":\""+userDetail.getUsername()+"\",");
        } else {
            sb.append("\"operator\":\"0\",");
        }
        // data数据长度
        sb.append("\"length\":\""+dataStr.length()+"\",");
        // 类型 0:使用文件  1:使用点号
        sb.append("\"planType\":\"0\",");
        sb.append("\"data\":"+dataStr+",");
        // 模板使用说明
        List<String> dateList = getDateList();
        List<Map<String,String>> dateMapping = new ArrayList<Map<String,String>>(0);

        List<PolicyConfigData> policyConfigDayData = peakShavingMapper.queryPeakPolicyConfigData(template.getStationId(), 1);

        if( policyConfigDayData == null || policyConfigDayData.size() == 0 ){
            throw new BusinessException(BaseResponseCode.SEND_DATA_IS_EXISTS);
        }

        Map<String,String> mapping = null;
        Integer temId = 0;
        for (String date : dateList) {
            mapping = new HashMap<>(0);
            mapping.put("date",date);
            DateTime parse = DateUtil.parse(date);
            int month = parse.month()+1;
            int day = parse.dayOfMonth();
            for (PolicyConfigData policyConfigData : policyConfigDayData) {
                if( policyConfigData.getMonth() == month && policyConfigData.getDay() == day ){
                    if( policyConfigData.getTemId() != null ) {
                        temId = policyConfigData.getTemId();
                        break;
                    }
                }
            }
            mapping.put("temNo",temId.toString());
            dateMapping.add(mapping);
        }
        String mappingStr = JSONUtil.toJsonStr(dateMapping);
        // crc32校验
        sb.append("\"crc32\":\""+crc32(dataStr)+"\",");
        sb.append("\"dateMapping\":"+mappingStr+"");
        sb.append("}");
        System.err.println(sb.toString());
        //log.info("PlanningCurveService getJson:{}",sb.toString());
        return sb.toString();
    }

    private Long crc32(String data){
        // 创建CRC32对象
        CRC32 crc32 = new CRC32();
        // 提供要计算的数据
        byte[] bytes = data.getBytes();
        // 更新CRC32值
        crc32.update(bytes);
        // 获取最终CRC32值
        long crcValue = crc32.getValue();
        return crcValue;
    }

    private List<String> getDateList(){
        List<String> dateList = new ArrayList<String>(0);
        int year = DateUtil.year(new Date());
        for (int month = 1; month <= 12; month++) {
            YearMonth yearMonth = YearMonth.of(year, month);
            int daysInMonth = yearMonth.lengthOfMonth();
            List<LocalDate> dates = new ArrayList<>();
            for (int i = 1; i <= daysInMonth; i++) {
                LocalDate date = LocalDate.of(year, month, i);
                dates.add(date);
            }
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            for (LocalDate date : dates) {
                String formattedDate = date.format(formatter);
                dateList.add(formattedDate);
            }
        }
        return dateList;
    }

    @Transactional
    @Override
    public Map<String, Object> policyConfig(List<PolicyConfig> policyConfigs) {
//         新增policyConfig表数据
        try {
            for (PolicyConfig policyConfig : policyConfigs) {
                Integer month = policyConfig.getMonth();
                LocalDate date = LocalDate.now();
                int year = date.getYear();
                List<Integer> days = getDays(year, month);
                // planId
                int planSeq = peakShavingMapper.getPlanSeq();
                // 计划曲线为空的情况
                if ( policyConfig.getTemId() != null ) {
                    List<PolicyConfigData> data = new ArrayList<>(0);
                    PolicyConfigData policyConfigData = null;
                    for (Integer day : days) {
                        policyConfigData = new PolicyConfigData();
                        policyConfigData.setDay(day);
                        policyConfigData.setPlanId(planSeq);
                        policyConfigData.setTemId(policyConfig.getTemId());
                        data.add(policyConfigData);
                    }
                    policyConfig.setData(data);
                }
                PolicyConfigPlanVo vo = new PolicyConfigPlanVo();
                if ( policyConfig.getPlanId() == null ) {
                    PolicyConfigPlan plan = new PolicyConfigPlan();
                    plan.setId( planSeq );
                    plan.setPlanName(policyConfig.getMonth() + "月方案_"+planSeq);
                    plan.setStationId(policyConfig.getStationId());
                    plan.setMonth(policyConfig.getMonth());
                    plan.setType(1);
                    vo.setPolicyConfigPlan(plan);
                }
                vo.setPolicyConfig(policyConfig);

                generateNewPlan(vo,0);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    private List<Integer> getDays(int year, int month){
        List<Integer> list = new ArrayList<>(0);
        List<Date> datesInMarch = getDatesInMonth(year, month);
        Date now = new Date();
        int nowMonth = now.getMonth();
        for (Date date : datesInMarch) {
            int dateMonth = date.getMonth();
            if( dateMonth == nowMonth ){
                if( date.after(now)||date.equals(now) ){
                    list.add(date.getDate());
                }
            } else {
                list.add(date.getDate());
            }
        }
        return list;
    }

    // 获取两个日期之间所有日
    private static List<Date> getDatesInMonth(int year, int month) {
        ArrayList<Date> dates = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1); // 注意月份是从0开始的

        int lastDayOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

        for (int day = 1; day <= lastDayOfMonth; day++) {
            calendar.set(Calendar.DAY_OF_MONTH, day);
            Date date = calendar.getTime();
            dates.add(date);
        }

        return dates;
    }


    @Override
    public List<PolicyConfigPlan> queryPlanList(PolicyConfigPlan policyConfigPlan) {
        List<PolicyConfigPlan> policyConfigPlans = peakShavingMapper.queryPlanList(policyConfigPlan);
        return policyConfigPlans;
    }

    @Override
    public List<PeakShavingBean> queryPeakPolicyList(PolicyConfigPlan policyConfigPlan) {
        List<PeakShavingBean> list = new ArrayList<>(0);
        PeakShavingBean bean = null;
        // 查询方案模板,组装成对象
        List<PolicyConfigPlan> policyConfigPlans = peakShavingMapper.queryPlanList(policyConfigPlan);
        for (PolicyConfigPlan configPlan : policyConfigPlans) {
            bean = new PeakShavingBean();
            bean.setId( configPlan.getId() );
            bean.setName( configPlan.getPlanName() );
            bean.setType(1);
            bean.setMonth( configPlan.getMonth() );
            bean.setKey( configPlan.getId() +"_"+1  );
            list.add(bean);
        }
        List<PeakShavingBean> peakShavingBeans = peakShavingMapper.queryPeakPolicyList(policyConfigPlan);
        if( peakShavingBeans != null && peakShavingBeans.size() > 0 ){
            list.addAll(peakShavingBeans);
        }
        return list;
    }

    @Override
    public void deletePlan(PolicyConfigPlan policyConfigPlan) {
        if( checkPlanUse(policyConfigPlan) ){
            throw new BusinessException(BaseResponseCode.PLAN_IS_USE);
        } else {
            peakShavingMapper.deletePlan(policyConfigPlan);
        }
    }

    /**
     * 判断方案是否正在使用
     * 正在使用则返回true 否则返回false
     * @return
     */
    private boolean checkPlanUse(PolicyConfigPlan policyConfigPlan){
        int i = peakShavingMapper.checkPlanUse(policyConfigPlan);
        if ( i > 0 ){
            return true;
        }
        return false;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void generateNewPlan(PolicyConfigPlanVo vo,Integer type) {
        boolean flag = false;
        PolicyConfig policyConfig = vo.getPolicyConfig();
        PolicyConfigPlan policyConfigPlan = vo.getPolicyConfigPlan();
        // 根据电站id和月删除对应月的peak_policy_config表数据
        if ( type == 0 ) {
            peakShavingMapper.deletePolicyConfigByMonth(policyConfig.getStationId(),policyConfig.getMonth());
        } else {
            peakShavingMapper.deletePolicyConfigByMonth(policyConfigPlan.getStationId(),policyConfigPlan.getMonth());
        }
        if ( policyConfig.getPlanId() == null ) {
            flag = true;
            if(  policyConfig.getData() == null || policyConfig.getData().size() == 0 ){
               return;
            }
        }
        try {
            List<PolicyConfigData> data = policyConfig.getData();
            // planId
            int planSeq = peakShavingMapper.getPlanSeq();
            //         policyConfig 表id
            int peakSeq = peakShavingMapper.getPeakSeq();
            policyConfig.setId(peakSeq);
            if ( policyConfig.getStationId() == null ) {
                policyConfig.setStationId(policyConfigPlan.getStationId());
                policyConfig.setPlanId(planSeq);
//                if ( flag ) {
//                    policyConfig.setTemId(data.get(0).getTemId() != null ? data.get(0).getTemId() : null);
//                }
                policyConfig.setMonth(policyConfigPlan.getMonth());
            }
            if( flag && (policyConfigPlan != null && policyConfigPlan.getId() != null) ){
                policyConfig.setPlanId(policyConfigPlan.getId());
            } else if( policyConfig.getPlanId() == null || type == 1){
                policyConfig.setPlanId(planSeq);
            }
            peakShavingMapper.addPolicyConfig(policyConfig);
            // 如果方案id不是空,表示调用了原来有的方案,那就不需要创建方案和日数据了
            if ( flag && policyConfigPlan != null) {
                data.stream().forEach( d ->{ d.setPlanId(planSeq); });
                policyConfigPlan.setId(planSeq);
                peakShavingMapper.addPlan(policyConfigPlan);
                peakShavingMapper.addPolicyConfigData(data);
            }
        } catch (Exception e) {
            throw new BusinessException(BaseResponseCode.ADD_FAIL);
        }
    }

    @Override
    public List<PolicyConfigData> queryPolicyConifgDetail(PolicyConfig policyConfig) {
        return peakShavingMapper.queryPolicyConifgDetail(policyConfig);
    }

    @Override
    public Map<String, Object> queryHolidayList(Holiday vo) {
        Map<String, Object> map = new HashMap<>(0);
        map.put(HOLIDAY_TYPE,new HashSet<>());
        map.put(WEEKDAY_TYPE,new HashSet<>());
        LinkedHashSet<Integer> holidayList = new LinkedHashSet<>(0);
        List<Holiday> holidays = peakShavingMapper.queryHolidayList(vo);
        if( !holidays.isEmpty() ){
            List<Integer> days = getDays(holidays.get(0).getYear(), vo.getMonth());
            for (Holiday holiday : holidays) {
                holidayList.add(holiday.getDay());
            }
            Set<Integer> intersection = new HashSet<>(days);
            intersection.retainAll(holidayList);
            // 从原始列表中删除交集部分
            for (int num : intersection) {
                days.remove((Object)num);
            }
            map.put(HOLIDAY_TYPE,holidayList);
            map.put(WEEKDAY_TYPE,days);
        }
        return map;
    }

    @Override
    public int checkPlanName(PolicyConfigPlan policyConfigPlan) {
        return peakShavingMapper.checkPlanName(policyConfigPlan);
    }
}
