/*
 * 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.grainReserves.modular.gopsPlan.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.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.basic.info.modular.mq.dto.jkEnum;
import com.unis.basic.info.modular.mq.pub.RecPublishService;
import com.unis.common.util.OrderNumberUtil;
import com.unis.grainReserves.modular.gopsPlan.param.*;
import com.unis.grainReserves.modular.gopsPlanBuy.entity.GopsPlanBuy;
import com.unis.grainReserves.modular.gopsPlanBuy.mapper.GopsPlanBuyMapper;
import com.unis.grainReserves.modular.gopsPlanSale.entity.GopsPlanSale;
import com.unis.grainReserves.modular.gopsPlanSale.mapper.GopsPlanSaleMapper;
import io.jsonwebtoken.lang.Collections;
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.grainReserves.modular.gopsPlan.entity.GopsPlan;
import com.unis.grainReserves.modular.gopsPlan.mapper.GopsPlanMapper;
import com.unis.grainReserves.modular.gopsPlan.service.GopsPlanService;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 购销计划Service接口实现类
 *
 * @author QSHan
 * @date 2024/05/18 17:25
 **/
@Service
@SuppressWarnings("all")
public class GopsPlanServiceImpl extends ServiceImpl<GopsPlanMapper, GopsPlan> implements GopsPlanService {
    @Resource
    private GopsPlanMapper gopsPlanMapper;
    @Resource
    private GopsPlanSaleMapper planSaleMapper;
    @Resource
    private GopsPlanBuyMapper planBuyMapper;

    @Resource
    private RecPublishService recPublishService;

    @Override
    public Page<GopsPlan> page(GopsPlanPageParam gopsPlanPageParam) {
        QueryWrapper<GopsPlan> queryWrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(gopsPlanPageParam.getOrgName())) {
            queryWrapper.apply("oi.org_name LIKE CONCAT('%', '" + gopsPlanPageParam.getOrgName() + "', '%')");
        }
        queryWrapper.lambda().orderByDesc(GopsPlan::getId);
        return gopsPlanMapper.pageList(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(GopsPlanAddParam gopsPlanAddParam) {
        GopsPlan gopsPlan = BeanUtil.toBean(gopsPlanAddParam, GopsPlan.class);
        // 生成计划单号
        gopsPlan.setPlanOrderNo(OrderNumberUtil.frontData("JH", 4, this.getLastPlanOrderNo()));
        this.save(gopsPlan);
        // 保存子表 计划类型 1:销售计划;2:收购计划
        if (1 == gopsPlan.getPlanType()) {
            List<GopsPlanSale> saleList = gopsPlanAddParam.getPlanSale();
            if (!Collections.isEmpty(saleList)) {
                saleList.forEach(sale -> {
                    Date date = new Date();
                    sale.setCreateTime(date);
                    sale.setUpdateTime(date);
                    sale.setGopsPlanId(gopsPlan.getId());
                    planSaleMapper.insert(sale);
                });
            }
        } else if (2 == gopsPlan.getPlanType()) {
            List<GopsPlanBuy> buyList = gopsPlanAddParam.getPlanBuy();
            if (!Collections.isEmpty(buyList)) {
                buyList.forEach(buy -> {
                    Date date = new Date();
                    buy.setCreateTime(date);
                    buy.setUpdateTime(date);
                    buy.setGopsPlanId(gopsPlan.getId());
                    planBuyMapper.insert(buy);
                });
            }
        }

        /**
         * 国家局上传
         */
        //操作标志 、表名、业务id、单位id
        recPublishService.sendMessage("i", jkEnum.cbjh.getTableName(),gopsPlan.getId()+"",Integer.valueOf(0));
    }

    // 获取本机构最后一个单号顺序号
    private synchronized int getLastPlanOrderNo() {
        String lastNo = gopsPlanMapper.getLastPlanOrderNo();
        int num = 1;
        if (StringUtils.isEmpty(lastNo)) {
            return num;
        } else {
            String substring = lastNo.substring(lastNo.length() - 4);
            int i = Integer.parseInt(substring);
            if (i < 9999)
                num += i;
            return num;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(GopsPlanEditParam gopsPlanEditParam) {
        GopsPlan gopsPlan = this.queryEntity(gopsPlanEditParam.getId());
        BeanUtil.copyProperties(gopsPlanEditParam, gopsPlan);
        this.updateById(gopsPlan);
        // 修改子表(计划类型 1:销售计划;2:收购计划)
        if (1 == gopsPlan.getPlanType()) {
            List<GopsPlanSale> saleList = gopsPlanEditParam.getPlanSale();
            if (!Collections.isEmpty(saleList)) {
                saleList.forEach(sale -> {
                    // 先删除在新增
                    planSaleMapper.deleteById(sale.getId());
                    Date date = new Date();
                    sale.setCreateTime(date);
                    sale.setUpdateTime(date);
                    sale.setGopsPlanId(gopsPlan.getId());
                    planSaleMapper.insert(sale);
                });
            }
        } else if (2 == gopsPlan.getPlanType()) {
            List<GopsPlanBuy> buyList = gopsPlanEditParam.getPlanBuy();
            if (!Collections.isEmpty(buyList)) {
                buyList.forEach(buy -> {
                    // 先删除在新增
                    planBuyMapper.deleteById(buy.getId());
                    Date date = new Date();
                    buy.setCreateTime(date);
                    buy.setUpdateTime(date);
                    buy.setGopsPlanId(gopsPlan.getId());
                    planBuyMapper.insert(buy);
                });
            }
        }

        /**
         * 国家局上传
         */
        //操作标志 、表名、业务id、单位id
        recPublishService.sendMessage("u", jkEnum.cbjh.getTableName(),gopsPlan.getId()+"",Integer.valueOf(0));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<GopsPlanIdParam> gopsPlanIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(gopsPlanIdParamList, GopsPlanIdParam::getId));
        // 删除子表
        gopsPlanIdParamList.forEach(params -> {
            // 修改子表(计划类型 1:销售计划;2:收购计划)
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("gops_plan_id", params.getId());
            if (1 == params.getPlanType()) {
                planSaleMapper.delete(wrapper);
            } else if (2 == params.getPlanType()) {
                planBuyMapper.delete(wrapper);
            }
        });

        /**
         * 国家局上传
         */
        //操作标志 、表名、业务id、单位id
        recPublishService.sendMessage("d", jkEnum.cbjh.getTableName(),gopsPlanIdParamList.get(0).getId()+"",Integer.valueOf(0));
    }

    @Override
    public GopsPlan detail(GopsPlanIdParam gopsPlanIdParam) {
        GopsPlan gopsPlan = this.queryEntity(gopsPlanIdParam.getId());
        // 子表(计划类型 1:销售计划;2:收购计划)
        String id = gopsPlanIdParam.getId();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("gops_plan_id", id);
        if (1 == gopsPlan.getPlanType()) {
            gopsPlan.setPlanSale(planSaleMapper.selectDetailList(wrapper));
        } else if (2 == gopsPlan.getPlanType()) {
            gopsPlan.setPlanBuy(planBuyMapper.selectList(wrapper));
        }
        return gopsPlan;
    }

    @Override
    public GopsPlan queryEntity(String id) {
        GopsPlan gopsPlan = this.getById(id);
        if (ObjectUtil.isEmpty(gopsPlan)) {
            throw new CommonException("购销计划不存在，id值为：{}", id);
        }
        return gopsPlan;
    }

    @Override
    public Map<String, Object> getListDetail(GopsPlanDetail param) {
        return gopsPlanMapper.getListDetail(param);
    }

    @Override
    public Page<List<Map<String, Object>>> getPlanRatePage(GopsPlanPageParam param) {
        QueryWrapper<GopsPlan> queryWrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(param.getOrgName())) {
            queryWrapper.apply("oi.org_name LIKE CONCAT('%', " + param.getOrgName() + ", '%')");
        }
        queryWrapper.groupBy("t1.orgId");
        return gopsPlanMapper.getPlanRatePage(new Page<>(param.getCurrent(), param.getSize()), queryWrapper);
    }

    @Override
    public List<Map<String, Object>> getEnumTreeList(Integer parentId) {
        return gopsPlanMapper.getEnumTreeList(parentId);
    }

    @Override
    public List<Map<String, Object>> getStoreHouseList(Integer orgId) {
        return gopsPlanMapper.getStoreHouseList(orgId);
    }

    @Override
    public List<Map<String, Object>> getWarehouseList(Integer storehouseId) {
        return gopsPlanMapper.getWarehouseList(storehouseId);
    }

    @Override
    public List<Map<String, Object>> getOrgIdList() {
        return gopsPlanMapper.getOrgIdList();
    }

    @Override
    public int getCollectionsToUpdate(List<GopsPlan> collections) {
        if (!CollectionUtils.isEmpty(collections)) {
            collections.forEach(plan -> {
                gopsPlanMapper.updateById(plan);
            });
            return 1;
        }
        return 0;
    }
}
