/*
 * 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.depotFlyerSiteLog.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.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.core.Const.BizStr;
import vip.xiaonuo.biz.modular.depotAlarm.param.DepotAlarmAddParam;
import vip.xiaonuo.biz.modular.depotAlarm.service.DepotAlarmService;
import vip.xiaonuo.biz.modular.depotFlyerSiteLog.param.*;
import vip.xiaonuo.biz.modular.depotGrain.service.DepotGrainService;
import vip.xiaonuo.biz.modular.depotGrainInfo.service.DepotGrainInfoFileService;
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.depotFlyerSiteLog.entity.DepotFlyerSiteLog;
import vip.xiaonuo.biz.modular.depotFlyerSiteLog.mapper.DepotFlyerSiteLogMapper;
import vip.xiaonuo.common.util.DatesUtil;
import vip.xiaonuo.dev.api.DevFileApi;
import vip.xiaonuo.dev.modular.file.util.MultipartFileUtils;

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

/**
 * 飞行监管Service接口实现类
 *
 * @author xiang
 * @date 2023/09/19 09:12
 **/
@Service
public class DepotFlyerSiteLogService extends ServiceImpl<DepotFlyerSiteLogMapper, DepotFlyerSiteLog> {

    @Resource
    DevFileApi devFileApi;
    @Resource
    DepotGrainService depotGrainService;
    @Resource
    DepotAlarmService alarmService;
    @Resource
    SysUserWxOpenSendLogService sysUserWxOpenSendLogService;
    @Resource
    DepotGrainInfoFileService depotGrainInfoFileService;

    public Page<DepotFlyerSiteLog> page(DepotFlyerSiteLogPageParam param) {
        QueryWrapper<DepotFlyerSiteLog> wrapper = new QueryWrapper<>();
        wrapper.and(Strings.isNotEmpty(param.getSearchKey()), w ->
                w.lambda().like(DepotFlyerSiteLog::getSiteMsg, param.getSearchKey())
                        .or().like(DepotFlyerSiteLog::getSaveMsg, param.getSearchKey()));
        List<String> depotIdLst = depotGrainService.lstOrgGrep();
        wrapper.lambda().in(CollUtil.isNotEmpty(depotIdLst), DepotFlyerSiteLog::getDepotId, depotIdLst);
        if (ObjectUtil.isNotEmpty(param.getDepotId())) {
            wrapper.lambda().eq(DepotFlyerSiteLog::getDepotId, param.getDepotId());
        }
        if (ObjectUtil.isNotEmpty(param.getSiteType())) {
            wrapper.lambda().eq(DepotFlyerSiteLog::getSiteType, param.getSiteType());
        }
        if (ObjectUtil.isNotEmpty(param.getSiteLv())) {
            wrapper.lambda().eq(DepotFlyerSiteLog::getSiteLv, param.getSiteLv());
        }
        if (ObjectUtil.isNotEmpty(param.getAlarmFlag())) {
            wrapper.lambda().eq(DepotFlyerSiteLog::getAlarmFlag, param.getAlarmFlag());
        }
        if (ObjectUtil.isNotEmpty(param.getSiteMsg())) {
            wrapper.lambda().like(DepotFlyerSiteLog::getSiteMsg, param.getSiteMsg());
        }
        if (ObjectUtil.isNotEmpty(param.getSaveMsg())) {
            wrapper.lambda().like(DepotFlyerSiteLog::getSaveMsg, param.getSaveMsg());
        }
        if (ObjectUtil.isNotEmpty(param.getSaveState())) {
            wrapper.lambda().eq(DepotFlyerSiteLog::getSaveState, param.getSaveState());
        }
        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(DepotFlyerSiteLog::getId);
        }
        Page page = this.page(CommonPageRequest.defaultPage(), wrapper);
        //匹配粮库名称
        depotGrainService.putDepotName(page.getRecords());
        return page;
    }

    public void add(DepotFlyerSiteLogAddParam param) {
        DepotFlyerSiteLog log = BeanUtil.toBean(param, DepotFlyerSiteLog.class);
        log.setSiteLv("质量数量".contains(log.getSiteType()) ? BizStr.LV_TWO : BizStr.LV_ONE);
        log.setCreateTime(new Date());
        //异常
        if (BizStr.FLAG_SHI.equals(log.getAlarmFlag())) {
            DepotAlarmAddParam alarmAddParam = new DepotAlarmAddParam(log.getDepotId(), BizStr.ALARM_FLYER
                    , StringUtils.join(log.getSiteType(), " ", log.getSiteMsg()));
            alarmService.add(alarmAddParam);
            log.setUnionAlarmId(alarmAddParam.getId());
            log.setSaveState(BizStr.STATE_PROCESS_N);
            //推送微信公众号 飞行监管
            sysUserWxOpenSendLogService.send(log.getDepotId(), BizStr.ALARM_FLYER
                    , StringUtils.join(log.getSiteType(), "，", log.getSiteMsg()), DatesUtil.forDateTime(log.getCreateTime()));
        }
        //监管图片
        if (Strings.isNotEmpty(param.getFile()))
            log.setSitePicUrl(devFileApi.storageFileWithReturnIdLocal(MultipartFileUtils.base64ToMultipart(param.getFile())));
        if (Strings.isNotEmpty(log.getSitePicUrl()) && log.getSitePicUrl().length() == 19) {
            log.setSitePicUrl(devFileApi.storageFilePathReturnUrlById(log.getSitePicUrl()));
        }
        this.save(log);
    }

    public void edit(DepotFlyerSiteLogEditParam param) {
        DepotFlyerSiteLog log = this.queryEntity(param.getId());
        if (BizStr.FLAG_SHI.equals(log.getAlarmFlag())) {
            //处理图片
            if (Strings.isNotBlank(param.getFile()))
                param.setSavePicUrl(devFileApi.storageFileWithReturnIdLocal(MultipartFileUtils.base64ToMultipart(param.getFile())));
            if (param.getSavePicUrl() != null && param.getSavePicUrl().length() == 19)
                param.setSavePicUrl(devFileApi.storageFilePathReturnUrlById(param.getSavePicUrl()));
            if (Strings.isNotEmpty(param.getSaveMsg()) && !param.getSaveMsg().equals(log.getSaveMsg()))
                param.setSaveTime(DatesUtil.forDateTime());
        }
        BeanUtil.copyProperties(param, log);
        this.updateById(log);
    }

    /**
     * 处理确认
     *
     * @author xiang
     * @date 2023/09/19 09:12
     */
    public void processFinish(DepotFlyerSiteLogEditParam param) {
        DepotFlyerSiteLog log = this.queryEntity(param.getId());
        log.setSaveState(param.getSaveState());
        alarmService.processById(log.getUnionAlarmId(), log.getSaveState());
        this.updateById(log);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(List<DepotFlyerSiteLogIdParam> depotFlyerSiteLogIdParamList) {
        // 执行删除
        this.removeBatchByIds(CollStreamUtil.toList(depotFlyerSiteLogIdParamList, DepotFlyerSiteLogIdParam::getId));
    }

    public DepotFlyerSiteLog detail(DepotFlyerSiteLogIdParam depotFlyerSiteLogIdParam) {
        DepotFlyerSiteLog log = this.queryEntity(depotFlyerSiteLogIdParam.getId());
        log.setDepotGrainName(depotGrainService.getNameByDepotId(log.getDepotId()));
        log.setSitePicUrl(depotGrainInfoFileService.getFullUrl(log.getSitePicUrl()));
        log.setSavePicUrl(depotGrainInfoFileService.getFullUrl(log.getSavePicUrl()));
        return log;
    }

    public DepotFlyerSiteLog queryEntity(String id) {
        DepotFlyerSiteLog depotFlyerSiteLog = this.getById(id);
        if (ObjectUtil.isEmpty(depotFlyerSiteLog)) {
            throw new CommonException("飞行监管不存在，id值为：{}", id);
        }
        return depotFlyerSiteLog;
    }

}
