package com.junmp.jyzb.service.impl;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.junmp.junmpProcess.dto.HandleDataDTO;
import com.junmp.jyzb.api.bean.query.SearchItemReq;
import com.junmp.jyzb.api.bean.req.UpdateBusFormReq;
import com.junmp.jyzb.entity.BusForm;
import com.junmp.jyzb.entity.InventorySummary;
import com.junmp.jyzb.entity.OrderMain;
import com.junmp.jyzb.entity.Reassignment;
import com.junmp.jyzb.mapper.InventorySummaryMapper;
import com.junmp.jyzb.service.BusFormService;
import com.junmp.jyzb.service.OrderMainService;
import com.junmp.jyzb.service.OrderCommonService;
import com.junmp.jyzb.service.ReassignmentService;
import com.junmp.jyzb.utils.BusinessUtil;
import com.junmp.v2.common.util.BeanPlusUtil;
import com.junmp.v2.sys.user.service.SysUserService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.junmp.junmpProcess.common.CommonConstants.BUSSINESS_TYPE;
import static com.junmp.junmpProcess.common.CommonConstants.TYPE_ORDER;

@Service
public class OrderCommonServiceImpl implements OrderCommonService {

    @Resource
    private SysUserService sysUserService;

    @Resource
    protected TaskService taskService;

    @Resource
    private OrderMainService orderMainService;

    @Resource
    private BusFormService busFormService;

    @Resource
    private ReassignmentService reassignmentService;

    @Resource
    private InventorySummaryMapper inventorySummaryMapper;

    @Resource
    private RuntimeService runtimeService;

    @Override
    public boolean changeOrderExamineState(HandleDataDTO handleDataDTO) {
        String taskId = handleDataDTO.getTaskId();
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().includeProcessVariables().processInstanceId(task.getProcessInstanceId()).singleResult();

        //更新单子的状态（改为已驳回，如果单子是报废，那么该单子的审核中的报废数量应该进行减少）
//        Map<String, Object> processVariables = task.getProcessVariables();
        //单据类型（出入库单、调岗单、业务单、盘库单）
//        String orderType = MapUtil.getStr(processVariables, ORDER_TYPE);
        String orderType= MapUtil.getStr(processInstance.getProcessVariables(),TYPE_ORDER);
        //单据业务类型（采购啥的......）
        String bussinessType= MapUtil.getStr(processInstance.getProcessVariables(),BUSSINESS_TYPE);
//        String bussinessType = MapUtil.getStr(processVariables, BUSSINESS_TYPE);
        String processInstanceId = task.getProcessInstanceId();
        boolean result=true;
        switch (orderType){
            case "workOrder":
            case "quickOrder":
                result = orderMainService.update(new LambdaUpdateWrapper<OrderMain>()
                        .eq(OrderMain::getProcessId, processInstanceId)
                        .set(OrderMain::getExamineState, "refuse"));
                break;
            case "bussinessOrder":
                if (bussinessType.equals("remove")){
                    BusForm one = busFormService.getOne(new LambdaQueryWrapper<BusForm>()
                            .eq(BusForm::getProcessId, processInstanceId));
                    UpdateBusFormReq updateBusFormReq = new UpdateBusFormReq();
                    BeanPlusUtil.copyProperties(one,updateBusFormReq);
                    busFormService.addOrRevokeAgentBrokenNum(updateBusFormReq,false);
                }
                result = busFormService.update(new LambdaUpdateWrapper<BusForm>()
                        .eq(BusForm::getProcessId, processInstanceId)
                        .set(BusForm::getExamineState, "refuse"));

                break;
            case "reassignment":
                reassignmentService.update(new LambdaUpdateWrapper<Reassignment>()
                        .eq(Reassignment::getProcessId,processInstanceId)
                        .set(Reassignment::getExamineState,"refuse"));
                break;
            case "stocktakeOrder":
                //还没写
                System.out.println("orderType = " + orderType);
                break;
        }

        return result;
    }

    @Override
    public String CheckSummaryStockNum(SearchItemReq req) {
        List<SearchItemReq> searchItemReqsList = JSON.parseArray(req.getJsonData(), SearchItemReq.class);
        List<Object[]> searchItem=new ArrayList<>();
        for (SearchItemReq itemReq:searchItemReqsList) {
            Object[] item=new Object[]{req.getOrgId(),itemReq.getLocationId(),itemReq.getTypeId(),itemReq.getSizeId(), itemReq.getPrice()};
            searchItem.add(item);
        }
        List<InventorySummary> inventorySummaryList = inventorySummaryMapper.selectSumByItems(searchItem);
        String reurnString="";
        for (SearchItemReq req1:searchItemReqsList) {
            boolean f=false;
            for (InventorySummary is:inventorySummaryList) {
                if (req1.getLocationId().equals(is.getLocationId()) && req1.getTypeId().equals(is.getTypeId())
                        && req1.getSizeId().equals(is.getSizeId()) && req1.getPrice().compareTo(is.getUnitPrice())==0){
                    //判断数量是否满足库存数量，如果不满足或者库存中找不到该装备，则直接提示库存不足
                    f=true;
                    if (is.getStockNumber()-is.getBrokenNumber()<req1.getPlanNum()){
                        reurnString=reurnString+"装备"+req1.getTypeName()+",号型为"+req1.getSizeName()+"的库存数量不足;";
                    }
                }
            }
            if (!f){
                reurnString=reurnString+"装备"+req1.getTypeName()+",号型为"+req1.getSizeName()+"的库存数量不足;";
            }
        }
        if (reurnString.trim().isEmpty()){
            return "库存足够";
        }else {
            return reurnString;
        }
    }
}
