package com.fjhx.jxst.flow;

import com.alibaba.fastjson.JSONObject;
import com.fjhx.flow.core.FlowDelegate;
import com.fjhx.jxst.entity.sales.dto.SalesContractDto;
import com.fjhx.jxst.entity.sales.po.SalesContractDetails;
import com.fjhx.jxst.service.sales.SalesContractDetailsService;
import com.fjhx.jxst.service.sales.SalesContractService;
import com.fjhx.mes.entity.work.dto.WorkOrderDto;
import com.fjhx.mes.service.work.WorkOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SalesContractFlow extends FlowDelegate {

    @Autowired
    private SalesContractService salesContractService;
    @Autowired
    private SalesContractDetailsService salesContractDetailsService;
    @Autowired
    private WorkOrderService workOrderService;
    @Override
    public String getFlowKey() {
        return "jxst_sales_contract_flow";
    }

    @Override
    public Long start(Long flowId, JSONObject submitData) {
        SalesContractDto salesContractDto = submitData.toJavaObject(SalesContractDto.class);
        salesContractDto.setFlowId(flowId);
        salesContractDto.setFlowKey(getFlowKey());
        salesContractService.add(salesContractDto);
        return salesContractDto.getId();
    }

    @Override
    public void end(Long flowId, Long businessId, JSONObject submitData) {
        //按产品往“工单管理”中插入对应的工单数据
        List<SalesContractDetails> salesContractDetailsList = salesContractDetailsService.list(q -> q.eq(SalesContractDetails::getSalesContractId, businessId));
        for (SalesContractDetails salesContractDetails : salesContractDetailsList) {
            WorkOrderDto workOrder = new WorkOrderDto();
            workOrder.setSourceId(businessId);
            workOrder.setSource("sales_contract");//销售合同
            workOrder.setProductId(salesContractDetails.getProductId());
            workOrder.setQuantity(salesContractDetails.getQuantity());
            workOrder.setIsCustomized(salesContractDetails.getIsCustomized());
            //添加工单
            workOrderService.add(workOrder);
        }
    }

}
