/*
 * 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.bizorder.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
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 com.fhs.trans.service.impl.TransService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.modular.customer.entity.BizCustomer;
import vip.xiaonuo.biz.modular.customer.service.BizCustomerService;
import vip.xiaonuo.biz.modular.bizorder.param.*;
import vip.xiaonuo.biz.modular.utils.CommonExportUtil;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.bizorder.entity.BizOrder;
import vip.xiaonuo.biz.modular.bizorder.mapper.BizOrderMapper;
import vip.xiaonuo.biz.modular.bizorder.service.BizOrderService;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

/**
 * 订单管理Service接口实现类
 *
 * @author fanzherong
 * @date  2025/03/21 17:16
 **/
@Service
public class BizOrderServiceImpl extends ServiceImpl<BizOrderMapper, BizOrder> implements BizOrderService {

    @Resource
    private BizCustomerService bizCustomerService;

    @Resource
    private TransService transService;

    @Override
    public Page<BizOrder> page(BizOrderPageParam bizOrderPageParam) {
        QueryWrapper<BizOrder> queryWrapper = getQueryWrapper(bizOrderPageParam);
        return this.getBaseMapper().getPage(CommonPageRequest.defaultPage(), queryWrapper);
    }

    public QueryWrapper<BizOrder> getQueryWrapper(BizOrderPageParam bizOrderPageParam){
        QueryWrapper<BizOrder> queryWrapper = new QueryWrapper<BizOrder>().checkSqlInjection();
        //订单名称查询
        if(ObjectUtil.isNotEmpty(bizOrderPageParam.getOrderName())){
            queryWrapper.like("bo.order_name",bizOrderPageParam.getOrderName());
        }
        //订单编号查询
        if(ObjectUtil.isNotEmpty(bizOrderPageParam.getOrderNumber())){
            queryWrapper.like("bo.order_number",bizOrderPageParam.getOrderNumber());
        }
        //客户名称查询
        if(ObjectUtil.isNotEmpty(bizOrderPageParam.getCustomerName())){
            queryWrapper.like("bc.customer_name",bizOrderPageParam.getCustomerName());
        }
        //货品名称查询
        if(ObjectUtil.isNotEmpty(bizOrderPageParam.getGoodsName())){
            queryWrapper.like("bg.`NAME`",bizOrderPageParam.getGoodsName());
        }
        //状态查询
        if(ObjectUtil.isNotEmpty(bizOrderPageParam.getOrderStatus())){
            queryWrapper.eq("bo.order_status",bizOrderPageParam.getOrderStatus());
        }
        //订单来源
        if(ObjectUtil.isNotEmpty(bizOrderPageParam.getOrderSource())){
            queryWrapper.eq("bo.order_source",bizOrderPageParam.getOrderSource());
        }
        queryWrapper.eq("bo.delete_flag","NOT_DELETE");
        queryWrapper.orderByDesc("bo.create_time");
        return queryWrapper;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizOrderAddParam bizOrderAddParam) {
        //判断订单编号是否存在
        long count = this.count(new QueryWrapper<BizOrder>().lambda().eq(BizOrder::getOrderNumber, bizOrderAddParam.getOrderNumber()));
        if(count>0){
            throw new CommonException("订单编号已存在！");
        }
        BizOrder bizOrder = BeanUtil.toBean(bizOrderAddParam, BizOrder.class);
        //数据库默认存KG，页面展示用吨
        bizOrder.setOrderWeight(bizOrder.getOrderWeight().multiply(new BigDecimal(1000)));
        //来源，手动新增
        bizOrder.setOrderSource("2");
        this.save(bizOrder);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizOrderEditParam bizOrderEditParam) {
        BizOrder bizOrder = this.queryEntity(bizOrderEditParam.getId());
        if(!StringUtils.equals(bizOrder.getOrderNumber(),bizOrderEditParam.getOrderNumber())){
            //订单编号修改，判断订单编号是否存在
            long count = this.count(new QueryWrapper<BizOrder>().lambda().eq(BizOrder::getOrderNumber, bizOrderEditParam.getOrderNumber()));
            if(count>0){
                throw new CommonException("订单编号已存在！");
            }
        }
        BeanUtil.copyProperties(bizOrderEditParam, bizOrder);
        //设置订单重量
        if(bizOrder.getOrderWeight().compareTo(bizOrderEditParam.getOrderWeight()) != 0){
            bizOrder.setOrderWeight(bizOrderEditParam.getOrderWeight().multiply(new BigDecimal(1000)));
        }else{
            bizOrder.setOrderWeight(bizOrder.getOrderWeight().multiply(new BigDecimal(1000)));
        }
        this.updateById(bizOrder);
    }

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

    @Override
    public BizOrder detail(BizOrderIdParam bizOrderIdParam) {
        return this.queryEntity(bizOrderIdParam.getId());
    }

    @Override
    public BizOrder queryEntity(String id) {
        BizOrder bizOrder = this.getById(id);
        if(ObjectUtil.isEmpty(bizOrder)) {
            throw new CommonException("订单管理不存在，id值为：{}", id);
        }
        return bizOrder;
    }

    @Override
    public List<BizCustomer> getCustomerById(BizOrderIdParam bizOrderIdParam) {
        if(ObjectUtil.isNotEmpty(bizOrderIdParam.getId())){
            List<BizCustomer> customerList = bizCustomerService.list(new QueryWrapper<BizCustomer>().lambda().eq(BizCustomer::getId, bizOrderIdParam.getId()));
            return customerList;
        }
        return null;
    }

    @Override
    public void bindCustomerId(BizOrderEditParam bizOrderEditParam) {
        BizOrder bizOrder = this.queryEntity(bizOrderEditParam.getId());
        if(ObjectUtil.isNotEmpty(bizOrderEditParam.getCustomerIdList())){
            bizOrder.setCustomerId(bizOrderEditParam.getCustomerIdList().get(0));
        }
        this.updateById(bizOrder);
    }

    @Override
    public void exportRecord(BizOrderPageParam bizOrderPageParam, HttpServletResponse response) throws IOException {
        QueryWrapper<BizOrder> queryWrapper = getQueryWrapper(bizOrderPageParam);
        List<BizOrder> orderList = this.getBaseMapper().getPage(queryWrapper);
        String fileName = "订单报表.xlsx";
        List<BizOrderExportResult> list = Lists.newArrayList();
        transService.transBatch(orderList);
        for(BizOrder bizOrder : orderList){
            BizOrderExportResult bizOrderExportResult = new BizOrderExportResult();
            BeanUtil.copyProperties(bizOrder, bizOrderExportResult);
            bizOrderExportResult.setOrderSourceName((String) bizOrder.getTransMap().get("orderSourceName"));
            bizOrderExportResult.setOrderStatusName((String) bizOrder.getTransMap().get("orderStatusName"));
            list.add(bizOrderExportResult);
        }
        CommonExportUtil.export(fileName, BizOrderExportResult.class,list,response,"订单报表");
    }

    @Override
    public void endOrder(BizOrderIdParam bizOrderIdParam) {
        BizOrder bizOrder = this.queryEntity(bizOrderIdParam.getId());
        bizOrder.setOrderStatus("2");
        this.updateById(bizOrder);
    }

    @Override
    public List<BizOrder> getList() {
        return this.list();
    }
}
