package com.prolog.rdc.tms.service.impl;

import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import com.prolog.common.util.ToolKits;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.core.restriction.Restriction;
import com.prolog.framework.core.restriction.Restrictions;
import com.prolog.rdc.tms.constant.DataDictionaryConstant;
import com.prolog.rdc.tms.dao.mapper.TmsShipbillHeaderMapper;
import com.prolog.rdc.tms.model.dto.basicConfigure.SysAlertConfigurationQueryDTO;
import com.prolog.rdc.tms.model.dto.basicConfigure.SysAlertUsersQueryDTO;
import com.prolog.rdc.tms.model.entity.TmsShipbillHeaderModel;
import com.prolog.rdc.tms.model.vo.basicConfigure.AlertMessageAddVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.SysAlertConfigurationQueryVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.SysAlertUsersQueryVO;
import com.prolog.rdc.tms.rmi.feign.MaindataFeign;
import com.prolog.rdc.tms.service.AlertJobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 预警实现层
 * <p>
 * Company: 湖北普罗格科技股份有限公司
 *
 * @author lhb
 * @since 2022/7/15 14:01
 */
@Service
public class AlertJobServiceImpl implements AlertJobService {

    @Autowired
    private MaindataFeign maindataTmsResource;

    @Autowired
    private TmsShipbillHeaderMapper tmsShipbillHeaderMapper;

    /**
     * 未及时提货预警处理
     *
     * @param
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    public void notPicUpAlert() {
        List<SysAlertConfigurationQueryDTO> AlertConfigurationList = Lists.newArrayList();
        List<SysAlertUsersQueryDTO> usersQueryDTOList = Lists.newArrayList();

        Date date = DateUtil.date();
        // 预警配置查询
        SysAlertConfigurationQueryVO configurationQueryVO = new SysAlertConfigurationQueryVO();
        configurationQueryVO.setSearch("未及时提货");
        RestMessage<List<SysAlertConfigurationQueryDTO>> restMessage1 = maindataTmsResource.listAlertConfigurationExecute(configurationQueryVO);
        if (!restMessage1.isSuccess()) {
            throw new RuntimeException("未及时提货预警配置查询调用失败!");
        } else {
            AlertConfigurationList = restMessage1.getData();
        }
        List<AlertMessageAddVO> alertMessageAddVOS = Lists.newArrayList();
        for (SysAlertConfigurationQueryDTO alertConfigurationQueryDTO : AlertConfigurationList) {
            // 预警配置用户查询
            SysAlertUsersQueryVO usersQueryVO = new SysAlertUsersQueryVO();
            usersQueryVO.setEarlyWarningId(alertConfigurationQueryDTO.getEarlyWarningId());
            RestMessage<List<SysAlertUsersQueryDTO>> restMessage2 = maindataTmsResource.listAlertUsersExecute(usersQueryVO);
            if (!restMessage1.isSuccess()) {
                throw new RuntimeException("未及时提货预警配置用户查询调用失败!");
            } else {
                usersQueryDTOList = restMessage2.getData();
            }

            String startUnit = alertConfigurationQueryDTO.getStartTimeOffsetUnit();
            String endUnit = alertConfigurationQueryDTO.getEndTimeOffsetUnit();
            Date startDate = null;
            Date endDate = null;
            if (startUnit.equals("小时")) {
                endDate = DateUtil.offsetHour(date, alertConfigurationQueryDTO.getStartTimeOffset().intValue());
            } else if (startUnit.equals("天")) {
                endDate = DateUtil.offsetDay(date, alertConfigurationQueryDTO.getStartTimeOffset().intValue());
            } else {
                endDate = DateUtil.offsetMinute(date, alertConfigurationQueryDTO.getStartTimeOffset().intValue());
            }

            if (endUnit.equals("小时")) {
                startDate = DateUtil.offsetHour(date, -alertConfigurationQueryDTO.getEndTimeOffset().intValue());
            } else if (startUnit.equals("天")) {
                startDate = DateUtil.offsetDay(date, -alertConfigurationQueryDTO.getStartTimeOffset().intValue());
            } else {
                startDate = DateUtil.offsetMinute(date, -alertConfigurationQueryDTO.getStartTimeOffset().intValue());
            }

            // 运单匹配
            Criteria criteria = Criteria.forClass(TmsShipbillHeaderModel.class);
            Restriction r1 = Restrictions.in(TmsShipbillHeaderModel::getConsigneeUnitId, alertConfigurationQueryDTO.getCustomerIds().split(","));
            Restriction r2 = Restrictions.lt(TmsShipbillHeaderModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_QY);
            Restriction r3 = Restrictions.ge(TmsShipbillHeaderModel::getEstimatedPickupStartTime, startDate);
            Restriction r4 = Restrictions.le(TmsShipbillHeaderModel::getEstimatedPickupStartTime, endDate);
            criteria.setRestriction(Restrictions.and(r1, r2, r3, r4));
            List<TmsShipbillHeaderModel> tmsShipbillHeaderModels = tmsShipbillHeaderMapper.findByCriteria(criteria);

            for (SysAlertUsersQueryDTO usersQueryDTO : usersQueryDTOList) {
                for (TmsShipbillHeaderModel headerModel : tmsShipbillHeaderModels) {
                    AlertMessageAddVO messageAddVO = new AlertMessageAddVO();
                    messageAddVO.setMessage(alertConfigurationQueryDTO.getDescribe());
                    messageAddVO.setCustomerIds(alertConfigurationQueryDTO.getCustomerIds());
                    messageAddVO.setCustomerCodes(alertConfigurationQueryDTO.getCustomerCodes());
                    messageAddVO.setCustomerNames(alertConfigurationQueryDTO.getCustomerNames());
                    messageAddVO.setReceiveEnterpriseId(String.valueOf(alertConfigurationQueryDTO.getEnterpriseId()));
                    messageAddVO.setReceiveEnterpriseName(alertConfigurationQueryDTO.getEnterprisename());

                    messageAddVO.setRefbillid(headerModel.getShipbillId());
                    messageAddVO.setRefbillno(headerModel.getShipbillNo());

                    messageAddVO.setReceivePeopleId(usersQueryDTO.getUserid());
                    messageAddVO.setReceivePeopleName(usersQueryDTO.getUsername());
                    messageAddVO.setReceiveDepartmentId(usersQueryDTO.getDepartmentId());
                    messageAddVO.setReceiveDepartmentName(usersQueryDTO.getDepartmentName());
                    alertMessageAddVOS.add(messageAddVO);
                }
            }
        }

        if (ToolKits.isNotEmpty(alertMessageAddVOS)) {
            RestMessage<String> rs = maindataTmsResource.alertMessageAddExecute(alertMessageAddVOS);
            if (!rs.isSuccess()) {
                throw new RuntimeException("未及时提货预警消息作成失败!");
            }
        }
    }

    /**
     * 未及时送货预警处理
     *
     * @param
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    public void notDeliveryAlert() {
        List<SysAlertConfigurationQueryDTO> AlertConfigurationList = Lists.newArrayList();
        List<SysAlertUsersQueryDTO> usersQueryDTOList = Lists.newArrayList();

        Date date = DateUtil.date();
        // 预警配置查询
        SysAlertConfigurationQueryVO configurationQueryVO = new SysAlertConfigurationQueryVO();
        configurationQueryVO.setSearch("未及时送货");
        RestMessage<List<SysAlertConfigurationQueryDTO>> restMessage1 = maindataTmsResource.listAlertConfigurationExecute(configurationQueryVO);
        if (!restMessage1.isSuccess()) {
            throw new RuntimeException("未及时送货预警配置查询调用失败!");
        } else {
            AlertConfigurationList = restMessage1.getData();
        }
        List<AlertMessageAddVO> alertMessageAddVOS = Lists.newArrayList();
        for (SysAlertConfigurationQueryDTO alertConfigurationQueryDTO : AlertConfigurationList) {
            // 预警配置用户查询
            SysAlertUsersQueryVO usersQueryVO = new SysAlertUsersQueryVO();
            usersQueryVO.setEarlyWarningId(alertConfigurationQueryDTO.getEarlyWarningId());
            RestMessage<List<SysAlertUsersQueryDTO>> restMessage2 = maindataTmsResource.listAlertUsersExecute(usersQueryVO);
            if (!restMessage1.isSuccess()) {
                throw new RuntimeException("未及时送货预警配置用户查询调用失败!");
            } else {
                usersQueryDTOList = restMessage2.getData();
            }

            String startUnit = alertConfigurationQueryDTO.getStartTimeOffsetUnit();
            String endUnit = alertConfigurationQueryDTO.getEndTimeOffsetUnit();
            Date startDate = null;
            Date endDate = null;
            if (startUnit.equals("小时")) {
                endDate = DateUtil.offsetHour(date, alertConfigurationQueryDTO.getStartTimeOffset().intValue());
            } else if (startUnit.equals("天")) {
                endDate = DateUtil.offsetDay(date, alertConfigurationQueryDTO.getStartTimeOffset().intValue());
            } else {
                endDate = DateUtil.offsetMinute(date, alertConfigurationQueryDTO.getStartTimeOffset().intValue());
            }

            if (endUnit.equals("小时")) {
                startDate = DateUtil.offsetHour(date, -alertConfigurationQueryDTO.getEndTimeOffset().intValue());
            } else if (startUnit.equals("天")) {
                startDate = DateUtil.offsetDay(date, -alertConfigurationQueryDTO.getStartTimeOffset().intValue());
            } else {
                startDate = DateUtil.offsetMinute(date, -alertConfigurationQueryDTO.getStartTimeOffset().intValue());
            }

            // 运单匹配
            Criteria criteria = Criteria.forClass(TmsShipbillHeaderModel.class);
            Restriction r1 = Restrictions.in(TmsShipbillHeaderModel::getConsigneeUnitId, alertConfigurationQueryDTO.getCustomerIds().split(","));
            Restriction r2 = Restrictions.lt(TmsShipbillHeaderModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_QY);
            Restriction r3 = Restrictions.ge(TmsShipbillHeaderModel::getEstimatedDeliveryStartTime, startDate);
            Restriction r4 = Restrictions.le(TmsShipbillHeaderModel::getEstimatedDeliveryStartTime, endDate);
            criteria.setRestriction(Restrictions.and(r1, r2, r3, r4));
            List<TmsShipbillHeaderModel> tmsShipbillHeaderModels = tmsShipbillHeaderMapper.findByCriteria(criteria);

            for (SysAlertUsersQueryDTO usersQueryDTO : usersQueryDTOList) {
                for (TmsShipbillHeaderModel headerModel : tmsShipbillHeaderModels) {
                    AlertMessageAddVO messageAddVO = new AlertMessageAddVO();
                    messageAddVO.setMessage(alertConfigurationQueryDTO.getDescribe());
                    messageAddVO.setCustomerIds(alertConfigurationQueryDTO.getCustomerIds());
                    messageAddVO.setCustomerCodes(alertConfigurationQueryDTO.getCustomerCodes());
                    messageAddVO.setCustomerNames(alertConfigurationQueryDTO.getCustomerNames());
                    messageAddVO.setReceiveEnterpriseId(String.valueOf(alertConfigurationQueryDTO.getEnterpriseId()));
                    messageAddVO.setReceiveEnterpriseName(alertConfigurationQueryDTO.getEnterprisename());

                    messageAddVO.setRefbillid(headerModel.getShipbillId());
                    messageAddVO.setRefbillno(headerModel.getShipbillNo());

                    messageAddVO.setReceivePeopleId(usersQueryDTO.getUserid());
                    messageAddVO.setReceivePeopleName(usersQueryDTO.getUsername());
                    messageAddVO.setReceiveDepartmentId(usersQueryDTO.getDepartmentId());
                    messageAddVO.setReceiveDepartmentName(usersQueryDTO.getDepartmentName());
                    alertMessageAddVOS.add(messageAddVO);
                }
            }
        }

        RestMessage<String> rs = maindataTmsResource.alertMessageAddExecute(alertMessageAddVOS);
        if (!rs.isSuccess()) {
            throw new RuntimeException("未及时送货预警消息作成失败!");
        }
    }

    /**
     * 未及时理货预警处理
     *
     * @param
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    public void notArrangeAlert() {
        List<SysAlertConfigurationQueryDTO> AlertConfigurationList = Lists.newArrayList();
        List<SysAlertUsersQueryDTO> usersQueryDTOList = Lists.newArrayList();

        Date date = DateUtil.date();
        // 预警配置查询
        SysAlertConfigurationQueryVO configurationQueryVO = new SysAlertConfigurationQueryVO();
        configurationQueryVO.setSearch("未及时理货");
        RestMessage<List<SysAlertConfigurationQueryDTO>> restMessage1 = maindataTmsResource.listAlertConfigurationExecute(configurationQueryVO);
        if (!restMessage1.isSuccess()) {
            throw new RuntimeException("未及时理货预警配置查询调用失败!");
        } else {
            AlertConfigurationList = restMessage1.getData();
        }
        List<AlertMessageAddVO> alertMessageAddVOS = Lists.newArrayList();
        for (SysAlertConfigurationQueryDTO alertConfigurationQueryDTO : AlertConfigurationList) {
            // 预警配置用户查询
            SysAlertUsersQueryVO usersQueryVO = new SysAlertUsersQueryVO();
            usersQueryVO.setEarlyWarningId(alertConfigurationQueryDTO.getEarlyWarningId());
            RestMessage<List<SysAlertUsersQueryDTO>> restMessage2 = maindataTmsResource.listAlertUsersExecute(usersQueryVO);
            if (!restMessage1.isSuccess()) {
                throw new RuntimeException("未及时理货预警配置用户查询调用失败!");
            } else {
                usersQueryDTOList = restMessage2.getData();
            }

            String startUnit = alertConfigurationQueryDTO.getStartTimeOffsetUnit();
            String endUnit = alertConfigurationQueryDTO.getEndTimeOffsetUnit();
            Date startDate = null;
            Date endDate = null;
            if (startUnit.equals("小时")) {
                endDate = DateUtil.offsetHour(date, alertConfigurationQueryDTO.getStartTimeOffset().intValue());
            } else if (startUnit.equals("天")) {
                endDate = DateUtil.offsetDay(date, alertConfigurationQueryDTO.getStartTimeOffset().intValue());
            } else {
                endDate = DateUtil.offsetMinute(date, alertConfigurationQueryDTO.getStartTimeOffset().intValue());
            }

            if (endUnit.equals("小时")) {
                startDate = DateUtil.offsetHour(date, -alertConfigurationQueryDTO.getEndTimeOffset().intValue());
            } else if (startUnit.equals("天")) {
                startDate = DateUtil.offsetDay(date, -alertConfigurationQueryDTO.getStartTimeOffset().intValue());
            } else {
                startDate = DateUtil.offsetMinute(date, -alertConfigurationQueryDTO.getStartTimeOffset().intValue());
            }

            // 运单匹配
            Criteria criteria = Criteria.forClass(TmsShipbillHeaderModel.class);
            Restriction r1 = Restrictions.in(TmsShipbillHeaderModel::getConsigneeUnitId, alertConfigurationQueryDTO.getCustomerIds().split(","));
            Restriction r2 = Restrictions.lt(TmsShipbillHeaderModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_LH_FINISH);
            Restriction r3 = Restrictions.ge(TmsShipbillHeaderModel::getEstimatedPickupStartTime, startDate);
            Restriction r4 = Restrictions.le(TmsShipbillHeaderModel::getEstimatedPickupStartTime, endDate);
            criteria.setRestriction(Restrictions.and(r1, r2, r3, r4));
            criteria.setRestriction(Restrictions.and(r1, r2));
            List<TmsShipbillHeaderModel> tmsShipbillHeaderModels = tmsShipbillHeaderMapper.findByCriteria(criteria);

            for (SysAlertUsersQueryDTO usersQueryDTO : usersQueryDTOList) {
                for (TmsShipbillHeaderModel headerModel : tmsShipbillHeaderModels) {
                    AlertMessageAddVO messageAddVO = new AlertMessageAddVO();
                    messageAddVO.setMessage(alertConfigurationQueryDTO.getDescribe());
                    messageAddVO.setCustomerIds(alertConfigurationQueryDTO.getCustomerIds());
                    messageAddVO.setCustomerCodes(alertConfigurationQueryDTO.getCustomerCodes());
                    messageAddVO.setCustomerNames(alertConfigurationQueryDTO.getCustomerNames());
                    messageAddVO.setReceiveEnterpriseId(String.valueOf(alertConfigurationQueryDTO.getEnterpriseId()));
                    messageAddVO.setReceiveEnterpriseName(alertConfigurationQueryDTO.getEnterprisename());

                    messageAddVO.setRefbillid(headerModel.getShipbillId());
                    messageAddVO.setRefbillno(headerModel.getShipbillNo());

                    messageAddVO.setReceivePeopleId(usersQueryDTO.getUserid());
                    messageAddVO.setReceivePeopleName(usersQueryDTO.getUsername());
                    messageAddVO.setReceiveDepartmentId(usersQueryDTO.getDepartmentId());
                    messageAddVO.setReceiveDepartmentName(usersQueryDTO.getDepartmentName());
                    alertMessageAddVOS.add(messageAddVO);
                }
            }
        }

        RestMessage<String> rs = maindataTmsResource.alertMessageAddExecute(alertMessageAddVOS);
        if (!rs.isSuccess()) {
            throw new RuntimeException("未及时理货预警消息作成失败!");
        }
    }

    /**
     * 未及时装卸预警处理
     *
     * @param
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    public void notLoadingAndUnLoadingAlert() {
        List<SysAlertConfigurationQueryDTO> AlertConfigurationList = Lists.newArrayList();
        List<SysAlertUsersQueryDTO> usersQueryDTOList = Lists.newArrayList();

        Date date = DateUtil.date();
        // 预警配置查询
        SysAlertConfigurationQueryVO configurationQueryVO = new SysAlertConfigurationQueryVO();
        configurationQueryVO.setSearch("未及时装卸");
        RestMessage<List<SysAlertConfigurationQueryDTO>> restMessage1 = maindataTmsResource.listAlertConfigurationExecute(configurationQueryVO);
        if (!restMessage1.isSuccess()) {
            throw new RuntimeException("未及时装卸预警配置查询调用失败!");
        } else {
            AlertConfigurationList = restMessage1.getData();
        }
        List<AlertMessageAddVO> alertMessageAddVOS = Lists.newArrayList();
        for (SysAlertConfigurationQueryDTO alertConfigurationQueryDTO : AlertConfigurationList) {
            // 预警配置用户查询
            SysAlertUsersQueryVO usersQueryVO = new SysAlertUsersQueryVO();
            usersQueryVO.setEarlyWarningId(alertConfigurationQueryDTO.getEarlyWarningId());
            RestMessage<List<SysAlertUsersQueryDTO>> restMessage2 = maindataTmsResource.listAlertUsersExecute(usersQueryVO);
            if (!restMessage1.isSuccess()) {
                throw new RuntimeException("未及时装卸预警配置用户查询调用失败!");
            } else {
                usersQueryDTOList = restMessage2.getData();
            }

            String startUnit = alertConfigurationQueryDTO.getStartTimeOffsetUnit();
            String endUnit = alertConfigurationQueryDTO.getEndTimeOffsetUnit();
            Date startDate = null;
            Date endDate = null;
            if (startUnit.equals("小时")) {
                endDate = DateUtil.offsetHour(date, alertConfigurationQueryDTO.getStartTimeOffset().intValue());
            } else if (startUnit.equals("天")) {
                endDate = DateUtil.offsetDay(date, alertConfigurationQueryDTO.getStartTimeOffset().intValue());
            } else {
                endDate = DateUtil.offsetMinute(date, alertConfigurationQueryDTO.getStartTimeOffset().intValue());
            }

            if (endUnit.equals("小时")) {
                startDate = DateUtil.offsetHour(date, -alertConfigurationQueryDTO.getEndTimeOffset().intValue());
            } else if (startUnit.equals("天")) {
                startDate = DateUtil.offsetDay(date, -alertConfigurationQueryDTO.getStartTimeOffset().intValue());
            } else {
                startDate = DateUtil.offsetMinute(date, -alertConfigurationQueryDTO.getStartTimeOffset().intValue());
            }

            // 运单匹配
            Criteria criteria = Criteria.forClass(TmsShipbillHeaderModel.class);
            Restriction r1 = Restrictions.in(TmsShipbillHeaderModel::getConsigneeUnitId, alertConfigurationQueryDTO.getCustomerIds().split(","));
            Restriction r2 = Restrictions.lt(TmsShipbillHeaderModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_ZX_FINISH);
            Restriction r3 = Restrictions.ge(TmsShipbillHeaderModel::getEstimatedPickupStartTime, startDate);
            Restriction r4 = Restrictions.le(TmsShipbillHeaderModel::getEstimatedPickupStartTime, endDate);
            criteria.setRestriction(Restrictions.and(r1, r2, r3, r4));
            List<TmsShipbillHeaderModel> tmsShipbillHeaderModels = tmsShipbillHeaderMapper.findByCriteria(criteria);

            for (SysAlertUsersQueryDTO usersQueryDTO : usersQueryDTOList) {
                for (TmsShipbillHeaderModel headerModel : tmsShipbillHeaderModels) {
                    AlertMessageAddVO messageAddVO = new AlertMessageAddVO();
                    messageAddVO.setMessage(alertConfigurationQueryDTO.getDescribe());
                    messageAddVO.setCustomerIds(alertConfigurationQueryDTO.getCustomerIds());
                    messageAddVO.setCustomerCodes(alertConfigurationQueryDTO.getCustomerCodes());
                    messageAddVO.setCustomerNames(alertConfigurationQueryDTO.getCustomerNames());
                    messageAddVO.setReceiveEnterpriseId(String.valueOf(alertConfigurationQueryDTO.getEnterpriseId()));
                    messageAddVO.setReceiveEnterpriseName(alertConfigurationQueryDTO.getEnterprisename());

                    messageAddVO.setRefbillid(headerModel.getShipbillId());
                    messageAddVO.setRefbillno(headerModel.getShipbillNo());

                    messageAddVO.setReceivePeopleId(usersQueryDTO.getUserid());
                    messageAddVO.setReceivePeopleName(usersQueryDTO.getUsername());
                    messageAddVO.setReceiveDepartmentId(usersQueryDTO.getDepartmentId());
                    messageAddVO.setReceiveDepartmentName(usersQueryDTO.getDepartmentName());
                    alertMessageAddVOS.add(messageAddVO);
                }
            }
        }

        RestMessage<String> rs = maindataTmsResource.alertMessageAddExecute(alertMessageAddVOS);
        if (!rs.isSuccess()) {
            throw new RuntimeException("未及时装卸预警消息作成失败!");
        }
    }
}
