package com.ximai.mes.remote.process;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ximai.mes.aspect.IExtendedProcess;
import com.ximai.mes.pro.domain.proWorkOrder.ProWorkorder;
import com.ximai.mes.pro.domain.task.ProTask;
import com.ximai.mes.pro.domain.task.ProTaskWorkunit;
import com.ximai.mes.pro.mapper.proWorkOrder.ProWorkorderMapper;
import com.ximai.mes.pro.service.task.IProTaskService;
import com.ximai.mes.remote.ErpService;
import com.ximai.mes.remote.dto.PurchasingRequisitionCreate;
import com.ximai.mes.remote.dto.PurchasingRequisitionDetailCreate;
import com.ximai.system.strategy.AutoCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class PurchasingRequisitionCreateProcess implements IExtendedProcess {

    @Autowired
    ErpService erpService;
    @Autowired
    IProTaskService taskService;
    @Autowired
    ProWorkorderMapper proWorkorderMapper;
    @Autowired
    private AutoCodeUtil autoCodeUtil;

    @Override
    public void process(Object[] args, Object returnResult) {
        ProTaskWorkunit taskWorkunit = (ProTaskWorkunit)args[0];
        ProTask task = taskService.selectProTaskByTaskId(taskWorkunit.getTaskId());
        QueryWrapper<ProWorkorder> workorderQuery = new QueryWrapper<>();
        workorderQuery.eq("t2.task_id", task.getTaskId());
        List<ProWorkorder> workorderList = proWorkorderMapper.selectProWorkorderJoinTask(workorderQuery);
        PurchasingRequisitionCreate create = new PurchasingRequisitionCreate();
        String requestCode = autoCodeUtil.genSerialCode("ERP_PURCHASING_REQUISITION","");
        if(workorderList.size()>0){
            create.setWorkorderType(workorderList.get(0).getWorkorderType());
            create.setWorkorderCode(workorderList.get(0).getWorkorderCode());
        }
        create.setRequisitionCode(requestCode);
        List<PurchasingRequisitionDetailCreate> details = new ArrayList<>();
        PurchasingRequisitionDetailCreate detailCreate = new PurchasingRequisitionDetailCreate();
        detailCreate.setQuantity(taskWorkunit.getQuantity()+"");
        detailCreate.setProcessName(task.getProcessName());
        detailCreate.setRequestDate(DateUtil.format(taskWorkunit.getScheduleEndDate(),"yyyyMMdd"));
        details.add(detailCreate);
        create.setDetails(details);
        erpService.purchasingRequisitionCreate(create);
    }
}
