package com.fjhx.sale.flow;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fjhx.common.constant.SourceConstant;
import com.fjhx.common.enums.CodingRuleEnum;
import com.fjhx.common.service.coding.CodingRuleService;
import com.fjhx.flow.core.FlowDelegate;
import com.fjhx.flow.core.FlowThreadLocalUtil;
import com.fjhx.purchase.entity.purchase.enums.PurchaseDataResourceEnum;
import com.fjhx.purchase.entity.purchase.enums.PurchaseDetailStatusEnum;
import com.fjhx.purchase.entity.purchase.enums.PurchaseStatusEnum;
import com.fjhx.purchase.entity.purchase.po.Purchase;
import com.fjhx.purchase.entity.purchase.po.PurchaseDetail;
import com.fjhx.purchase.entity.subscribe.enums.SubscribeDetailStatusEnum;
import com.fjhx.purchase.entity.subscribe.po.Subscribe;
import com.fjhx.purchase.entity.subscribe.po.SubscribeDetail;
import com.fjhx.purchase.service.purchase.PurchaseDetailService;
import com.fjhx.purchase.service.purchase.PurchaseService;
import com.fjhx.purchase.service.subscribe.SubscribeDetailService;
import com.fjhx.purchase.service.subscribe.SubscribeService;
import com.fjhx.sale.entity.contract.po.ContractProduct;
import com.fjhx.sale.service.contract.ContractProductService;
import com.obs.services.internal.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 采购流程
 *
 * @Author:caozj
 * @DATE:2023/4/3 17:38
 */
@Component
public class PurchaseFlowByWdly extends FlowDelegate {

    @Autowired
    private PurchaseService purchaseService;

    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private SubscribeService subscribeService;
    @Autowired
    private SubscribeDetailService subscribeDetailService;
    @Autowired
    private ContractProductService contractProductService;
    @Autowired
    private CodingRuleService codingRuleService;

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

    /**
     * 发起流程
     *
     * @param flowId     流程ID
     * @param submitData 采购数据
     * @return
     */
    @Override
    public Long start(Long flowId, JSONObject submitData) {
        DynamicDataSourceContextHolder.push(SourceConstant.PURCHASE);
        try {
            Purchase purchase = submitData.toJavaObject(Purchase.class);
//            purchase.setCode(CodeEnum.PURCHASE.getCode());
            purchase.setCode(codingRuleService.createCode(CodingRuleEnum.PURCHASE.getKey(), null));
            purchase.setPurchaseStatus(PurchaseStatusEnum.UNDER_REVIEW.getKey());
            purchase.setProcessInstanceId("wdly_purchase");
            purchase.setFlowId(flowId);
            purchaseService.save(purchase);
            List<PurchaseDetail> purchaseDetailList = purchase.getPurchaseDetailList();
            if (CollectionUtils.isNotEmpty(purchaseDetailList)) {
                for (PurchaseDetail s : purchaseDetailList) {
                    s.setPurchaseId(purchase.getId());
                    //计算采购数量是否大于申购数量
                    List<PurchaseDetail> purchaseDetailList1 = purchaseDetailService.list(q -> q.eq(PurchaseDetail::getSubscribeDetailId,
                            s.getSubscribeDetailId()));
                    //求和
                    BigDecimal purchaseCount = purchaseDetailList1.stream()
                            .map(PurchaseDetail::getCount)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    //计算历史采购数量+本次采购数量之和
                    BigDecimal count = purchaseCount.add(s.getCount());
                    //判断采购数量是否大于申购数量
                    SubscribeDetail subscribeDetail = subscribeDetailService.getById(s.getSubscribeDetailId());
                    if (count.compareTo(subscribeDetail.getCount()) > 0) {
                        throw new ServiceException("采购数量不能大于申购数量");
                    }
                }
                purchaseDetailService.saveBatch(purchaseDetailList);
            }
            //根据申购明细id去申购单获取仓库id 名称
            if (ObjectUtils.isEmpty(purchaseDetailList)) {
                return purchase.getId();
            }
            PurchaseDetail purchaseDetail = purchaseDetailList.get(0);
            SubscribeDetail subscribeDetail = subscribeDetailService.getById(purchaseDetail.getSubscribeDetailId());
            if (ObjectUtils.isEmpty(subscribeDetail)) {
                return purchase.getId();
            }
            Subscribe subscribe = subscribeService.getById(subscribeDetail.getSubscribeId());
            if (ObjectUtils.isEmpty(subscribe)) {
                return purchase.getId();
            }
            String victoriatouristJson = subscribe.getVictoriatouristJson();
            if (ObjectUtils.isNotEmpty(victoriatouristJson)) {
                JSONObject json = JSONObject.parseObject(victoriatouristJson);
                Long receiptWarehouseId = json.getLong("receiptWarehouseId");

                String victoriatouristJson1 = purchase.getVictoriatouristJson();
                JSONObject json1 = JSONObject.parseObject(victoriatouristJson1);
                json1.put("receiptWarehouseId", receiptWarehouseId);
                purchase.setVictoriatouristJson(com.alibaba.fastjson2.JSONObject.toJSONString(json1, JSONWriter.Feature.WriteLongAsString));
                purchaseService.updateById(purchase);
            }
            return purchase.getId();
        } finally {
            DynamicDataSourceContextHolder.poll();
        }
    }

    /**
     * 结束流程
     *
     * @param flowId     流程ID
     * @param businessId 业务ID
     * @param submitData 数据
     */
    @Override
    public void end(Long flowId, Long businessId, JSONObject submitData) {
        //修改申购明细状态
        List<PurchaseDetail> purchaseDetailList = purchaseDetailService.list(Wrappers.<PurchaseDetail>query().lambda().eq(PurchaseDetail::getPurchaseId, businessId));
        Map<Long, PurchaseDetail> purchaseDetailMap = purchaseDetailList.stream().collect(Collectors.toMap(PurchaseDetail::getSubscribeDetailId, Function.identity()));
        List<Long> subscribeDetailIds = purchaseDetailList.stream().map(PurchaseDetail::getSubscribeDetailId).collect(Collectors.toList());
        List<SubscribeDetail> subscribeDetails = subscribeDetailService.listByIds(subscribeDetailIds);
        for (SubscribeDetail subscribeDetail : subscribeDetails) {
            //获取申购明细下的所有采购记录 计算已采购数
            List<PurchaseDetail> purchaseDetails = purchaseDetailService.list(q -> q.eq(PurchaseDetail::getSubscribeDetailId,
                    subscribeDetail.getId()).eq(PurchaseDetail::getBussinessId, subscribeDetail.getBussinessId()));
            BigDecimal count = purchaseDetails.stream()
                    .map(PurchaseDetail::getCount)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
//            PurchaseDetail purchaseDetail = purchaseDetailMap.get(subscribeDetail.getId());
            if (count.compareTo(subscribeDetail.getCount()) >= 0) {
                //修改为已采购
                subscribeDetail.setStatus(SubscribeDetailStatusEnum.PURCHASED.getKey());
            } else {
                //修改为部分采购
                subscribeDetail.setStatus(SubscribeDetailStatusEnum.LITT_PAID_AMOUNT.getKey());
            }
        }
        subscribeDetailService.updateBatchById(subscribeDetails);
//        purchaseFlow.end(flowId,businessId,submitData);

        //通过业务ID查询采购数据
        Purchase purchase = purchaseService.getById(businessId);
        if (ObjectUtils.isEmpty(purchase)) {
            throw new ServiceException("采购单不存在");
        }
        //查询采购产品
//        List<PurchaseDetail> purchaseDetailList = purchaseDetailService.list(Wrappers.<PurchaseDetail>query().lambda().eq(PurchaseDetail::getPurchaseId,businessId));
        List<ContractProduct> upContractProduct = new ArrayList<>();
        for (PurchaseDetail p : purchaseDetailList) {
            if (ObjectUtils.isNotEmpty(p.getDataResourceId()) &&
                    p.getDataResource() == PurchaseDataResourceEnum.DATA_RESOURCE_1.getKey()) {//如果采购的是外销合同
                ContractProduct contractProduct = contractProductService.getById(p.getDataResourceId());
                BigDecimal expendQuantity = contractProduct.getExpendQuantity().subtract(p.getCount());
                if (expendQuantity.compareTo(BigDecimal.ZERO) < 1) {//小于0不让继续执行
                    throw new ServiceException("采购数量不得大于外销合同数量");
                }
                contractProduct.setExpendQuantity(expendQuantity);
                upContractProduct.add(contractProduct);
            }
        }
        if (CollectionUtils.isNotEmpty(upContractProduct)) {//扣减销售合同数量
            contractProductService.updateBatchById(upContractProduct);
        }
        //修改采购状态为审批通过
        purchase.setPurchaseStatus(PurchaseStatusEnum.PASS.getKey());
        purchase.setApprovedDate(new Date());
        purchaseService.updateById(purchase);
        //修改采购明细为待采购
        PurchaseDetail detail = new PurchaseDetail();
        detail.setStatus(PurchaseDetailStatusEnum.PASS.getKey());
        purchaseDetailService.update(detail, Wrappers.<PurchaseDetail>query()
                .lambda().eq(PurchaseDetail::getPurchaseId, purchase.getId()));
    }

    /**
     * 重新发起编辑方法
     */
    public void reStart() {
        DynamicDataSourceContextHolder.push(SourceConstant.PURCHASE);
        try {
            //获取提交的数据
            JSONObject submitData = FlowThreadLocalUtil.getCurrentData();
            //修改采购信息
            Purchase purchase = submitData.toJavaObject(Purchase.class);
            purchase.setPurchaseStatus(PurchaseStatusEnum.UNDER_REVIEW.getKey());
            purchaseService.updateById(purchase);
            //修改采购明细
            List<PurchaseDetail> purchaseDetailList = purchase.getPurchaseDetailList();
            if (CollectionUtils.isNotEmpty(purchaseDetailList)) {
                for (PurchaseDetail s : purchaseDetailList) {
                    s.setPurchaseId(purchase.getId());
                    //计算采购数量是否大于申购数量
                    List<PurchaseDetail> purchaseDetailList1 = purchaseDetailService.list(q -> q.eq(PurchaseDetail::getSubscribeDetailId,
                            s.getSubscribeDetailId()));
                    //求和
                    BigDecimal purchaseCount = purchaseDetailList1.stream()
                            .map(PurchaseDetail::getCount)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    //计算历史采购数量+本次采购数量之和
                    BigDecimal count = purchaseCount.add(s.getCount());
                    //判断采购数量是否大于申购数量
                    SubscribeDetail subscribeDetail = subscribeDetailService.getById(s.getSubscribeDetailId());
                    if (count.compareTo(subscribeDetail.getCount()) > 0) {
                        throw new ServiceException("采购数量不能大于申购数量");
                    }
                }
                //更新明细列表信息
                purchaseDetailService.editLinked(purchaseDetailList, PurchaseDetail::getPurchaseId, purchase.getId());
            }
            //根据申购明细id去申购单获取仓库id 名称
            if (ObjectUtils.isNotEmpty(purchaseDetailList)) {
                PurchaseDetail purchaseDetail = purchaseDetailList.get(0);
                SubscribeDetail subscribeDetail = subscribeDetailService.getById(purchaseDetail.getSubscribeDetailId());
                if (ObjectUtils.isEmpty(subscribeDetail)) {
                    throw new ServiceException("查询不到申购明细信息");
                }
                Subscribe subscribe = subscribeService.getById(subscribeDetail.getSubscribeId());
                if (ObjectUtils.isEmpty(subscribe)) {
                    throw new ServiceException("查询不到申购信息");
                }
                String victoriatouristJson = subscribe.getVictoriatouristJson();
                if (ObjectUtils.isNotEmpty(victoriatouristJson)) {
                    JSONObject json = JSONObject.parseObject(victoriatouristJson);
                    Long receiptWarehouseId = json.getLong("receiptWarehouseId");

                    String victoriatouristJson1 = purchase.getVictoriatouristJson();
                    JSONObject json1 = JSONObject.parseObject(victoriatouristJson1);
                    json1.put("receiptWarehouseId", receiptWarehouseId);
                    purchase.setVictoriatouristJson(com.alibaba.fastjson2.JSONObject.toJSONString(json1, JSONWriter.Feature.WriteLongAsString));
                    purchaseService.updateById(purchase);
                }
            }
        } finally {
            DynamicDataSourceContextHolder.poll();
        }
    }

}
