/*
 * 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.circulateMonitor.modular.realTimeQueryStatistic.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.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
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.circulateMonitor.modular.realTimeQueryStatisticItem.entity.RealTimeQueryStatisticItem;
import com.unis.circulateMonitor.modular.realTimeQueryStatisticItem.mapper.RealTimeQueryStatisticItemMapper;
import com.unis.circulateMonitor.modular.realTimeQueryStatisticItem.param.RealTimeQueryStatisticItemConvertParam;
import com.unis.circulateMonitor.modular.realTimeQueryStatisticItem.service.RealTimeQueryStatisticItemService;
import com.unis.circulateMonitor.modular.utils.ParamInitUtil;
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.circulateMonitor.modular.realTimeQueryStatistic.entity.RealTimeQueryStatistic;
import com.unis.circulateMonitor.modular.realTimeQueryStatistic.mapper.RealTimeQueryStatisticMapper;
import com.unis.circulateMonitor.modular.realTimeQueryStatistic.param.RealTimeQueryStatisticAddParam;
import com.unis.circulateMonitor.modular.realTimeQueryStatistic.param.RealTimeQueryStatisticEditParam;
import com.unis.circulateMonitor.modular.realTimeQueryStatistic.param.RealTimeQueryStatisticIdParam;
import com.unis.circulateMonitor.modular.realTimeQueryStatistic.param.RealTimeQueryStatisticPageParam;
import com.unis.circulateMonitor.modular.realTimeQueryStatistic.service.RealTimeQueryStatisticService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 流通监测Service接口实现类
 *
 * @author QSHan
 * @date 2024/06/17 09:41
 **/
@Service
public class RealTimeQueryStatisticServiceImpl extends ServiceImpl<RealTimeQueryStatisticMapper, RealTimeQueryStatistic> implements RealTimeQueryStatisticService {
    @Resource
    private RealTimeQueryStatisticItemService realTimeQueryStatisticItemService;
    @Resource
    private RealTimeQueryStatisticItemMapper realTimeQueryStatisticItemMapper;

    @Override
    public Page<RealTimeQueryStatistic> page(RealTimeQueryStatisticPageParam realTimeQueryStatisticPageParam) {
        QueryWrapper<RealTimeQueryStatistic> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isAllNotEmpty(realTimeQueryStatisticPageParam.getSortField(), realTimeQueryStatisticPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(realTimeQueryStatisticPageParam.getSortOrder());
            queryWrapper.orderBy(true, realTimeQueryStatisticPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(realTimeQueryStatisticPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByDesc(RealTimeQueryStatistic::getId);
        }
        if (StringUtils.isNotEmpty(realTimeQueryStatisticPageParam.getMonitoringPointName())) {
            queryWrapper.like("monitoring_point_name", realTimeQueryStatisticPageParam.getMonitoringPointName());
        }
        // 监测地区
        if (StringUtils.isNotEmpty(realTimeQueryStatisticPageParam.getMonitoringArea())) {
            queryWrapper.like("monitoring_region_province", realTimeQueryStatisticPageParam.getMonitoringArea())
                    .or().like("monitoring_region_city", realTimeQueryStatisticPageParam.getMonitoringArea())
                    .or().like("monitoring_region_area", realTimeQueryStatisticPageParam.getMonitoringArea())
                    .or().like("monitoring_region_address", realTimeQueryStatisticPageParam.getMonitoringArea());
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(RealTimeQueryStatisticAddParam realTimeQueryStatisticAddParam) {
        RealTimeQueryStatistic realTimeQueryStatistic = BeanUtil.toBean(realTimeQueryStatisticAddParam, RealTimeQueryStatistic.class);
        this.save(realTimeQueryStatistic);
        // 保存子表数据
        List<RealTimeQueryStatisticItem> itemAddParam = this.convertParam(realTimeQueryStatisticAddParam.getItemAddParams());
//        List<RealTimeQueryStatisticItem> itemAddParam = realTimeQueryStatisticAddParam.getItemAddParam();
        if (CollectionUtils.isNotEmpty(itemAddParam)) {
            itemAddParam.forEach(item -> {
                item.setCmRealTimeQueryStatisticId(realTimeQueryStatistic.getId());
                realTimeQueryStatisticItemService.save(item);
            });
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(RealTimeQueryStatisticEditParam realTimeQueryStatisticEditParam) {
        RealTimeQueryStatistic realTimeQueryStatistic = this.queryEntity(realTimeQueryStatisticEditParam.getId());
        BeanUtil.copyProperties(realTimeQueryStatisticEditParam, realTimeQueryStatistic);
        this.updateById(realTimeQueryStatistic);
        // 修改子表数据
        List<RealTimeQueryStatisticItem> itemAddParam = this.convertParam(realTimeQueryStatisticEditParam.getItemAddParams());
//        List<RealTimeQueryStatisticItem> itemAddParam = realTimeQueryStatisticEditParam.getItemAddParam();
        // 转换获取不到子表id,先删除,在新增
        QueryWrapper<RealTimeQueryStatisticItem> wrapper = new QueryWrapper<>();
        wrapper.eq("cm_real_time_query_statistic_id", realTimeQueryStatisticEditParam.getId());
        realTimeQueryStatisticItemMapper.delete(wrapper);
        if (CollectionUtils.isNotEmpty(itemAddParam)) {
            itemAddParam.forEach(item -> {
                item.setCmRealTimeQueryStatisticId(realTimeQueryStatistic.getId());
                realTimeQueryStatisticItemService.save(item);
            });
        }
    }

    private synchronized List<RealTimeQueryStatisticItem> convertParam(RealTimeQueryStatisticItemConvertParam itemAddParams) {
        List<RealTimeQueryStatisticItem> itemList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(itemAddParams)) {
            // 小麦
            RealTimeQueryStatisticItem item1 = new RealTimeQueryStatisticItem();
            item1.setGrainVariety(1);
            item1.setPrice(itemAddParams.getXmPrice() == null ? ParamInitUtil.gitInitBigDecimal() : itemAddParams.getXmPrice());
            item1.setTradeQuantity(itemAddParams.getXmTradeQuantity() == null ? ParamInitUtil.gitInitBigDecimal() : itemAddParams.getXmTradeQuantity());
            itemList.add(item1);

            // 青稞
            RealTimeQueryStatisticItem item2 = new RealTimeQueryStatisticItem();
            item2.setGrainVariety(2);
            item2.setPrice(itemAddParams.getQkPrice() == null ? ParamInitUtil.gitInitBigDecimal() : itemAddParams.getQkPrice());
            item2.setTradeQuantity(itemAddParams.getQkTradeQuantity() == null ? ParamInitUtil.gitInitBigDecimal() : itemAddParams.getQkTradeQuantity());
            itemList.add(item2);

            // 稻谷
            RealTimeQueryStatisticItem item3 = new RealTimeQueryStatisticItem();
            item3.setGrainVariety(3);
            item3.setPrice(itemAddParams.getDgPrice() == null ? ParamInitUtil.gitInitBigDecimal() : itemAddParams.getDgPrice());
            item3.setTradeQuantity(itemAddParams.getDgTradeQuantity() == null ? ParamInitUtil.gitInitBigDecimal() : itemAddParams.getDgTradeQuantity());
            itemList.add(item3);

            // 大米
            RealTimeQueryStatisticItem item4 = new RealTimeQueryStatisticItem();
            item4.setGrainVariety(4);
            item4.setPrice(itemAddParams.getDmPrice() == null ? ParamInitUtil.gitInitBigDecimal() : itemAddParams.getDmPrice());
            item4.setTradeQuantity(itemAddParams.getDmTradeQuantity() == null ? ParamInitUtil.gitInitBigDecimal() : itemAddParams.getDmTradeQuantity());
            itemList.add(item4);

            // 白面
            RealTimeQueryStatisticItem item5 = new RealTimeQueryStatisticItem();
            item5.setGrainVariety(5);
            item5.setPrice(itemAddParams.getBmPrice() == null ? ParamInitUtil.gitInitBigDecimal() : itemAddParams.getBmPrice());
            item5.setTradeQuantity(itemAddParams.getBmTradeQuantity() == null ? ParamInitUtil.gitInitBigDecimal() : itemAddParams.getBmTradeQuantity());
            itemList.add(item5);

            // 菜籽油
            RealTimeQueryStatisticItem item6 = new RealTimeQueryStatisticItem();
            item6.setGrainVariety(6);
            item6.setPrice(itemAddParams.getCzyPrice() == null ? ParamInitUtil.gitInitBigDecimal() : itemAddParams.getCzyPrice());
            item6.setTradeQuantity(itemAddParams.getCzyTradeQuantity() == null ? ParamInitUtil.gitInitBigDecimal() : itemAddParams.getCzyTradeQuantity());
            itemList.add(item6);
        }
        return itemList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<RealTimeQueryStatisticIdParam> realTimeQueryStatisticIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(realTimeQueryStatisticIdParamList, RealTimeQueryStatisticIdParam::getId));
        // 删除子表关联数据
        if (CollectionUtils.isNotEmpty(realTimeQueryStatisticIdParamList)) {
            realTimeQueryStatisticIdParamList.forEach(item -> {
                QueryWrapper<RealTimeQueryStatisticItem> wrapper = new QueryWrapper<>();
                wrapper.eq("cm_real_time_query_statistic_id", item.getId());
                realTimeQueryStatisticItemMapper.delete(wrapper);
            });

        }
    }

    @Override
    public RealTimeQueryStatistic detail(RealTimeQueryStatisticIdParam realTimeQueryStatisticIdParam) {
        RealTimeQueryStatistic realTimeQueryStatistic = this.queryEntity(realTimeQueryStatisticIdParam.getId());
        // 查询子表数据
        RealTimeQueryStatisticItemConvertParam itemAddParams = realTimeQueryStatisticItemMapper.selectOneConvert(realTimeQueryStatisticIdParam.getId());
        if (ObjectUtil.isNotEmpty(itemAddParams)) {
            realTimeQueryStatistic.setItemAddParams(itemAddParams);
        }
        return realTimeQueryStatistic;
    }

    @Override
    public RealTimeQueryStatistic queryEntity(String id) {
        RealTimeQueryStatistic realTimeQueryStatistic = this.getById(id);
        if (ObjectUtil.isEmpty(realTimeQueryStatistic)) {
            throw new CommonException("流通监测不存在，id值为：{}", id);
        }
        return realTimeQueryStatistic;
    }
}
