package com.ximai.mes.restful;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ximai.common.core.controller.BaseController;
import com.ximai.common.core.domain.AjaxResult;
import com.ximai.common.core.domain.SapAjaxResult;
import com.ximai.common.core.page.TableDataInfo;
import com.ximai.common.utils.data.ExceptionUtil;
import com.ximai.common.utils.data.StringUtils;
import com.ximai.framework.security.BasicAuth;
import com.ximai.mes.constant.WorkorderConst;
import com.ximai.mes.constant.WorkorderSAPStatusEnum;
import com.ximai.mes.constant.WorkorderStatusEnum;
import com.ximai.mes.pro.domain.ep.EPDtoProWorkOrder;
import com.ximai.mes.pro.domain.proWorkOrder.ProWorkOrderChangeRecord;
import com.ximai.mes.pro.domain.proWorkOrder.ProWorkorder;
import com.ximai.mes.pro.domain.sap.SAPDtoProWorkOrder;
import com.ximai.mes.pro.mapper.proWorkOrder.ProWorkorderMapper;
import com.ximai.mes.pro.service.proWorkOrder.IProWorkOrderChangeRecordService;
import com.ximai.mes.pro.service.proWorkOrder.IProWorkorderService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

import static com.ximai.common.constant.Constants.*;

/**
 * @ Author: chicheng.li
 * @ Date  : 2024/2/21
 */
@Slf4j
@RestController
@RequestMapping(value = "/api/v1/workOrder")
public class WorkorderRestController extends BaseController {

    @Autowired
    private IProWorkorderService proWorkorderService;
    @Resource
    private ProWorkorderMapper proWorkorderMapper;
    @Autowired
    private IProWorkOrderChangeRecordService proWorkOrderChangeRecordService;


    /**
     * sap ep 工单同步逻辑
     *
     * @param orderVo
     * @return
     */
    @ApiOperation(value = "打样工单创建")
    @BasicAuth
    @RequestMapping(value = "/workOrderCreate", method = RequestMethod.POST)
    public AjaxResult workorderCreate(@RequestBody String orderVo) {

        try {
            EPDtoProWorkOrder SAPDtoProWorkOrder = JSON.parseObject(orderVo).toJavaObject(EPDtoProWorkOrder.class);
            proWorkorderService.workorderCreate(SAPDtoProWorkOrder);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * sap 工单同步逻辑  包含增删改
     *
     * @param orderVo
     * @return
     */
    @ApiOperation(value = "sap生产工单操作")
    @BasicAuth
    @RequestMapping(value = "/sapapi", method = RequestMethod.POST)
    public SapAjaxResult sapapi(@RequestBody String orderVo) {
        try {
            SAPDtoProWorkOrder sapDtoProWorkOrder = JSON.parseObject(orderVo, SAPDtoProWorkOrder.class);
            ProWorkOrderChangeRecord proWorkOrderChangeRecord = new ProWorkOrderChangeRecord();
            proWorkOrderChangeRecord.setWorkorderCode(sapDtoProWorkOrder.getWorkorderCode());
            proWorkOrderChangeRecord.setRequestBody(orderVo);
            proWorkOrderChangeRecord.setApiFlag(true);
            proWorkOrderChangeRecordService.insertProWorkOrderChangeRecord(proWorkOrderChangeRecord);


// 状态ID
//I0001
//I0002
//I0045
//I0076
//I0043

            String status = sapDtoProWorkOrder.getStatus();
            ExceptionUtil.checkTrueThrowException(StringUtils.isEmpty(status), "ZSTATUS, 操作类型为空");
            String workorderCode = sapDtoProWorkOrder.getWorkorderCode();
            List<ProWorkorder> proWorkorders = proWorkorderMapper.selectListByQw(new QueryWrapper<ProWorkorder>().eq("workorder_code", workorderCode));
            ProWorkorder proWorkorder = CollectionUtil.isNotEmpty(proWorkorders) ? proWorkorders.get(0) : null;
            WorkorderSAPStatusEnum sapStatusEnum = WorkorderSAPStatusEnum.get(status);
            switch (sapStatusEnum) {
                //  新增/变更
                case RELEASED:
                    if (proWorkorder == null) {
                        proWorkorderService.sapCreateObj(sapDtoProWorkOrder);
                        ProWorkorder workorder = proWorkorderMapper.selectListByQw(new QueryWrapper<ProWorkorder>().eq("workorder_code", workorderCode)).get(0);
                        proWorkOrderChangeRecord.setActionType(METHOD_INSERT_TYPE);
                        proWorkOrderChangeRecord.setWorkorderId(workorder.getWorkorderId());
                        proWorkOrderChangeRecord.setWorkorderCode(workorder.getWorkorderCode());
                        proWorkOrderChangeRecord.setWorkorderName(workorder.getWorkorderName());
                    } else {
                        proWorkorderService.sapUpdateObj(sapDtoProWorkOrder, proWorkorder);
                        proWorkOrderChangeRecord.setActionType(METHOD_UPDATE_TYPE);
                        proWorkOrderChangeRecord.setWorkorderId(proWorkorder.getWorkorderId());
                        proWorkOrderChangeRecord.setWorkorderCode(proWorkorder.getWorkorderCode());
                        proWorkOrderChangeRecord.setWorkorderName(proWorkorder.getWorkorderName());
                    }

                    break;
                case COMPLETED:
                    //  完工
                    if (proWorkorder != null) {
                        proWorkorder.setStatus(WorkorderStatusEnum.FINISHED.getValue());
                        proWorkorder.setApiFlag(true);
                        proWorkorderService.updateProWorkorder(proWorkorder);
                        proWorkOrderChangeRecord.setActionType(METHOD_UPDATE_TYPE);
                        proWorkOrderChangeRecord.setWorkorderId(proWorkorder.getWorkorderId());
                        proWorkOrderChangeRecord.setWorkorderCode(proWorkorder.getWorkorderCode());
                        proWorkOrderChangeRecord.setWorkorderName(proWorkorder.getWorkorderName());
                    }
                    break;
                case CANCAL:
                    ExceptionUtil.checkTrueThrowException(proWorkorder == null, WorkorderConst.WorkOrderErrorConst.ERROR_8);
                    ExceptionUtil.checkTrueThrowException(Objects.equals(proWorkorder.getStatus(), WorkorderStatusEnum.FINISHED.getValue()) || Objects.equals(proWorkorder.getStatus(), WorkorderStatusEnum.CANCELED.getValue()), WorkorderConst.WorkOrderErrorConst.ERROR_10);

                    // 标记/工单作废
                    proWorkorder.setApiFlag(true);
                    proWorkorderService.clossAndDeleteObjV2(proWorkorder);
                    proWorkOrderChangeRecord.setActionType(METHOD_DELETE_TYPE);
                    proWorkOrderChangeRecord.setWorkorderId(proWorkorder.getWorkorderId());
                    proWorkOrderChangeRecord.setWorkorderCode(proWorkorder.getWorkorderCode());
                    proWorkOrderChangeRecord.setWorkorderName(proWorkorder.getWorkorderName());
                    break;
                case LOCK:
                    // 锁定
                    break;
                default:
                    break;
            }
            proWorkOrderChangeRecordService.updateProWorkOrderChangeRecord(proWorkOrderChangeRecord);
        } catch (Exception e) {
            e.printStackTrace();
            return SapAjaxResult.error(e.getMessage());
        }

        return SapAjaxResult.success();
    }

    @ApiOperation(value = "查询工序任务状态")
    @BasicAuth
    @RequestMapping(value = "/getWorkorderProcessInfo", method = RequestMethod.POST)
    public AjaxResult getWorkorderProcessInfo(@RequestBody Map mapArg) {
        String workorderCode = mapArg.get("code").toString();
        return AjaxResult.success(proWorkorderService.getWorkorderProcessInfo(workorderCode));
    }


    @ApiOperation(value = "查询生产销售订单关系")
    @BasicAuth
    @RequestMapping(value = "/saleList", method = RequestMethod.GET)
    public TableDataInfo saleList(ProWorkorder proWorkorder) {
        List<ProWorkorder> proWorkorders = proWorkorderService.selectSaleAndWorkorderList(proWorkorder);
        List<Map<String, Object>> objects = new ArrayList<>();
        for (ProWorkorder workorder : proWorkorders) {
            Map<String, Object> map = new HashMap<>();
            map.put("workorderCode", workorder.getWorkorderCode());
            map.put("arrangeCode", workorder.getArrangeCode());
            map.put("salesVoucher", workorder.getSalesVoucher());
            map.put("salesVoucherItem", workorder.getSalesVoucherItem());
            objects.add(map);
        }

        return getDataTable(objects);
    }



}
