/*
 * 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 com.unis.intelligentManagement.modular.tLqData.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.common.pojo.CommonResult;
import com.unis.intelligentManagement.modular.station.entity.TStation;
import com.unis.intelligentManagement.modular.station.mapper.TStationMapper;
import com.unis.intelligentManagement.modular.tLqData.param.*;
import com.unis.intelligentManagement.modular.tLqData.vo.CrkywVO;
import com.unis.mobileInfo.modular.qcqualityinspection.entity.BusinessQcQualityInspection;
import com.unis.safeStorage.modular.ssFireWarn.entity.SsFireWarn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.unis.common.enums.CommonSortOrderEnum;
import com.unis.common.exception.CommonException;
import com.unis.common.page.CommonPageRequest;
import com.unis.intelligentManagement.modular.tLqData.entity.TLqData;
import com.unis.intelligentManagement.modular.tLqData.mapper.TLqDataMapper;
import com.unis.intelligentManagement.modular.tLqData.service.TLqDataService;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * 多功能粮情-主表Service接口实现类
 *
 * @author hjc
 * @date 2024/06/07 10:18
 **/
@Service
public class TLqDataServiceImpl extends ServiceImpl<TLqDataMapper, TLqData> implements TLqDataService {

    @Resource
    private TStationMapper tStationMapper;

    @Resource
    private RestTemplate restTemplate;

    @Override
    public Page<TLqData> page(TLqDataPageParam tLqDataPageParam) {
        QueryWrapper<TLqData> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(TLqData::getOrgId, tLqDataPageParam.getOrgId());
        if (StringUtils.isNotEmpty(tLqDataPageParam.getFoodVarietyName())) {
            queryWrapper.lambda().like(TLqData::getFoodVarietyName, tLqDataPageParam.getFoodVarietyName());
        }
        if (StringUtils.isNotEmpty(tLqDataPageParam.getStorehouseName())) {
            queryWrapper.lambda().like(TLqData::getStorehouseName, tLqDataPageParam.getStorehouseName());
        }
        if (ObjectUtil.isNotEmpty(tLqDataPageParam.getGatherTime())) {
            Date gatherTime = tLqDataPageParam.getGatherTime();
            LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(gatherTime.getTime()), ZoneId.systemDefault());
            // 通过LocalDateTime的 with方法设置某天的最小值和最大值！！
            LocalDateTime minDateTime = localDateTime.with(LocalTime.MIN);
            // 格式化日期
            Date minDate = Date.from(minDateTime.atZone(ZoneId.systemDefault()).toInstant());

            LocalDateTime maxDateTime = localDateTime.with(LocalTime.MAX);
            Date maxDate = Date.from(maxDateTime.atZone(ZoneId.systemDefault()).toInstant());
            queryWrapper.lambda().between(TLqData::getGatherTime, minDate, maxDate);
        }

        if (ObjectUtil.isAllNotEmpty(tLqDataPageParam.getSortField(), tLqDataPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(tLqDataPageParam.getSortOrder());
            queryWrapper.orderBy(true, tLqDataPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(tLqDataPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByDesc(TLqData::getCreatedate);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(TLqDataAddParam tLqDataAddParam) {
        TLqData tLqData = BeanUtil.toBean(tLqDataAddParam, TLqData.class);
        this.save(tLqData);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(TLqDataEditParam tLqDataEditParam) {
        TLqData tLqData = this.queryEntity(tLqDataEditParam.getId());
        BeanUtil.copyProperties(tLqDataEditParam, tLqData);
        this.updateById(tLqData);
    }

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

    @Override
    public TLqData detail(TLqDataIdParam tLqDataIdParam) {
        return this.queryEntity(tLqDataIdParam.getId());
    }

    @Override
    public TLqData queryEntity(String id) {
        TLqData tLqData = this.getById(id);
        if (ObjectUtil.isEmpty(tLqData)) {
            throw new CommonException("多功能粮情-主表不存在，id值为：{}", id);
        }
        return tLqData;
    }

    @Override
    public Page<TLqData> getPage(TLqDataGetPageParam tLqDataGetPageParam) {
        {
            QueryWrapper<TLqData> queryWrapper = new QueryWrapper<>();

            if (ObjectUtil.isNotEmpty(tLqDataGetPageParam.getStartJysj()) && ObjectUtil.isNotEmpty(tLqDataGetPageParam.getEndJysj())) {
                queryWrapper.lambda().between(TLqData::getGatherTime, tLqDataGetPageParam.getStartJysj(), tLqDataGetPageParam.getEndJysj());
            }
            if (StringUtils.isNotEmpty(tLqDataGetPageParam.getStorehouseName())) {
                queryWrapper.lambda().eq(TLqData::getStorehouseName, tLqDataGetPageParam.getStorehouseName());
            }
            if (StringUtils.isNotEmpty(tLqDataGetPageParam.getOrgId())) {
                queryWrapper.lambda().eq(TLqData::getOrgId, tLqDataGetPageParam.getOrgId());
            }

            if (null != tLqDataGetPageParam.getTempMax()) {
                queryWrapper.lambda().gt(TLqData::getTempMax, tLqDataGetPageParam.getTempMax());
            }
            if (null != tLqDataGetPageParam.getTempMin()) {
                queryWrapper.lambda().lt(TLqData::getTempMin, tLqDataGetPageParam.getTempMin());
            }

            if (ObjectUtil.isAllNotEmpty(tLqDataGetPageParam.getSortField(), tLqDataGetPageParam.getSortOrder())) {
                CommonSortOrderEnum.validate(tLqDataGetPageParam.getSortOrder());
                queryWrapper.orderBy(true, tLqDataGetPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                        StrUtil.toUnderlineCase(tLqDataGetPageParam.getSortField()));
            } else {
                queryWrapper.lambda().orderByDesc(TLqData::getGatherTime);
            }
            return this.page(CommonPageRequest.defaultPage(), queryWrapper);
        }
    }

    @Override
    public CommonResult sendStoreDetection(TStationSelect tStationSelect) {
        // 查询发送指令地址
        try {
            QueryWrapper<TStation> wrapper = new QueryWrapper<>();
            wrapper.eq("org_id", tStationSelect.getOrgId());
            wrapper.eq("islocal", tStationSelect.getIlqYq());
            TStation tStation = tStationMapper.selectOne(wrapper);
            if (ObjectUtils.isNotEmpty(tStation)) {
                String serviceIp = tStation.getServiceip();
                if (tStationSelect.getIlqYq().equals("0")) {
                    JSONObject object = new JSONObject();
                    object.put("cmd", "fetch_data");
                    if (StringUtils.isNotEmpty(tStationSelect.getStorehouseCode()))
                        object.put("data", tStationSelect.getStorehouseCode());
                    else
                        object.put("data", ""); // 全库检测发送空字符串
                    restTemplate.postForObject(serviceIp, object, Object.class);
                }
            }
        } catch (RestClientException e) {
            e.printStackTrace();
            return CommonResult.error("指令发送失败!");
        }
        return CommonResult.ok();
    }

    /**
     * 购销监管-粮情监管-分页
     *
     * @author hjc
     * @date 2024/06/07 10:18
     */
    @Override
    public Page<TLqData> purchaseAndSalesSupervisionPage(PurchaseAndSalesTLqDataPageParam pageParam) {
        QueryWrapper<TLqData> queryWrapper = new QueryWrapper<>();
        //展示不符合的数据
        queryWrapper.lambda().eq(TLqData::getIsAccordModel,0);
        if (StringUtils.isNotEmpty(pageParam.getOrgName())) {
            queryWrapper.lambda().like(TLqData::getOrgName, pageParam.getOrgName());
        }
        if (ObjectUtil.isAllNotEmpty(pageParam.getSortField(), pageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(pageParam.getSortOrder());
            queryWrapper.orderBy(true, pageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(pageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByDesc(TLqData::getCreatedate);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }
}
