package cn.estsh.i3plus.ext.mes.apiservice.controller.base;

import cn.estsh.i3plus.ext.mes.api.base.IWorkOrderExtService;
import cn.estsh.i3plus.ext.mes.pojo.model.*;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesWorkOrderExt;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.ExcelTool;
import cn.estsh.i3plus.platform.common.util.CommonConstWords;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ResourceEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkOrder;
import cn.estsh.i3plus.pojo.mes.model.RequestModel;
import cn.estsh.impp.framework.base.controller.MesBaseController;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.util.ImppRedis;
import cn.estsh.impp.framework.boot.util.ResultBean;
import cn.estsh.impp.framework.boot.util.ValidatorBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import java.util.List;

/**
 * @author yumingxing
 * @version 1.0
 * @date 2021/1/12 14:39
 **/
@RestController
@RequestMapping(CommonConstWords.BASE_URL_MES + "/work-order")
@Api(tags = "松下生产工单")
public class WorkOrderExtController extends MesBaseController {

    @Autowired
    private IWorkOrderExtService workOrderExtService;
    @Resource(name="redisRes")
    private ImppRedis redisRes;
    @Autowired
    private EntityManager entityManager;

    @ApiOperation("生成工单")
    @PostMapping("generate")
    public ResultBean generateWorkOrder(@RequestBody GenerateWorkOrderDto workOrderDto){
        LOGGER.info("生成工单 输入参数 {}",workOrderDto);
        try {
            ValidatorBean.beginValid(workOrderDto)
                    .notNull("partNo",workOrderDto.getPartNo())
                    .notNull("partNameRdd",workOrderDto.getPartNameRdd())
                    .notNull("qty",workOrderDto.getQty())
                    .notNull("workCenterCode",workOrderDto.getWorkCenterCode())
                    .notNull("startTime",workOrderDto.getStartTime())
                    .notNull("endTime",workOrderDto.getEndTime());
            workOrderExtService.insertManualGenerate(workOrderDto);
            return ResultBean.success();
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }

    }

    /**
     * 系统检查导入的文件格式和数据必要性。文件格式错误提示“格式错误，请检查格式后再次导入。“。
     * 对物料编码、生产线代码和工厂做是否存在的判断，如果不存在，提示“[产线]***不存在“，[]内为数据字段，***为数据。
     * @param file 导入文件
     * @return
     */
    @ApiOperation("导入工单")
    @PostMapping("import")
    public ResultBean importWorkOrder(@RequestParam("file") MultipartFile file){
        try {
            ExcelTool excelTool =new ExcelTool(entityManager,redisRes).setThrowAllErrorMode(true);

            if(!file.getOriginalFilename().contains(".xlsx")){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.BUSINESS_EXCEPTION_DATA_ERROR.getCode())
                        .setErrorDetail("格式错误，请检查格式后再次导入")
                        .setErrorSolution("格式错误，请检查格式后再次导入")
                        .build();
            }
            List<ExcelWorkOrderDto> excelWorkOrderDtoList = excelTool.importData(file.getOriginalFilename(), file.getInputStream(), ExcelWorkOrderDto.class);
            workOrderExtService.importGenerate(excelWorkOrderDtoList);
            return ResultBean.success();
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }

    }

    @ApiOperation("调整工单")
    @PutMapping("adjust")
    public ResultBean adjustWorkOrder(@RequestBody GenerateWorkOrderDto generateWorkOrderDto){
        try {

            workOrderExtService.adjustWorkOrder(generateWorkOrderDto);
            return ResultBean.success();
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }


    @GetMapping(value = "/query-list-page")
    @ApiOperation(value = "生产工单分页查询")
    public ResultBean geWorkOrderListPage(WorkOrderQueryDto workOrderQueryDto, Pager pager) {
        try {

            // 生产工单分页列表
            return ResultBean.success("生产工单分页查询成功")
                    .setListPager(workOrderExtService.getListPageByCondition(workOrderQueryDto, pager))
                    .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException imppException) {
            LOGGER.error(imppException.getErrorMsg() + "：{}", imppException.getErrorDetail(), imppException);
            return ResultBean.fail(imppException);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }



    @PostMapping("close")
    @ApiOperation("生产工单关闭")
    public ResultBean closeWorkOrder(String orderNo){
        try {
            workOrderExtService.closeWorkOrder(orderNo);
            return ResultBean.success();
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }


    @PostMapping("release")
    @ApiOperation("生产工单发布")
    public ResultBean releaseWorkOrder(String orderNo){
        try {
            workOrderExtService.releaseWorkOrder(orderNo);
            return ResultBean.success();
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PostMapping("update-seq")
    @ApiOperation("生产工单调序")
    public ResultBean updateSeq(@RequestBody WorkOrderSeq workOrderSeq){
        try {
            workOrderExtService.updateSeq(workOrderSeq);
            return ResultBean.success();
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }

    }


    @PutMapping(value = "/update-order-status")
    @ApiOperation(value = "生产工单状态批量调整")
    public ResultBean updateWorkOrderStatus(@RequestBody RequestModel requestModel) {
        try {
            List<String> orderNoList = null;
            Integer workOrderStatus = null;
            if (null != requestModel) {
                orderNoList = requestModel.getOrderNoList();
                workOrderStatus = requestModel.getDestStatus();
            }
            // 数据校验
            ValidatorBean.checkNotNull(workOrderStatus, "工单状态不能为空");
            ValidatorBean.checkNotNull(orderNoList, "工单号不能为空");

            //   workOrderExtService.updateWorkOrderStatus(workOrderStatus, orderNoList);
            workOrderExtService.updateEpWorkOrderStatus(workOrderStatus, orderNoList);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }


    @GetMapping(value = "/detail")
    @ApiOperation(value = "获取生产工单详细信息")
    public ResultBean getMesWorkOrderDetail(String orderNo) {
        try {
            return ResultBean.success("操作成功")
                    .setResultObject(workOrderExtService.getMesWorkOrderDetail(orderNo))
                    .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException imppException) {
            LOGGER.error(imppException.getErrorMsg() + "：{}", imppException.getErrorDetail(), imppException);
            return ResultBean.fail(imppException);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/find-by-seq")
    @ApiOperation(value = "查询需要排序的工单")
    public ResultBean findMesWorkOrderBySeqAsc(MesWorkOrder mesWorkOrder) {
        try {
            mesWorkOrder.setOrganizeCode(AuthUtil.getOrganize().getOrganizeCode());
            return new ResultBean(true, workOrderExtService.findMesWorkOrderBySeqAsc(mesWorkOrder)).setMsg("查询配置详情成功");
        } catch (ImppBusiException imppException) {
            LOGGER.error(imppException.getErrorMsg() + "：{}", imppException.getErrorDetail(), imppException);
            return ResultBean.fail(imppException);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PostMapping(value = "sort-by/mes-work-order/update")
    @ApiOperation(value = "生产工单重新排序和时间", notes = "生产工单重新排序和时间")
    public ResultBean updateSortByMesWorkOrder(@RequestBody List<MesWorkOrderExt> mesWorkOrderList) {
        try {
            workOrderExtService.updateSortByMesWorkOrder(mesWorkOrderList);
            return ResultBean.success("修改成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException imppException) {
            LOGGER.error(imppException.getErrorMsg() + "：{}", imppException.getErrorDetail(), imppException);
            return ResultBean.fail(imppException);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }


    @ApiOperation("WMS获取mes工单最大SEQ,根据生产版本获取生产线及区域代码")
    @PostMapping("/max-seq-and-center/query")
    public ResultBean doHandleWmsWorkOrder(@RequestBody SxWmsToMesWorkOrderModel model){
        try {
            ValidatorBean.beginValid(model)
                    .notNull(MesExtConstWords.ORGANIZE_CODE, model.getOrganizeCode());

            SxWmsToMesWorkOrderModel sxWmsToMesWorkOrderModel = workOrderExtService.doHandleWmsWorkOrder(model);

            return ResultBean.success("查询成功")
                    .setResultObject(sxWmsToMesWorkOrderModel)
                    .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

}
