package cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.base;

import cn.estsh.i3plus.ext.mes.api.base.IMesNumberOfSafeOperationDaysService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesAccidentDate;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesNumberOfSafeOperationDays;
import cn.estsh.i3plus.ext.mes.pojo.model.bu.MesNumberOfSafeOperationDaysModel;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesAccidentDateRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesNumberOfSafeOperationDaysRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.mes.apiservice.util.DateUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 文件描述
 *
 * @author xiangming.liao
 * @date 2021年06月30日 14:45
 */
@Slf4j
@Service
public class MesNumberOfSafeOperationDaysService implements IMesNumberOfSafeOperationDaysService {
    @Autowired
    private MesNumberOfSafeOperationDaysRepository numberOfSafeOperationDaysRepository;
    @Autowired
    private MesAccidentDateRepository accidentDateRepository;

    @Override
    public MesNumberOfSafeOperationDays updateNumberOfSafeOperationDays(MesNumberOfSafeOperationDays numberOfSafeOperationDays) throws ParseException {
        //Date startDate = TimeTool.parseDate(numberOfSafeOperationDays.getInitStartDate());
        Date startDate = DateUtil.parse(numberOfSafeOperationDays.getInitStartDate(), DateUtil.SHORT_FORMAT);
        //Date endDate = TimeTool.parseDate(numberOfSafeOperationDays.getInitEndDate());
        Date endDate = DateUtil.parse(numberOfSafeOperationDays.getInitEndDate(), DateUtil.SHORT_FORMAT);

        Date today = DateUtil.parse(TimeTool.getToday(), DateUtil.SHORT_FORMAT);
        log.info("today:{}", today);

        log.info("startDate.after(today):{}", startDate.after(today));
        //1.选中的初始开始日期 不能大于当前日期
        if (startDate.after(today)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("初始开始日期不能大于当前日期!")
                    .build();
        }
        //选中的初始开始日期 不能等于当前日期
        /*if (startDate.equals(today)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("初始开始日期不能为当前日期!")
                    .build();
        }*/
        //2.选中的初始开始日期 不能大于初始结束日期
        if (startDate.after(endDate)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("初始开始日期不能大于初始结束日期!")
                    .build();
        }

        //3、结束日期不能为当前日期或大于当前日期
        if (endDate.after(today)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("结束日期不能大于当前日期!")
                    .build();
        }
        /*if (endDate.equals(today)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("结束日期不能为当前日期!")
                    .build();
        }*/

        String organizeCode = AuthUtil.getOrganize().getOrganizeCode();
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        packBean.setOrderByStr(" order by accidentDate desc");
        List<MesAccidentDate> accidentDateList = accidentDateRepository.findByHqlWhere(packBean);
        //判断是否有维护的事故日期
        if (!CollectionUtils.isEmpty(accidentDateList)) {

            //4.选中的初始开始日期 不能小于最新事故日期
            String accidentDateStr = accidentDateList.iterator().next().getAccidentDate();
            Date accidentDate = DateUtil.parse(accidentDateStr, DateUtil.SHORT_FORMAT);
            if (startDate.equals(accidentDate)) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                        .setErrorDetail("初始开始日期不能为最新事故日期!")
                        .build();
            }
            if (startDate.before(accidentDate)) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                        .setErrorDetail("初始开始日期不能小于最新事故日期!")
                        .build();
            }

            int initDays = TimeTool.getSecoundsBetweenTime(4, accidentDateStr, numberOfSafeOperationDays.getInitEndDate());
            numberOfSafeOperationDays.setInitDays(initDays);

            ConvertBean.saveOrUpdate(numberOfSafeOperationDays, AuthUtil.getSessionUser().getUserName());

            return numberOfSafeOperationDaysRepository.save(numberOfSafeOperationDays);
            //计算并且设置安全运行天数
            //return saveMesNumberOfSafeOperationDays(numberOfSafeOperationDays, accidentDate, endDate);
        }

        if (numberOfSafeOperationDays.getInitStartDate().equals(numberOfSafeOperationDays.getInitEndDate())) {
            numberOfSafeOperationDays.setInitDays(1);
        } else {
            int initDays = TimeTool.getSecoundsBetweenTime(4, numberOfSafeOperationDays.getInitStartDate(), numberOfSafeOperationDays.getInitEndDate());
            numberOfSafeOperationDays.setInitDays(initDays+1);
        }


        ConvertBean.saveOrUpdate(numberOfSafeOperationDays, AuthUtil.getSessionUser().getUserName());

        return numberOfSafeOperationDaysRepository.save(numberOfSafeOperationDays);
        //计算并且设置安全运行天数
        //return saveMesNumberOfSafeOperationDays(numberOfSafeOperationDays, startDate, endDate);

    }

    /**
     * @return cn.estsh.i3plus.ext.mes.pojo.bean.MesNumberOfSafeOperationDays
     * @Description: 计算并且设置安全运行天数
     * @Param [numberOfSafeOperationDays, startDate, endDate]
     * @Date 2021/7/1 14:54
     **/
    private MesNumberOfSafeOperationDays saveMesNumberOfSafeOperationDays(MesNumberOfSafeOperationDays numberOfSafeOperationDays, Date startDate, Date endDate) {
        /*//计算初始天数
        int initDays = (int) ((endDate.getTime()) - (startDate.getTime()) / (1000 * 3600 * 24));
        //设置初始安全运行天数
        numberOfSafeOperationDays.setInitDays(initDays);*/

        //int initDays = (int) ((initEndDate.getTime()) - dateAccidentDate.getTime()) / (1000 * 3600 * 24);
        Long initDays = DateUtil.daysBetweenTwoTime(endDate, startDate);
        //设置初始安全运行天数
        numberOfSafeOperationDays.setInitDays(Integer.valueOf(String.valueOf(initDays)));


        ConvertBean.saveOrUpdate(numberOfSafeOperationDays, AuthUtil.getSessionUser().getUserName());
        return numberOfSafeOperationDaysRepository.save(numberOfSafeOperationDays);
    }

    @Override
    public MesNumberOfSafeOperationDays queryNumberOfSafeOperationDays(String organizeCode) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        return numberOfSafeOperationDaysRepository.getByProperty(packBean);
    }

    @Override
    public MesNumberOfSafeOperationDays queryNumberOfSafeOperationDaysBoard(String organizeCode) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        MesNumberOfSafeOperationDays numberOfSafeOperationDays = numberOfSafeOperationDaysRepository.getByProperty(packBean);
        log.info("BI看板日期numberOfSafeOperationDays：{}", numberOfSafeOperationDays);
        //当前日期
        Date nowDate = DateUtil.parse(TimeTool.getToday(), DateUtil.SHORT_FORMAT);
        String nowTime = TimeTool.getNowTime(true);


        //格式化开始日期作比较
        Date startDate = DateUtil.parse(numberOfSafeOperationDays.getInitStartDate(), DateUtil.SHORT_FORMAT);
        log.info("BI看板日期startDate：{}", startDate);

        int compareTo = nowDate.compareTo(startDate);
        log.info("BI看板日期nowDate：{}", nowDate);


        //如果当前时间在安全开始时间之后，则截取当前月份的安全天数结果
        if (compareTo == 0 || compareTo == 1) {
            //获取当月开始日期
            String minMonthDate = TimeTool.getMinMonthDate(nowTime);

            int compareTo2 = startDate.compareTo(DateUtil.parse(minMonthDate, DateUtil.SHORT_FORMAT));
            if (compareTo2 == -1) {
                log.info("BI看板日期minMonthDate：{}", minMonthDate);
                //设置为当月开始日期
                numberOfSafeOperationDays.setInitStartDate(minMonthDate);
            }

        }

        return numberOfSafeOperationDays;
    }

    @Override
    public MesNumberOfSafeOperationDaysModel queryBuNumberOfSafeOperationDaysBoard(String organizeCode) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        MesNumberOfSafeOperationDays numberOfSafeOperationDays = numberOfSafeOperationDaysRepository.getByProperty(packBean);
        log.info("BI看板日期numberOfSafeOperationDays：{}", numberOfSafeOperationDays);
        // 如果当天存在事故日期 开始日期 为： “---”
        MesNumberOfSafeOperationDaysModel model = new MesNumberOfSafeOperationDaysModel();
        BeanUtils.copyProperties(numberOfSafeOperationDays, model);
        MesAccidentDate maxMesAccidentDate = getMaxMesAccidentDate(organizeCode);
        if(maxMesAccidentDate != null){
            if(maxMesAccidentDate.getAccidentDate().compareTo(TimeTool.getToday()) == 0){
                model.setSafeStartDate("---");
            }else{
                model.setSafeStartDate(TimeTool.timeCalc(TimeTool.stringParseToDate(maxMesAccidentDate.getAccidentDate(), MesExtConstWords.DATE_FORMAT), Calendar.DATE, 1, MesExtConstWords.DATE_FORMAT));
            }
        }else{
            model.setSafeStartDate(model.getInitStartDate());
        }
        //当前日期
        Date nowDate = DateUtil.parse(TimeTool.getToday(), DateUtil.SHORT_FORMAT);
        String nowTime = TimeTool.getNowTime(true);

        //格式化开始日期作比较
        Date startDate = DateUtil.parse(numberOfSafeOperationDays.getInitStartDate(), DateUtil.SHORT_FORMAT);
        log.info("BI看板日期startDate：{}", startDate);

        int compareTo = nowDate.compareTo(startDate);
        log.info("BI看板日期nowDate：{}", nowDate);

        //如果当前时间在安全开始时间之后，则截取当前月份的安全天数结果
        if (compareTo == 0 || compareTo == 1) {
            //获取当月开始日期
            String minMonthDate = TimeTool.getMinMonthDate(nowTime);

            int compareTo2 = startDate.compareTo(DateUtil.parse(minMonthDate, DateUtil.SHORT_FORMAT));
            if (compareTo2 == -1) {
                log.info("BI看板日期minMonthDate：{}", minMonthDate);
                //设置为当月开始日期
                model.setInitStartDate(minMonthDate);
            }
        }

        return model;
    }

    private MesAccidentDate getMaxMesAccidentDate(String organizeCode){
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        packBean.setOrderByStr(" order by accidentDate desc ");
        return accidentDateRepository.getByProperty(packBean);
    }


}
