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

import cn.estsh.i3plus.ext.mes.api.base.IMesAccidentDateService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesAccidentDate;
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.bean.MesProcessCell;
import cn.estsh.i3plus.ext.mes.pojo.model.MesAccidentDateModel;
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.ext.mes.pojo.util.MesExtEnumUtil;
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.platform.common.util.MesConstWords;
import cn.estsh.i3plus.platform.common.util.MesPcnConstWords;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.common.PagerHelper;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.sqlpack.MesHqlPack;
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.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

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

/**
 * @Author: xiangming.liao
 * @CreateDate: 2021/01/17 17:59 下午
 * @Description:
 **/
@Slf4j
@Service
public class MesAccidentDateService implements IMesAccidentDateService {

    @Autowired
    private MesAccidentDateRepository mesAccidentDateRDao;
    @Autowired
    private MesNumberOfSafeOperationDaysRepository numberOfSafeOperationDaysRDao;

    @Override
    public MesAccidentDate insertAccidentDate(MesAccidentDate accidentDate) throws ParseException {
        //日期校验
        Date nowTime = DateUtil.parse(TimeTool.getToday(), DateUtil.SHORT_FORMAT);

        String organizeCode = AuthUtil.getOrganize().getOrganizeCode();
        Date dateAccidentDate = DateUtil.parse(accidentDate.getAccidentDate(), DateUtil.SHORT_FORMAT);

        int nowCompareTo = nowTime.compareTo(dateAccidentDate);
        //如果当前日期不为事故日期

        //查询最新事故日期
        DdlPackBean accidentPackBean = DdlPackBean.getDdlPackBean(organizeCode);
        accidentPackBean.setOrderByStr(" order by accidentDate desc");
        List<MesAccidentDate> accidentDateList = mesAccidentDateRDao.findByHqlWhere(accidentPackBean);

        //如果事故日期超过当前期日期
        if (nowCompareTo == -1) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("事故日期【%s】不能超过当前日期！", dateAccidentDate)
                    .build();
        }

        accidentDate.setOrganizeCode(organizeCode);

        //保存
        ConvertBean.serviceModelInitialize(accidentDate, AuthUtil.getSessionUser().getUserName());
        MesAccidentDate mesAccidentDate = mesAccidentDateRDao.insert(accidentDate);

        //----------如果事故日期在安全运行天数范围内，则清除安全运行天数，重新计算
        //查询安全运行天数

        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        MesNumberOfSafeOperationDays numberOfSafeOperationDays = numberOfSafeOperationDaysRDao.getByProperty(packBean);
        if (null != numberOfSafeOperationDays) {
            //初始开始日期
            Date initStartDate = DateUtil.parse(numberOfSafeOperationDays.getInitStartDate(), DateUtil.SHORT_FORMAT);
            //如果设置的事故日期在安全运行天数的范围内
            if (initStartDate.before(dateAccidentDate) || numberOfSafeOperationDays.getInitStartDate().equals(accidentDate.getAccidentDate())) {
                log.info("如果设置的事故日期在安全运行天数的范围内,{},{}", initStartDate, dateAccidentDate);


                if (!CollectionUtils.isEmpty(accidentDateList)) {
                    Date accidentDateByNew = DateUtil.parse(accidentDateList.iterator().next().getAccidentDate(), DateUtil.SHORT_FORMAT);

                    log.info("accidentDateByNew{}", accidentDateByNew);

                    log.info("通过当前已选择的日期 计算初始天数,{},{}", accidentDateByNew, dateAccidentDate);

                    if (accidentDateByNew.before(dateAccidentDate)) {
                        //通过当前已选择的日期 计算初始天数
                        int initDays = TimeTool.getSecoundsBetweenTime(4, accidentDate.getAccidentDate(), numberOfSafeOperationDays.getInitEndDate());

                        log.info("initDays{}", initDays);

                        //设置初始安全运行天数
                        numberOfSafeOperationDays.setInitDays(initDays);
                        ConvertBean.saveOrUpdate(numberOfSafeOperationDays, AuthUtil.getSessionUser().getUserName());
                        numberOfSafeOperationDaysRDao.save(numberOfSafeOperationDays);
                    }
                } else {
                    int initDays = TimeTool.getSecoundsBetweenTime(4, accidentDate.getAccidentDate(), numberOfSafeOperationDays.getInitEndDate());
                    log.info("通过当前已选择的日期 计算初始天数1,{},{}", accidentDate.getAccidentDate(), numberOfSafeOperationDays.getInitEndDate());

                    //设置初始安全运行天数
                    numberOfSafeOperationDays.setInitDays(initDays);
                    log.info("initDays{}", initDays);

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

        return mesAccidentDate;
    }

    @Override
    public MesAccidentDate insertBuAccidentDate(MesAccidentDate accidentDate) throws ParseException {
        return null;
    }

    @Override
    public MesAccidentDate updateAccidentDate(MesAccidentDate accidentDate) {
        //对id做有效性校验
        MesAccidentDate mesAccidentDateDb = mesAccidentDateRDao.getById(accidentDate.getId());
        if (mesAccidentDateDb == null) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(cn.estsh.impp.framework.boot.exception.ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("事故日期【%s】，事故状态为【%s】的记录不存在"
                            , accidentDate.getAccidentDate(), accidentDate.getAccidentStatus())
                    .build();
        }

        mesAccidentDateDb.setRemark(accidentDate.getRemark());
        ConvertBean.serviceModelUpdate(mesAccidentDateDb, AuthUtil.getSessionUser().getUserName());
        return mesAccidentDateRDao.save(mesAccidentDateDb);
    }

    @Override
    public MesAccidentDate updateBuAccidentDate(MesAccidentDate accidentDate) throws ParseException {
        return null;
    }

    @Override
    public int updateStatusAccidentDate(long id, Integer status) {
        List<MesAccidentDate> bomList = mesAccidentDateRDao.findByProperty(new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID, MesExtConstWords.ID},
                new Object[]{AuthUtil.getOrganize().getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), MesExtEnumUtil.IS_VAILD.VAILD.getValue(), id});
        if (StringUtils.isEmpty(bomList)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("该事故日期不存在")
                    .build();
        }
        return mesAccidentDateRDao.updateByProperties(new String[]{MesExtConstWords.ID}, new Object[]{id},
                new String[]{MesConstWords.IS_VALID, MesExtConstWords.MODIFY_USER, MesExtConstWords.MODIFY_DATE_TIME},
                new Object[]{status, AuthUtil.getSessionUser().getUserName(), TimeTool.getNowTime(true)});
    }

    @Override
    public ListPager<MesAccidentDate> queryAccidentDateByPager(MesAccidentDate accidentDate, Pager pager) {
        DdlPackBean packBean = MesHqlPack.getMesAllData(AuthUtil.getOrganize().getOrganizeCode());
        DdlPreparedPack.getNumEqualPack(accidentDate.getIsValid(), MesExtConstWords.IS_VALID, packBean);
        DdlPreparedPack.getNumEqualPack(accidentDate.getAccidentStatus(), "accidentStatus", packBean);
        DdlPreparedPack.timeBuilder(accidentDate.getCreateDateTimeStart(), accidentDate.getCreateDateTimeEnd(), MesExtConstWords.CREATE_DATE_TIME, packBean, true);
        pager = PagerHelper.getPager(pager, mesAccidentDateRDao.findByHqlWhereCount(packBean));
        packBean.setOrderByStr(accidentDate.orderBy());
        return new ListPager(mesAccidentDateRDao.findByHqlWherePage(packBean, pager), pager);
    }

    @Override
    public MesAccidentDate queryAccidentDateByNewest() {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(AuthUtil.getOrganize().getOrganizeCode());
        packBean.setOrderByStr(" order by accidentDate desc");
        List<MesAccidentDate> accidentDateList = mesAccidentDateRDao.findByHqlWhere(packBean);
        return accidentDateList.iterator().next();
    }

    @Override
    public MesAccidentDateModel queryAccidentDaysBoard(String organizeCode) {
        MesAccidentDateModel accidentDateModel = new MesAccidentDateModel();

        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        // String thisMonth = TimeTool.getToday().substring(0, 7);
        DdlPreparedPack.getStringLikerPack(TimeTool.getYearMonth(DateUtil.parse(TimeTool.getToday(), DateUtil.SHORT_FORMAT)), "accidentDate", packBean);

        //DdlPreparedPack.timeBuilder(thisMonth, thisMonth, "accidentDate", packBean, true);
        packBean.setOrderByStr(" order by accidentDate desc");
        List<MesAccidentDate> accidentDateList = mesAccidentDateRDao.findByHqlWhere(packBean);
        //当月事故日期集合
        accidentDateModel.setMesAccidentDateList(accidentDateList);

        //总事故数量
        DdlPackBean packBeanCount = DdlPackBean.getDdlPackBean(organizeCode);
        accidentDateModel.setAccidentDays(mesAccidentDateRDao.findByHqlWhereCount(packBeanCount));
//        accidentDateModel.setStatisticsDateScope( "("+startDate.replaceAll("-",".") + "——" + endDate.replaceAll("-",".") + ")");
        return accidentDateModel;
    }

    @Override
    public MesAccidentDateModel queryBuAccidentDaysBoard(String organizeCode) {
        MesAccidentDateModel accidentDateModel = new MesAccidentDateModel();

        // 松下年 当年4月-来年3月
        String today = TimeTool.getToday();
        String startDate;
        String endDate;
        String year = today.substring(0,4);
        if(today.substring(5,7).compareTo("03") > 0){
            startDate = year + "-04-01";
            endDate = Integer.valueOf(year) + 1 + "-03-31";
        }else{
            startDate = Integer.valueOf(year) -1 + "-04-01";
            endDate = year + "-03-31";
        }

        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        // String thisMonth = TimeTool.getToday().substring(0, 7);
        DdlPreparedPack.getStringLikerPack(TimeTool.getYearMonth(DateUtil.parse(TimeTool.getToday(), DateUtil.SHORT_FORMAT)), "accidentDate", packBean);
        //DdlPreparedPack.timeBuilder(thisMonth, thisMonth, "accidentDate", packBean, true);
        packBean.setOrderByStr(" order by accidentDate desc");
        List<MesAccidentDate> accidentDateList = mesAccidentDateRDao.findByHqlWhere(packBean);
        //当月事故日期集合
        accidentDateModel.setMesAccidentDateList(accidentDateList);

        //松下年 总事故数量
        DdlPackBean packBeanCount = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.timeBuilder(startDate, endDate, MesExtConstWords.ACCIDENT_DATE, packBeanCount, false);
        accidentDateModel.setAccidentDays(mesAccidentDateRDao.findByHqlWhereCount(packBeanCount));

        accidentDateModel.setStatisticsDateScope( "("+startDate.replaceAll("-",".") + "——" + endDate.replaceAll("-",".") + ")");

        return accidentDateModel;
    }

}
