package com.fjhx.sale.flow;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fjhx.common.enums.FlowStatusEnum1;
import com.fjhx.flow.core.FlowDelegate;
import com.fjhx.sale.entity.sample.dto.SampleDto;
import com.fjhx.sale.entity.sample.po.Sample;
import com.fjhx.sale.entity.sample.po.SampleProduct;
import com.fjhx.sale.entity.sample.po.SampleProject;
import com.fjhx.sale.entity.sample.po.SampleShipment;
import com.fjhx.sale.service.sample.SampleProductService;
import com.fjhx.sale.service.sample.SampleProjectService;
import com.fjhx.sale.service.sample.SampleService;
import com.fjhx.sale.service.sample.SampleShipmentService;
import com.ruoyi.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 样品单变更流程
 */
@Component
public class SampleUpdateFlow extends FlowDelegate {

    @Autowired
    private SampleFlow sampleFlow;

    @Autowired
    private SampleService sampleService;

    @Autowired
    private SampleProductService sampleProductService;

    @Autowired
    private SampleProjectService sampleProjectService;

    @Autowired
    private SampleShipmentService sampleShipmentService;

    @Override
    public String getFlowKey() {
        return "sample_update_flow";
    }

    /**
     * 发起流程
     *
     * @param flowId     流程ID
     * @param submitData 样品单数据
     * @return
     */
    @Override
    public Long start(Long flowId, JSONObject submitData) {

        SampleDto newSample = submitData.toJavaObject(SampleDto.class);

        // 原样品单id不能为空
        Long oldSampleId = newSample.getOldSampleId();
        if (oldSampleId == null) {
            throw new ServiceException("原样品单id不能为空");
        }
        //查询原样品单
        Sample oldSample = sampleService.getById(newSample.getOldSampleId());
        if(ObjectUtil.isEmpty(oldSample)){
            throw new ServiceException("查询不到原样品单信息");
        }
        //查询旧样品单的订单产品
        List<SampleProduct> oldSampleProductList = sampleProductService.list(q -> q.eq(SampleProduct::getSampleId, oldSampleId));
        if(CollectionUtils.isEmpty(oldSampleProductList)){
            throw new ServiceException("原样品单没有产品");
        }
        Map<Long,List<SampleProduct>> oldSampleMap = oldSampleProductList.stream().collect(Collectors.groupingBy(SampleProduct::getId));
        List<SampleProduct> newSampleProductList = newSample.getSampleProductList();
        if(CollectionUtils.isEmpty(newSampleProductList)){
            throw new ServiceException("变更样品单产品不能为空");
        }
        /**
         * 赋值新的变更样品单号
         */
        String code = oldSample.getCode();
        Matcher matcher = Pattern.compile(".*\\((.*?)\\)$").matcher(code);
        int index = 2;
        if (matcher.find()) {
            index = (Integer.parseInt(matcher.group(1)) + 1);
            code = code.substring(0, code.lastIndexOf("("));
        }
        newSample.setCode(code + "(" + index + ")");
        /**
         * 计算新样品单的剩余数量
         */
        for(SampleProduct newCp:newSampleProductList){

            if(ObjectUtil.isNotEmpty(newCp.getId())){//如果新样品单产品ID不为空
                //取出旧样品单
                SampleProduct oldSampleProduct = oldSampleMap.getOrDefault(newCp.getId(),null).get(0);
                //取出旧样品单包装方式
                JSONObject oldJson = JSONObject.parseObject(oldSampleProduct.getEhsdJson());
                String oldPackMethod = oldJson.getOrDefault("packMethod",null)==null?null:oldJson.getOrDefault("packMethod",null).toString();
                //取出新样品单包装方式
                JSONObject newJson = JSONObject.parseObject(newCp.getEhsdJson());
                String newPackMethod = newJson.getOrDefault("packMethod",null)==null?null:oldJson.getOrDefault("packMethod",null).toString();
                /**
                 * 商品英文名、尺寸、包装方式、数量 没有变更---取原本的剩余数量
                 */
                if(oldSampleProduct.getQuantity().compareTo(newCp.getQuantity())==0
                        && StringUtils.equals(oldSampleProduct.getProductName(), newCp.getProductName())
                        && StringUtils.equals(oldSampleProduct.getProductModel(),newCp.getProductModel())
                        && StringUtils.equals(oldPackMethod,newPackMethod)){
                    //取出旧的剩余数量
                    newCp.setExpendQuantity(oldSampleProduct.getExpendQuantity());
                }
            }
        }
        return sampleFlow.start(newSample);
    }

    /**
     * 结束流程
     *
     * @param flowId     流程ID
     * @param businessId 业务ID
     * @param submitData 数据
     */
    @Override
    public void end(Long flowId, Long businessId, JSONObject submitData) {
        // 通过业务ID查询样品单数据
        Sample newSample = sampleService.getById(businessId);
        if (ObjectUtils.isEmpty(newSample)) {
            throw new ServiceException("样品单不存在");
        }
        long  oldSampleId = newSample.getOldSampleId();//取出旧的样品单ID
        Sample oldSample = sampleService.getById(oldSampleId);
        if (oldSample == null) {
            throw new ServiceException("原样品单不存在");
        }
        /**
         * 处理新样品单---
         */
        newSample.setId(oldSampleId);//id赋值为旧样品单的id
        newSample.setStatus(FlowStatusEnum1.PASS.getKey());
        newSample.setApprovedDate(new Date());
        sampleService.update(newSample,Wrappers.<Sample>query().lambda().eq(Sample::getId,businessId));
        //修改样品单产品相关数据
        sampleProductService.update(Wrappers.<SampleProduct>update().lambda().set(SampleProduct::getSampleId,oldSampleId).eq(SampleProduct::getSampleId,businessId));
        //修改样品单收费相关数据
        sampleProjectService.update(Wrappers.<SampleProject>update().lambda().set(SampleProject::getSampleId,oldSampleId).eq(SampleProject::getSampleId,businessId));
        //修改样品单出货相关数据
        sampleShipmentService.update(Wrappers.<SampleShipment>update().lambda().set(SampleShipment::getSampleId,oldSampleId).eq(SampleShipment::getSampleId,businessId));
        /**
         * 处理旧的样品单---
         */
        oldSample.setId(businessId);
        oldSample.setStatus(FlowStatusEnum1.UPDATE.getKey());
        oldSample.setIsChange("1");
        sampleService.update(oldSample,Wrappers.<Sample>query().lambda().eq(Sample::getId,oldSampleId));
        //修改样品单产品相关数据
        sampleProductService.update(Wrappers.<SampleProduct>update().lambda().set(SampleProduct::getSampleId,businessId).eq(SampleProduct::getSampleId,oldSampleId));
        //修改样品单收费相关数据
        sampleProjectService.update(Wrappers.<SampleProject>update().lambda().set(SampleProject::getSampleId,businessId).eq(SampleProject::getSampleId,oldSampleId));
        //修改样品单出货相关数据
        sampleShipmentService.update(Wrappers.<SampleShipment>update().lambda().set(SampleShipment::getSampleId,businessId).eq(SampleShipment::getSampleId,oldSampleId));
    }
}
