/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.depotAlarm.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.api.cloud.param.DepotCloudAlarmAddParam;
import vip.xiaonuo.biz.core.Const.BizStr;
import vip.xiaonuo.biz.modular.depotAlarm.entity.DepotAlarmAddCountGroupTypeVo;
import vip.xiaonuo.biz.modular.depotAlarm.param.*;
import vip.xiaonuo.biz.modular.depotDeviceWarn.entity.DepotDeviceWarn;
import vip.xiaonuo.biz.modular.depotDeviceWarn.param.DepotDeviceWarnAddParam;
import vip.xiaonuo.biz.modular.depotDeviceWarn.service.DepotDeviceWarnService;
import vip.xiaonuo.biz.modular.depotGrain.service.DepotGrainService;
import vip.xiaonuo.biz.modular.depotGrainInfoWarn.entity.DepotGrainInfoWarn;
import vip.xiaonuo.biz.modular.depotTruckBook.entity.DepotTruckBook;
import vip.xiaonuo.biz.modular.depotTruckBook.service.DepotTruckBookService;
import vip.xiaonuo.biz.modular.depotWorkAlarm.entity.DepotWorkAlarm;
import vip.xiaonuo.biz.modular.depotWorkAlarm.param.DepotWorkAlarmAddParam;
import vip.xiaonuo.biz.modular.depotWorkAlarm.service.DepotWorkAlarmService;
import vip.xiaonuo.biz.modular.depotWorkAlarmSet.service.DepotWorkAlarmSetService;
import vip.xiaonuo.biz.modular.sysUserWxOpenSendLog.service.SysUserWxOpenSendLogService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.depotAlarm.entity.DepotAlarm;
import vip.xiaonuo.biz.modular.depotAlarm.mapper.DepotAlarmMapper;
import vip.xiaonuo.common.util.BeanCopyUtil;
import vip.xiaonuo.common.util.DatesUtil;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 异常报警Service接口实现类
 *
 * @author xiang
 * @date 2023/09/19 16:23
 **/
@Service
public class DepotAlarmService extends ServiceImpl<DepotAlarmMapper, DepotAlarm> {

    @Resource
    DepotGrainService depotGrainService;

    public Page<DepotAlarm> page(DepotAlarmPageParam param) {
        QueryWrapper<DepotAlarm> wrapper = new QueryWrapper<>();
        grep(param, wrapper);
        if (ObjectUtil.isAllNotEmpty(param.getSortField(), param.getSortOrder())) {
            CommonSortOrderEnum.validate(param.getSortOrder());
            wrapper.orderBy(true, param.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(param.getSortField()));
        } else {
            wrapper.lambda().orderByDesc(DepotAlarm::getId);
        }
        Page page = this.page(CommonPageRequest.defaultPage(), wrapper);
        //匹配粮库名称
        depotGrainService.putDepotName(page.getRecords());
        return page;
    }

    /**
     * 条件查询
     *
     * @author xiang
     * @date 2023/09/19 16:23
     **/
    public List<DepotAlarm> lst(DepotAlarmPageParam param) {
        QueryWrapper<DepotAlarm> wrapper = new QueryWrapper<>();
        grep(param, wrapper);
        return list(wrapper);
    }

    /**
     * 条件查询
     *
     * @author xiang
     * @date 2023/09/19 16:23
     **/
    public List<DepotAlarm> list(DepotAlarmPageParam param) {
        List<DepotAlarm> list = lst(param);
        //匹配粮库名称
        depotGrainService.putDepotName(list);
        return list;
    }

    /**
     * 条件匹配
     *
     * @author xiang
     * @date 2023/09/19 16:23
     **/
    private QueryWrapper grep(DepotAlarmPageParam param, QueryWrapper<DepotAlarm> wrapper) {
        param.setDepotIdLst(param.getDepotIdLst() != null && param.getDepotIdLst().isEmpty() ? depotGrainService.lstOrgGrep() : param.getDepotIdLst());
        wrapper.lambda().in(CollUtil.isNotEmpty(param.getDepotIdLst()), DepotAlarm::getDepotId, param.getDepotIdLst());
        if (ObjectUtil.isNotEmpty(param.getDepotId())) {
            wrapper.lambda().eq(DepotAlarm::getDepotId, param.getDepotId());
        }
        if (ObjectUtil.isNotEmpty(param.getAlarmType())) {
            wrapper.lambda().eq(DepotAlarm::getAlarmType, param.getAlarmType());
        }
        if (ObjectUtil.isNotEmpty(param.getSaveState())) {
            wrapper.lambda().eq(DepotAlarm::getSaveState, param.getSaveState());
        }
        if (ObjectUtil.isNotEmpty(param.getAlarmMsg())) {
            wrapper.lambda().like(DepotAlarm::getAlarmMsg, param.getAlarmMsg());
        }
        if (ObjectUtil.isNotEmpty(param.getStartCreateTime()) && ObjectUtil.isNotEmpty(param.getEndCreateTime()))
            wrapper.lambda().between(DepotAlarm::getCreateTime, param.getStartCreateTime(), param.getEndCreateTime());
        return wrapper;
    }

    public void add(DepotAlarmAddParam depotAlarmAddParam) {
        DepotAlarm depotAlarm = BeanUtil.toBean(depotAlarmAddParam, DepotAlarm.class);
        this.save(depotAlarm);
    }

    public void adds(List<DepotAlarmAddParam> AddParams) {
        saveBatch(BeanCopyUtil.copyListProperties(AddParams, DepotAlarm::new));
    }

    /**
     * 风险预警
     *
     * @author xiang
     * @date 2023/09/19 16:23
     **/
    @Transactional(rollbackFor = Exception.class)
    public void addByGrainInfoWarn(List<DepotGrainInfoWarn> warns) {
        List<DepotAlarm> alarmAdds = new ArrayList<>();
        List<DepotAlarm> alarmEdits = new ArrayList<>();
        List<DepotGrainInfoWarn> sendWarns = new ArrayList<>();
        Date createTime = new Date();
        for (DepotGrainInfoWarn warn : warns) {
            DepotAlarm alarm = new DepotAlarm(warn.getUnionAlarmId(), warn.getDepotId(), BizStr.ALARM_LOAN, warn.getSaveState()
                    , String.format("%s风险 %s", warn.getWarnType(), warn.getWarnMsg()), warn.getWarnColourLevel());
            if (alarm.getId() == null) {
                alarm.setId(IdWorker.getIdStr());
                warn.setUnionAlarmId(alarm.getId());
                warn.setCreateTime(createTime);
                alarmAdds.add(alarm);
                sendWarns.add(warn);
            } else {
                alarmEdits.add(alarm);
            }
        }
        if (!alarmAdds.isEmpty()) {
            this.saveBatch(alarmAdds);
            //推送微信公众号 客户风险
            sysUserWxOpenSendLogService.send(sendWarns, BizStr.ALARM_LOAN, DatesUtil.forDate(createTime));
        }
        if (!alarmEdits.isEmpty()) {
            this.updateBatchById(alarmEdits);
        }
    }

    public void edit(DepotAlarmEditParam depotAlarmEditParam) {
        DepotAlarm depotAlarm = this.queryEntity(depotAlarmEditParam.getId());
        BeanUtil.copyProperties(depotAlarmEditParam, depotAlarm);
        this.updateById(depotAlarm);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(List<DepotAlarmIdParam> depotAlarmIdParamList) {
        this.deleteByIds(CollStreamUtil.toList(depotAlarmIdParamList, DepotAlarmIdParam::getId));
    }

    public void deleteByIds(List<String> ids) {
        // 执行删除
        this.removeBatchByIds(ids);
    }

    public DepotAlarm detail(DepotAlarmIdParam depotAlarmIdParam) {
        return this.queryEntity(depotAlarmIdParam.getId());
    }

    public DepotAlarm queryEntity(String id) {
        DepotAlarm depotAlarm = this.getById(id);
        if (ObjectUtil.isEmpty(depotAlarm)) {
            throw new CommonException("异常报警不存在，id值为：{}", id);
        }
        return depotAlarm;
    }

    /**
     * 处理
     *
     * @author xiang
     * @date 2023/09/19 16:23
     **/
    public void processById(String id) {
        processById(id, BizStr.STATE_PROCESS_Y);
    }

    /**
     * 处理
     *
     * @author xiang
     * @date 2023/09/19 16:23
     **/
    public void processById(String id, String processState) {
        if (Strings.isBlank(id)) return;
        updateById(new DepotAlarm(id, processState));
    }

    /**
     * 查询待处理统计数量
     *
     * @author xiang
     * @date 2023/09/19 16:23
     **/
    public DepotAlarmAddCountGroupTypeVo getAlarmAddCountGroupType(DepotAlarmPageParam param) {
        param.setSaveState(BizStr.STATE_PROCESS_N);
        List<DepotAlarm> list = lst(param);
        long ALARM_CHU_RU_KU = 0, ALARM_LOAN = 0, ALARM_DEVICE = 0, ALARM_FLYER = 0, ALARM_PROJECT = 0;
        for (DepotAlarm one : list) {
            if (BizStr.ALARM_CHU_RU_KU.equals(one.getAlarmType()))
                ALARM_CHU_RU_KU += 1;
            else if (BizStr.ALARM_LOAN.equals(one.getAlarmType()))
                ALARM_LOAN += 1;
            else if (BizStr.ALARM_DEVICE.equals(one.getAlarmType()))
                ALARM_DEVICE += 1;
            else if (BizStr.ALARM_FLYER.equals(one.getAlarmType()))
                ALARM_FLYER += 1;
            else if (BizStr.ALARM_PROJECT.equals(one.getAlarmType()))
                ALARM_PROJECT += 1;
        }
        return new DepotAlarmAddCountGroupTypeVo(ALARM_CHU_RU_KU, ALARM_LOAN, ALARM_DEVICE, ALARM_FLYER, ALARM_PROJECT);
    }

    @Resource
    private DepotTruckBookService depotTruckBookService;
    @Resource
    private DepotWorkAlarmService depotWorkAlarmService;
    @Resource
    DepotDeviceWarnService deviceWarnService;
    @Resource
    DepotWorkAlarmSetService depotWorkAlarmSetService;
    @Resource
    SysUserWxOpenSendLogService sysUserWxOpenSendLogService;

    /**
     * 添加监控异常
     *
     * @author xiang
     * @date 2023/09/19 16:23
     **/
    public void depotWorkAlarmAdd(DepotCloudAlarmAddParam param) {
        //项目心跳监控
        if ("6".equals(param.getFlowType())) {
            depotGrainService.putOnline(param.getDepotId());
        } else if (Strings.isBlank(param.getAlarmMsg())) {
        }
        //设备离线
        else if ("7".equals(param.getFlowType())) {
            if (!deviceWarnService.lst(new DepotDeviceWarn(param.getDepotId(), param.getDeviceName(), param.getAlarmMsg())).isEmpty()) return;
            DepotDeviceWarn depotDeviceWarn = deviceWarnService.add(new DepotDeviceWarnAddParam(param.getDepotId(), param.getDeviceName(), param.getDeviceTax(), param.getAlarmMsg()));
            //推送微信公众号 设备离线
            sysUserWxOpenSendLogService.send(param.getDepotId(), BizStr.ALARM_DEVICE, depotDeviceWarn.getDeviceName(), DatesUtil.forDateTime(depotDeviceWarn.getCreateTime()));
        }
        //身份识别
        else if ("8".equals(param.getFlowType())) {
            DepotWorkAlarmAddParam addParam = new DepotWorkAlarmAddParam(param.getTruckBookId(), param.getFlowType(), param.getAlarmMsg());
            addParam.setAlarmCause("车辆身份识别");
            addParam.asByBook(BeanUtil.toBean(param, DepotTruckBook.class));
            //报警
            if (depotWorkAlarmSetService.forBaoJing(addParam.getFlowType())) {
                //禁止通行
                depotTruckBookService.processTo(addParam.getTruckBookId(), BizStr.STATE_TRUCK_N);
                addParam.setAlarmType(BizStr.ALARM_TYPE_B);
            }
            DepotWorkAlarm depotWorkAlarm = depotWorkAlarmService.add(addParam);
            //推送微信公众号 出库入库
            sysUserWxOpenSendLogService.send(depotWorkAlarm.getDepotId(), param.getAreaType(), BizStr.ALARM_CHU_RU_KU, depotWorkAlarm.getLicensePlate(), param.getDepotBizType() + depotWorkAlarm.getAlarmType()
                    , param.getAlarmMsg(), param.getCreateTime());
        }
        //出入库异常
        else {
            DepotWorkAlarm alarm = depotWorkAlarmService.getOne(new DepotWorkAlarm(param.getTruckBookId(), param.getFlowType()));
            if (alarm != null) return;
            DepotWorkAlarmAddParam addParam = new DepotWorkAlarmAddParam(param.getTruckBookId(), param.getFlowType(), param.getAlarmMsg());
            addParam.setAlarmCause("出入库现场监管");
            addParam.asByBook(depotTruckBookService.getOneByBookId(addParam.getTruckBookId()));
            //报警
            if (depotWorkAlarmSetService.forBaoJing(addParam.getFlowType())) {
                //禁止通行
                depotTruckBookService.processTo(addParam.getTruckBookId(), BizStr.STATE_TRUCK_N);
                addParam.setAlarmType(BizStr.ALARM_TYPE_B);
            }
            DepotWorkAlarm depotWorkAlarm = depotWorkAlarmService.add(addParam);
            //推送微信公众号 出库入库
            sysUserWxOpenSendLogService.send(depotWorkAlarm.getDepotId(), BizStr.ALARM_CHU_RU_KU, depotWorkAlarm.getLicensePlate(), depotWorkAlarm.getDepotBizType() + depotWorkAlarm.getAlarmType()
                    , param.getAlarmMsg(), DatesUtil.forDateTime(depotWorkAlarm.getCreateTime()));
        }
    }

}
