package com.fjhx.sale.flow;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.fjhx.area.utils.CustomizeAreaUtil;
import com.fjhx.common.constant.SourceConstant;
import com.fjhx.common.enums.CodingRuleEnum;
import com.fjhx.common.enums.FlowStatusEnum1;
import com.fjhx.common.service.coding.CodingRuleService;
import com.fjhx.file.utils.ObsFileUtil;
import com.fjhx.flow.core.FlowDelegate;
import com.fjhx.flow.core.FlowThreadLocalUtil;
import com.fjhx.flow.enums.FlowStatusEnum;
import com.fjhx.flow.enums.HandleTypeEnum;
import com.fjhx.sale.entity.contract.po.Contract;
import com.fjhx.sale.entity.sale.dto.SaleQuotationDto;
import com.fjhx.sale.entity.sale.po.SaleQuotation;
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.annotation.LogicIgnore;
import com.ruoyi.common.core.domain.BasePo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 样品单流程
 * @Author:caozj
 * @DATE:2023/4/3 17:38
 */
@Component
@DS(SourceConstant.SALE)
public class SampleFlow extends FlowDelegate {

    @Autowired
    private CodingRuleService codingRuleService;

    @Autowired
    private SampleService sampleService;

    @Autowired
    private SampleProductService sampleProductService;

    @Autowired
    private SampleProjectService sampleProjectService;

    @Autowired
    private SampleShipmentService sampleShipmentService;

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



    /**
     * 发起流程
     * @param flowId 流程ID
     * @param submitData 采购付款数据
     * @return
     */
    @Override
    @DSTransactional
    public Long start(Long flowId, JSONObject submitData) {
        SampleDto sample = submitData.toJavaObject(SampleDto.class);
        sample.setCode(codingRuleService.createCode(CodingRuleEnum.SAMPLE.getKey(),sample.getBuyCorporationId()));
        long id = start(sample);
        return id;
    }

    /**
     * 重新发起
     * @param flowId
     * @param businessId
     * @param flowStatus
     * @param submitData
     */
    @Override
    @LogicIgnore(tableName = {""},alias = {""})
    @Transactional(rollbackFor = Exception.class)
    public void relaunch(Long flowId, Long businessId, FlowStatusEnum flowStatus, JSONObject submitData) {
        //删除采购合同
        SampleDto sample = submitData.toJavaObject(SampleDto.class);
        if(ObjectUtils.isEmpty(sample)){
            throw new ServiceException("样品单数据不能为空");
        }
        start(sample);
    }

    /**
     * 驳回
     * @param flowId
     * @param businessId
     * @param flowStatus
     */
    @Override
    public void reject(Long flowId, Long businessId, FlowStatusEnum flowStatus) {
        if (HandleTypeEnum.REJECT.equals(FlowThreadLocalUtil.getHandleTypeEnum())) {
            sampleService.update(q -> q
                    .eq(Sample::getId, FlowThreadLocalUtil.getBusinessId())
                    .set(Sample::getStatus, 20)//20为驳回
                    .set(Sample::getUpdateTime, new Date())
                    .set(BasePo::getUpdateUser, SecurityUtils.getUserId())
            );
        }
    }

    public Long start(SampleDto sample){
        //赋值城市省份信息
        CustomizeAreaUtil.setAreaId(sample);
        sample.setBuyCityId(sample.getCityId());
        sample.setBuyCountryId(sample.getCountryId());
        sample.setBuyProvinceId(sample.getProvinceId());
//        sample.setCode(CodeEnum.SAMPLE_CODE.getCode());
        sample.setStatus(FlowStatusEnum1.UNDER_REVIEW.getKey());
        sample.setUserName(SecurityUtils.getUsername());

        sampleService.saveOrUpdate(sample);
        List<SampleProduct> sampleProductList = sample.getSampleProductList();
        if(CollectionUtils.isNotEmpty(sampleProductList)){//保存样品单产品
            for(SampleProduct c : sampleProductList){
                c.setId(IdWorker.getId());
                c.setSampleId(sample.getId());
                c.setExpendQuantity(c.getQuantity());
            }
            sampleProductService.saveOrUpdateBatch(sampleProductList);
        }
        List<SampleProject> sampleProjectList = sample.getSampleProjectList();
        if(CollectionUtils.isNotEmpty(sampleProjectList)){//保存收费项目
            for(SampleProject c : sampleProjectList){
                c.setId(IdWorker.getId());
                c.setSampleId(sample.getId());
            }
            sampleProjectService.saveOrUpdateBatch(sampleProjectList);
        }
        List<SampleShipment> sampleShipmentList = sample.getSampleShipmentList();
        if(CollectionUtils.isNotEmpty(sampleShipmentList)){//保存自定义出货
            for(SampleShipment c : sampleShipmentList){
                c.setId(IdWorker.getId());
                c.setSampleId(sample.getId());
            }
            sampleShipmentService.saveOrUpdateBatch(sampleShipmentList);
        }
        //交接单附件
        ObsFileUtil.saveFile(sample.getFileList(),sample.getId(),1);
        //包装附件
        ObsFileUtil.saveFile(sample.getPackageFileList(),sample.getId(),2);
        return sample.getId();
    }

    /**
     * 结束流程
     * @param flowId 流程ID
     * @param businessId 业务ID
     * @param submitData 数据
     */
    @Override
    public void end(Long flowId, Long businessId, JSONObject submitData) {
        SampleService sampleService = SpringUtil.getBean(SampleService.class);
        //通过业务ID查询样品单数据
        Sample sample = sampleService.getById(businessId);
        if(ObjectUtils.isEmpty(sample)){
            throw new ServiceException("样品单不存在");
        }
        //修改样品单状态为审批通过
        sample.setStatus(FlowStatusEnum1.PASS.getKey());
        sample.setApprovedDate(new Date());
        sampleService.updateById(sample);
    }


}
