package com.sunda.spmsweb.ordercontroller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsorder.entity.MaterialApplication;
import com.sunda.spmsorder.entity.OrderKeyValueConfig;
import com.sunda.spmsorder.entity.vo.MaterialApplicationQueryResultVo;
import com.sunda.spmsorder.entity.vo.MaterialApplicationQueryVo;
import com.sunda.spmsorder.excel.MaterialApplicationExcel;
import com.sunda.spmsorder.service.IMaterialApplicationDtlService;
import com.sunda.spmsorder.service.IMaterialApplicationService;
import com.sunda.spmsorder.service.IOrderKeyValueConfigService;
import com.sunda.spmsorder.service.IOrderLogService;
import com.sunda.spmsoversea.entity.ZOaOrgClient;
import com.sunda.spmsoversea.service.IZOaOrgClientService;
import com.sunda.spmsuser.entity.SpmsUser;
import com.sunda.spmsuser.service.ISpmsUserService;
import com.sunda.spmsweb.oaservice.OaService;
import com.sunda.spmsweb.util.ExcelUtil;
import com.sunda.spmsweb.util.JWTUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.sunda.spmscommon.Constans.SUBMIT_OA_ERROR;
import static com.sunda.spmscommon.Constans.SUBMIT_OA_SUCCESS;

/**
 * <p>
 * 物料申请单表表头 前端控制器
 * </p>
 *
 * @author Wayne
 * @since 2021-05-21
 */
@RestController
@RequestMapping("/materialApplication")
@Api(tags = "物料申请接口", description = "物料申请接口")
public class MaterialApplicationController {

    @Autowired
    IMaterialApplicationService iMaterialApplicationService;

    @Autowired
    IMaterialApplicationDtlService iMaterialApplicationDtlService;
    @Autowired
    IOrderKeyValueConfigService iOrderKeyValueConfigService;

    @Value("${oa.workflow.id0915}")
    String workflow0915;
    @Value("${oa.new.workflow.id0915}")
    String workflow0915_new;
    @Value("${oa.ipo.workflow.id0915}")
    String workflow0915_ipo;
    @Value("${oa.new.url}")
    String oaUrl;

    @Autowired
    IOrderLogService iOrderLogService;
    @Autowired
    ISpmsUserService iSpmsUserService;

    @Autowired
    private IZOaOrgClientService izOaOrgClientService;

    @RequestMapping("/getMaterialApplicationList")
    @ApiOperation(value = "获取物料申请表头不分页", notes = "查询物料申请表头\n" +
            "入参都非必输\n", httpMethod = "POST")
    public ResponseResult getMaterialApplicationList(MaterialApplicationQueryVo materialApplicationQueryVo){
        try {
            return ResponseResult.success().add("getMaterialApplicationList", iMaterialApplicationService.getMaterialApplicationList(materialApplicationQueryVo));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }

    @RequestMapping("/deleteMaterialApplication")
    @ApiOperation(value = "删除物料申请表头", notes = "删除物料申请表头", httpMethod = "POST")
    @RequiresPermissions("materialApplication-deleteMaterialApplication")
    public ResponseResult deletemMaterialApplication( @RequestParam("appUuid") String applicationUuid){
        try {
            return ResponseResult.success().add("deleteMaterialApplication", iMaterialApplicationService.deleteMaAndDtl(applicationUuid));
        }catch ( Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }

    @RequestMapping("/getIPageMA")
    @ApiOperation(value = "获取物料申请表头Page VoEntity 分页", notes = "获取物料申请表头Page VoEntity 分页\n" +
            "入参都非必输\n", httpMethod = "POST")
    public ResponseResult getIPageMA(@RequestBody MaterialApplicationQueryVo materialApplicationQueryVo){
        try {
            return ResponseResult.success().add("getMaterialApplicationPage", iMaterialApplicationService.getPageMaterialApplication(materialApplicationQueryVo));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }

    @RequestMapping("/getPageMap")
    @ApiOperation(value = "获取物料申请表头Page Map 分页", notes = "获取物料申请表头Page Map 分页\n" +
            "入参都非必输\n" +
            "{\n" +
            "\t\"applicationId\": \"\",\n" +
            "\t\"beginDate\": \"2021-08-06\",\n" +
            "\t\"endDate\": \"2021-08-06\",\n" +
            "\t\"pageNo\": 1,\n" +
            "\t\"pageSize\": 20,\n" +
            "\t\"spmsStatus\": \"\",\n" +
            "\t\"userId\": \"\",\n" +
            "\t\"werks\": \"\",\n" +
            "\t\"workshopCode\": \"\"\n" +
            "}", httpMethod = "POST")
    @RequiresPermissions("materialApplication-getPageMap")
    public ResponseResult getPageMap(@RequestBody JSONObject doc){
        try {
            return ResponseResult.success().add("getMaterialApplicationList", iMaterialApplicationService.getPageMap(doc));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }

    @RequestMapping("/getMADtlList")
    @ApiOperation(value = "查询物料申请行项目", notes = "查询物料申请行项目\n" +
            "入参为物料申请单uuid 示例 applicationUuid = 123456；\n", httpMethod = "POST")
    @RequiresPermissions("materialApplication-getMADtlList")
    public ResponseResult getMaterialApplicationDtlList(String applicationUuid){
        try {
            return ResponseResult.success().add("getMaterialApplicationDtlList", iMaterialApplicationService.getMaterialApplicationDtlList(applicationUuid));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }


    @RequestMapping("/getMaterialApplicationByOaCode")
    @ApiOperation(value = "获取物料申请OA日志", notes = "获取物料申请OA日志信息，实时向OA发一个请求，示例 requestId = 838295, 933533", httpMethod = "POST")
    @RequiresPermissions("materialApplication-getMaterialApplicationByOaCode")
    public ResponseResult getMaterialApplicationByOaCode(String requestId) {
        try {
            OaService oaService = new OaService();
            String userId = "";
            MaterialApplication materialApplication = iMaterialApplicationService.getMaterialApplicationByOaCode(requestId);
            if(materialApplication!=null){
                userId = materialApplication.getUserId();
            }else{
                return ResponseResult.success().add("orderWerksOALog", new ArrayList<>());
            }

            // 根据工厂查询对应的OA Clinet
            String oaUl = oaUrl;
            List<ZOaOrgClient> selectList = izOaOrgClientService.getByWerks(materialApplication.getWerks());
            if (CollectionUtils.isNotEmpty(selectList)) {
                oaUl =  selectList.get(0).getOa();
            } else {
                throw new RuntimeException("工厂："+materialApplication.getWerks()+"未找到对应的OA服务");
            }
            return ResponseResult.success().add("orderWerksOALog", oaService.getOALogV2(requestId,oaUl,userId));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }


    @RequestMapping("/addMaAndDtl")
    @ApiOperation(value = "新建或更新物料申请单", notes = "新建或更新物料申请单\n" +
            "请求参数示例：\n" +
            "{\n" +
            "\t\"materialApplication\": {\n" +
            "\t\t\"applicationUuid\": \"\",\n" +
            "\t\t\"applicationType\": \"1\",\n" +
            "\t\t\"userId\": \"999947\",\n" +
            "\t\t\"werks\": \"GF03\",\n" +
            "\t\t\"spmsStatus\": \"1\",\n" +
            "\t\t\"workshopCode\": \"RM\",\n" +
            "\t\t\"remarks\": null,\n" +
            "\t\t\"applicationDate\": \"2021-05-26\",\n" +
            "\t\t\"cpx\": \"0\"\n" +
            "\t},\n" +
            "\t\"materialApplicationDtl\": [{\n" +
            "\t\t\t\"applicationUuid\": \"\",\n" +
            "\t\t\t\"applicationItem\": \"10\",\n" +
            "\t\t\t\"materialEnDesc\": \"123\",\n" +
            "\t\t\t\"specs\": \"123\",\n" +
            "\t\t\t\"basicUnit\": \"12\",\n" +
            "\t\t\t\"materialModel\": null,\n" +
            "\t\t\t\"supplierMaterialNo\": null,\n" +
            "\t\t\t\"supplyDesc\": null,\n" +
            "\t\t\t\"relateEquipment\": null,\n" +
            "\t\t\t\"equipmentSpec\": null,\n" +
            "\t\t\t\"equipmentSupplier\": null,\n" +
            "\t\t\t\"equipmentBrand\": null,\n" +
            "\t\t\t\"productLevelLargeDesc\": null,\n" +
            "\t\t\t\"productLevelMidDesc\": null,\n" +
            "\t\t\t\"productLevelSmallDesc\": null,\n" +
            "\t\t\t\"picture\": null,\n" +
            "\t\t\t\"purchaseUsername\": null,\n" +
            "\t\t\t\"spareField\": null,\n" +
            "\t\t\t\"remarks\": null\n" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"applicationUuid\": \"\",\n" +
            "\t\t\t\"applicationItem\": \"20\",\n" +
            "\t\t\t\"materialEnDesc\": \"234\",\n" +
            "\t\t\t\"specs\": \"21\",\n" +
            "\t\t\t\"basicUnit\": \"12\",\n" +
            "\t\t\t\"materialModel\": null,\n" +
            "\t\t\t\"supplierMaterialNo\": null,\n" +
            "\t\t\t\"supplyDesc\": null,\n" +
            "\t\t\t\"relateEquipment\": null,\n" +
            "\t\t\t\"equipmentSpec\": null,\n" +
            "\t\t\t\"equipmentSupplier\": null,\n" +
            "\t\t\t\"equipmentBrand\": null,\n" +
            "\t\t\t\"productLevelLargeDesc\": null,\n" +
            "\t\t\t\"productLevelMidDesc\": null,\n" +
            "\t\t\t\"productLevelSmallDesc\": null,\n" +
            "\t\t\t\"picture\": null,\n" +
            "\t\t\t\"purchaseUsername\": null,\n" +
            "\t\t\t\"spareField\": null,\n" +
            "\t\t\t\"remarks\": null\n" +
            "\t\t}\n" +
            "\t]\n" +
            "}\n" +
            "请求表头中 werks, workshopCode, spmsStatus 必输。spmsStatus 说明：1保存（可修改、删除）；2提交；\n"
            ,httpMethod = "POST")
    @RequiresPermissions("materialApplication-addMaAndDtl")
    public ResponseResult addMaAndDtl(@RequestBody JSONObject doc){
        String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
        try {
            ResponseResult responseResult = iMaterialApplicationService.addMaAndDtl(doc, userId);
            return responseResult;
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }


    @RequestMapping("/materialApplicationSubmitOA")
    @ApiOperation(value = "物料申请单提交OA", notes = "物料申请单提交OA\n" +
            "请求参数示例：\n" +
            "{\n" +
            "\t\"applicationUuid\": \"3989f36cf540452f904cad51a14d2a48\"" +
            "}\n" +
            "请求表头中 applicationUuid 必输。\n"
            ,httpMethod = "POST")
    public ResponseResult materialApplicationSubmitOA (@RequestBody JSONObject doc){
        String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
        try {
            ResponseResult responseResult = iMaterialApplicationService.getMaAndDtlExcel(doc, userId);
            if (responseResult.getCode() == 200){
                // 提交OA流程
                String uuid = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
                SpmsUser spmsUser = iSpmsUserService.getByUserId(((MaterialApplication)responseResult.getData().get("materialApplication")).getUserId());
                OaService oaService = new OaService();
                if (((MaterialApplication) responseResult.getData().get("materialApplication")).getCpx().isEmpty()){
                    return ResponseResult.error("产品线不能为空");
                }
                doc.put("cpx", ((MaterialApplication)responseResult.getData().get("materialApplication")).getCpx());
                doc.put("applicationId", ((MaterialApplication)responseResult.getData().get("materialApplication")).getApplicationId());
                doc.put("werks", ((MaterialApplication)responseResult.getData().get("materialApplication")).getWerks());
                doc.put("purchaseLocation", ((MaterialApplication)responseResult.getData().get("materialApplication")).getPurchaseLocation());

                List<OrderKeyValueConfig> orderKeyValueConfigs = iOrderKeyValueConfigService.getByFieldKey("oaConfig");
                boolean newOa = false;
                if(orderKeyValueConfigs!=null && orderKeyValueConfigs.size()>0){
                    String oaConfig = orderKeyValueConfigs.get(0).getKeyCode();
                    if("0".equals(oaConfig)){//0:启用新OA接口
                        workflow0915 = workflow0915_new;
                        newOa = true;
                    }
                }

                MaterialApplicationQueryVo queryVo = new MaterialApplicationQueryVo();
                queryVo.setApplicationId(doc.getString("applicationId"));
                List<MaterialApplicationQueryResultVo> resultVos = iMaterialApplicationService.getMaterialApplicationList(queryVo);
                // 根据工厂查询对应的OA Clinet
                String oaUl = oaUrl;
                String oaClient = "OA";
                List<ZOaOrgClient> selectList = izOaOrgClientService.getByWerks(resultVos.get(0).getWerks());
                if (CollectionUtils.isNotEmpty(selectList)) {
                    oaUl =  selectList.get(0).getOa();
                    if(oaUl.contains("fm-oa") || oaUl.contains("oa-ipo")){
                        workflow0915 = workflow0915_ipo;
                        oaClient = "FM-OA";
                    }else{
                        workflow0915 = workflow0915_new;
                    }
                } else {
                    throw new RuntimeException("工厂："+resultVos.get(0).getWerks()+"未找到对应的OA服务");
                }
                int reqid = oaService.createRequest0915(doc, responseResult.getData().get("filename").toString(), responseResult.getData().get("fileUrl").toString(), spmsUser,workflow0915,oaUl,newOa);
                //int reqid = 100000;
                if (reqid <= 0) {
                    /** 记录物料申请提交OA失败日志信息 */
                    iOrderLogService.saveOrderLog(spmsUser.getUserId(),  SUBMIT_OA_ERROR + " " + reqid, uuid);
                    return ResponseResult.error("物料申请提交OA失败")
                            .add("reqid", reqid)
                            .add("materialApplication", responseResult.getData().get("materialApplication"))
                            .add("getMaterialApplicationDtlList", responseResult.getData().get("getMaterialApplicationDtlList"));
                }
                // 将OA返回的编号信息写入申请单
                ResponseResult updateResponseResult = iMaterialApplicationService.updateMaterialApplicationSubmitOaStatus(doc, reqid, userId,oaClient);
                if (updateResponseResult.getCode() == 200){
                    /** 记录物料申请提交OA成功日志信息 */
                    iOrderLogService.saveOrderLog(spmsUser.getUserId(),  SUBMIT_OA_SUCCESS, uuid);
                    return ResponseResult.success("物料申请提交OA成功")
                            .add("reqid", reqid)
                            .add("materialApplication", responseResult.getData().get("materialApplication"))
                            .add("getMaterialApplicationDtlList", responseResult.getData().get("getMaterialApplicationDtlList"));
                }
            }
            return responseResult;
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }

    @RequestMapping("/setBom")
    @ApiOperation(value = "更新物料号", notes = "更新物料号\n" +
            "请求参数示例：\n" +
            "{\n" +
            "\t\"materialApplication\": {\n" +
            "\t\t\"applicationUuid\": \"\",\n" +
            "\t\t\"applicationType\": \"1\",\n" +
            "\t\t\"userId\": \"999947\",\n" +
            "\t\t\"werks\": \"GF03\",\n" +
            "\t\t\"spmsStatus\": \"1\",\n" +
            "\t\t\"workshopCode\": \"RM\",\n" +
            "\t\t\"remarks\": null,\n" +
            "\t\t\"applicationDate\": \"2021-05-26\"\n" +
            "\t},\n" +
            "\t\"materialApplicationDtl\": [{\n" +
            "\t\t\t\"applicationUuid\": \"\",\n" +
            "\t\t\t\"applicationItem\": \"10\",\n" +
            "\t\t\t\"materialEnDesc\": \"123\",\n" +
            "\t\t\t\"specs\": \"123\",\n" +
            "\t\t\t\"basicUnit\": \"12\",\n" +
            "\t\t\t\"materialModel\": null,\n" +
            "\t\t\t\"supplierMaterialNo\": null,\n" +
            "\t\t\t\"supplyDesc\": null,\n" +
            "\t\t\t\"relateEquipment\": null,\n" +
            "\t\t\t\"equipmentSpec\": null,\n" +
            "\t\t\t\"equipmentSupplier\": null,\n" +
            "\t\t\t\"equipmentBrand\": null,\n" +
            "\t\t\t\"productLevelLargeDesc\": null,\n" +
            "\t\t\t\"productLevelMidDesc\": null,\n" +
            "\t\t\t\"productLevelSmallDesc\": null,\n" +
            "\t\t\t\"picture\": null,\n" +
            "\t\t\t\"remarks\": null\n" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"applicationUuid\": \"\",\n" +
            "\t\t\t\"applicationItem\": \"20\",\n" +
            "\t\t\t\"materialEnDesc\": \"234\",\n" +
            "\t\t\t\"specs\": \"21\",\n" +
            "\t\t\t\"basicUnit\": \"12\",\n" +
            "\t\t\t\"materialModel\": null,\n" +
            "\t\t\t\"supplierMaterialNo\": null,\n" +
            "\t\t\t\"supplyDesc\": null,\n" +
            "\t\t\t\"relateEquipment\": null,\n" +
            "\t\t\t\"equipmentSpec\": null,\n" +
            "\t\t\t\"equipmentSupplier\": null,\n" +
            "\t\t\t\"equipmentBrand\": null,\n" +
            "\t\t\t\"productLevelLargeDesc\": null,\n" +
            "\t\t\t\"productLevelMidDesc\": null,\n" +
            "\t\t\t\"productLevelSmallDesc\": null,\n" +
            "\t\t\t\"picture\": null,\n" +
            "\t\t\t\"remarks\": null\n" +
            "\t\t}\n" +
            "\t]\n" +
            "}\n" +
            "请求表头中 werks, workshopCode, spmsStatus 必输。spmsStatus 说明：1保存（可修改、删除）；2提交；\n"
            ,httpMethod = "POST")
    @RequiresPermissions("materialApplication-setBom")
    public ResponseResult setBom(@RequestBody JSONObject doc){
        String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
        try {
            return iMaterialApplicationService.setBom(doc, userId);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }

    @RequestMapping("/getOrderLogList")
    @ApiOperation(value = "查询物料申请单关联操作日志", notes = "查询物料申请单关联操作日志\n" +
            "入参为物料申请单uuid 示例 applicationUuid = 123456；\n", httpMethod = "POST")
    public ResponseResult getOrderLogList(String applicationUuid){
        try {
            return ResponseResult.success().add("orderLogList", iMaterialApplicationService.getOrderLogList(applicationUuid));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }


    @RequestMapping("/deleteMaAndDtl")
    @ApiOperation(value = "根据物料申请单uuid删除单据", notes = "根据物料申请单uuid删除单据\n" +
            "入参为物料申请单uuid。此处做真删除。\n", httpMethod = "POST")
    public ResponseResult deleteMaAndDtl(String applicationUuid){
        try {
            return iMaterialApplicationService.deleteMaAndDtl(applicationUuid);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }

    @RequestMapping("/getMaDtlBySpmsStatus")
    @ApiOperation(value="根据物料状态查找物料详情",
            notes= "{\n" +
                    "\"applicationId\": null,\n" +
                    "\"applicationUuid\": null,\n" +
                    "\"cpx\": 1,\n" +
                    "\"pageNo\": null,\n" +
                    "\"pageSize\": 20,\n" +
                    "\"werks\": null,\n" +
                    "\"workshopCode\": null,\n" +
                    "\"userId\":999948\n" +
                    "}",
            httpMethod = "GET")
    public ResponseResult getMatByStatus(@RequestBody JSONObject doc){

        int pageNo = !doc.containsKey("pageNo") || doc.get("pageNo") == null || "".equals(doc.get("pageNo")) ? 1 : Integer.parseInt(doc.get("pageNo").toString());
        int pageSize = !doc.containsKey("pageSize") || doc.get("pageSize") == null || "".equals(doc.get("pageSize")) ? 20 : Integer.parseInt(doc.get("pageSize").toString());
        Page<Map<String, Object>> pages = new Page<>(pageNo, pageSize);
        List<Map<String, Object>> pageData = iMaterialApplicationDtlService.getMatBySpms(pages);
        pages.setRecords(pageData);

        try {
            return ResponseResult.success().add("page",pages);
//            return ResponseResult.success().add("list",iMaterialApplicationDtlService.getMatBySpms(pages));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }

    @RequestMapping("/getMatDtl")
    @ApiOperation(value="查找物料",notes="查找物料\n" +
            "示例参数：\n" +
            "{\n" +
            "\t\"applicationId\": \"\",\n" +
            "\t\"applicationitem\": \"\",\n" +
            "\t\"cpx\": \"\",\n" +
            "\t\"applicationUuid\": \"\",\n" +
            "\t\"werks\": \"CI31\",\n" +
            "\t\"specs\": \"\",\n" +
            "\t\"materialEnDesc\": \"\",\n" +
            "\t\"userId\": \"\",\n" +
            "\t\"name\": \"\",\n" +
            "\t\"materialNo\": \"\",\n" +
            "\t\"beginDate\": \"2022-01-01\",\n" +
            "\t\"endDate\": \"2022-01-31\",\n" +
            "\t\"pageNo\": 1,\n" +
            "\t\"pageSize\": \"20\"\n" +
            "}", httpMethod = "POST")
    @RequiresPermissions("materialApplication-getMatDtl")
    public ResponseResult getMatDtl(@RequestBody JSONObject doc){

        int pageNo = !doc.containsKey("pageNo") || doc.get("pageNo") == null || "".equals(doc.get("pageNo")) ? 1 : Integer.parseInt(doc.get("pageNo").toString());
        int pageSize = !doc.containsKey("pageSize") || doc.get("pageSize") == null || "".equals(doc.get("pageSize")) ? 20 : Integer.parseInt(doc.get("pageSize").toString());

        System.out.println(doc);
        String applicationId = StringUtils.isNotEmpty(doc.getString("applicationId")) ?doc.getString("applicationId"):null;
        String applicationItem = StringUtils.isNotEmpty(doc.getString("applicationitem"))?doc.getString("applicationitem"):null;
        String cpx = StringUtils.isNotEmpty(doc.getString("cpx"))?doc.getString("cpx"):null;
        String applicationUuid = StringUtils.isNotEmpty(doc.getString("applicationUuid"))?doc.getString("applicationUuid"):null;
        String werks = StringUtils.isNotEmpty(doc.getString("werks"))?doc.getString("werks"):null;
        String specs = StringUtils.isNotEmpty(doc.getString("specs"))?doc.getString("specs"):null;
        String materialEnDesc = StringUtils.isNotEmpty(doc.getString("materialEnDesc"))?doc.getString("materialEnDesc"):null;
        String userId = StringUtils.isNotEmpty(doc.getString("userId"))?doc.getString("userId"):null;
        String name = StringUtils.isNotEmpty(doc.getString("name"))?doc.getString("name"):null;
        String materialNo =StringUtils.isNotEmpty(doc.getString("materialNo"))?doc.getString("materialNo"):null;
        String beginDate = StringUtils.isNotEmpty(doc.getString("beginDate")) ? doc.getString("beginDate") : null;
        String endDate = StringUtils.isNotEmpty(doc.getString("endDate")) ? doc.getString("endDate") : null;

        Page<Map<String, Object>> pages = new Page<>(pageNo, pageSize);
        List<Map<String, Object>> pageData = iMaterialApplicationDtlService.getMatBySpmsNParam(pages, applicationId, applicationItem, cpx, applicationUuid,
                werks, specs, materialEnDesc, userId, name, materialNo, beginDate, endDate);
        pages.setRecords(pageData);

        try {

            return ResponseResult.success().add("page",pages);
//            return ResponseResult.success().add("list",iMaterialApplicationDtlService.getMatBySpmsNParam(pages,applicationId,applicationItem,cpx,applicationUuid,werks,specs, materialEnDesc, userId, name, materialNo));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error(e.getMessage());
        }
    }


    /**
     * 导出车间请购单详情
     */
    @RequestMapping("/exportMatDtl")
    @ApiOperation(value = "导出非目录物料", notes="导出非目录物料\n" +
            "示例参数：\n" +
            "{\n" +
            "\t\"applicationId\": \"\",\n" +
            "\t\"applicationitem\": \"\",\n" +
            "\t\"cpx\": \"\",\n" +
            "\t\"applicationUuid\": \"\",\n" +
            "\t\"werks\": \"CI31\",\n" +
            "\t\"specs\": \"\",\n" +
            "\t\"materialEnDesc\": \"\",\n" +
            "\t\"userId\": \"\",\n" +
            "\t\"name\": \"\",\n" +
            "\t\"materialNo\": \"\",\n" +
            "\t\"beginDate\": \"2022-01-01\",\n" +
            "\t\"endDate\": \"2022-01-31\",\n" +
            "\t\"pageNo\": 1,\n" +
            "\t\"pageSize\": \"20\"\n" +
            "}", httpMethod = "POST")
    //public void exportMatDtl(String da, HttpServletResponse response) {
    public void exportMatDtl(@RequestBody JSONObject doc, HttpServletResponse response) {
        try {
            //JSONObject doc = new JSONObject();
            String applicationId = StringUtils.isNotEmpty(doc.getString("applicationId")) ?doc.getString("applicationId"):null;
            String applicationItem = StringUtils.isNotEmpty(doc.getString("applicationitem"))?doc.getString("applicationitem"):null;
            String cpx = StringUtils.isNotEmpty(doc.getString("cpx"))?doc.getString("cpx"):null;
            String applicationUuid = StringUtils.isNotEmpty(doc.getString("applicationUuid"))?doc.getString("applicationUuid"):null;
            String werks = StringUtils.isNotEmpty(doc.getString("werks"))?doc.getString("werks"):null;
            String specs = StringUtils.isNotEmpty(doc.getString("specs"))?doc.getString("specs"):null;
            String materialEnDesc = StringUtils.isNotEmpty(doc.getString("materialEnDesc"))?doc.getString("materialEnDesc"):null;
            String userId = StringUtils.isNotEmpty(doc.getString("userId"))?doc.getString("userId"):null;
            String name = StringUtils.isNotEmpty(doc.getString("name"))?doc.getString("name"):null;
            String materialNo =StringUtils.isNotEmpty(doc.getString("materialNo"))?doc.getString("materialNo"):null;

            List<Map<String,Object>> result = iMaterialApplicationDtlService.getExcelMap(applicationId, applicationItem, cpx, applicationUuid, werks, specs, materialEnDesc, userId, name, materialNo);

            List<MaterialApplicationExcel> itemList = new ArrayList<MaterialApplicationExcel>();
            if(result!=null && result.size()>0) {
                for (int i = 0; i < result.size(); i++) {
                    Map<String,Object> map = (Map<String,Object>) result.get(i);
                    MaterialApplicationExcel report = JSONObject.parseObject(JSONObject.toJSONString(map), MaterialApplicationExcel.class);
                    itemList.add(report);
                }
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String dateTime = sdf.format(new Date() );
            ExcelUtil.export(response, "MaterialDtl" + dateTime, "bodyData", itemList, MaterialApplicationExcel.class);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @RequestMapping("/getMaDtlBySpmsStatusNParam")
    @ApiOperation(value="根据参数查找物料详情", notes="根据参数查找物料详情", httpMethod = "POST")
    public ResponseResult getMatByStatusNParam(@RequestBody JSONObject doc){

        int pageNo = !doc.containsKey("pageNo") || doc.get("pageNo") == null || "".equals(doc.get("pageNo")) ? 1 : Integer.parseInt(doc.get("pageNo").toString());
        int pageSize = !doc.containsKey("pageSize") || doc.get("pageSize") == null || "".equals(doc.get("pageSize")) ? 20 : Integer.parseInt(doc.get("pageSize").toString());

        System.out.println(doc);
        String applicationId = StringUtils.isNotEmpty(doc.getString("applicationId")) ?doc.getString("applicationId"):null;
        String applicationItem = StringUtils.isNotEmpty(doc.getString("applicationitem"))?doc.getString("applicationitem"):null;
        String cpx = StringUtils.isNotEmpty(doc.getString("cpx"))?doc.getString("cpx"):null;
        String applicationUuid = StringUtils.isNotEmpty(doc.getString("applicationUuid"))?doc.getString("applicationUuid"):null;
        String werks = StringUtils.isNotEmpty(doc.getString("werks"))?doc.getString("werks"):null;
        String specs = StringUtils.isNotEmpty(doc.getString("specs"))?doc.getString("specs"):null;
        String materialEnDesc = StringUtils.isNotEmpty(doc.getString("materialEnDesc"))?doc.getString("materialEnDesc"):null;
        String userId = StringUtils.isNotEmpty(doc.getString("userId"))?doc.getString("userId"):null;
        String name = StringUtils.isNotEmpty(doc.getString("name"))?doc.getString("name"):null;
        String materialNo =StringUtils.isNotEmpty(doc.getString("materialNo"))?doc.getString("materialNo"):null;
        List<String> timeJson = StringUtils.isNotEmpty(doc.getString("time"))?(List<String>)doc.get("time"): Arrays.asList("","");
        if(timeJson!=null){
            System.out.println(timeJson);
        }


        Page<Map<String, Object>> pages = new Page<>(pageNo, pageSize);
        List<Map<String, Object>> pageData = iMaterialApplicationDtlService.getMatBySpmsNParam(pages, applicationId, applicationItem, cpx, applicationUuid, werks, specs, materialEnDesc, userId, name, materialNo, timeJson.get(0),timeJson.get(1));
        pages.setRecords(pageData);

        try {

              return ResponseResult.success().add("page",pages);
//            return ResponseResult.success().add("list",iMaterialApplicationDtlService.getMatBySpmsNParam(pages,applicationId,applicationItem,cpx,applicationUuid,werks,specs, materialEnDesc, userId, name, materialNo));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error(e.getMessage());
        }
    }

    @RequestMapping("/getExcelMaDtlBySpms")
    @ApiOperation(value="下载物料清单详情", notes="下载物料清单详情", httpMethod = "POST")
    public ResponseResult getEditMatByStatus(@RequestBody JSONObject doc){

//        int pageNo = !doc.containsKey("pageNo") || doc.get("pageNo") == null || "".equals(doc.get("pageNo")) ? 1 : Integer.parseInt(doc.get("pageNo").toString());
//        int pageSize = !doc.containsKey("pageSize") || doc.get("pageSize") == null || "".equals(doc.get("pageSize")) ? 20 : Integer.parseInt(doc.get("pageSize").toString());

        System.out.println(doc);
        String applicationId = StringUtils.isNotEmpty(doc.getString("applicationId")) ?doc.getString("applicationId"):null;
        String applicationItem = StringUtils.isNotEmpty(doc.getString("applicationitem"))?doc.getString("applicationitem"):null;
        String cpx = StringUtils.isNotEmpty(doc.getString("cpx"))?doc.getString("cpx"):null;
        String applicationUuid = StringUtils.isNotEmpty(doc.getString("applicationUuid"))?doc.getString("applicationUuid"):null;
        String werks = StringUtils.isNotEmpty(doc.getString("werks"))?doc.getString("werks"):null;
        String specs = StringUtils.isNotEmpty(doc.getString("specs"))?doc.getString("specs"):null;
        String materialEnDesc = StringUtils.isNotEmpty(doc.getString("materialEnDesc"))?doc.getString("materialEnDesc"):null;
        String userId = StringUtils.isNotEmpty(doc.getString("userId"))?doc.getString("userId"):null;
        String name = StringUtils.isNotEmpty(doc.getString("name"))?doc.getString("name"):null;
        String materialNo =StringUtils.isNotEmpty(doc.getString("materialNo"))?doc.getString("materialNo"):null;

//        Page<Map<String, Object>> pages = new Page<>(pageNo, pageSize);
//        List<Map<String, Object>> pageData = iMaterialApplicationDtlService.getMatBySpmsNParam(pages, applicationId, applicationItem, cpx, applicationUuid, werks, specs, materialEnDesc, userId, name, materialNo);
        List<Map<String,Object>> answer = iMaterialApplicationDtlService.getExcelMap(applicationId, applicationItem, cpx, applicationUuid, werks, specs, materialEnDesc, userId, name, materialNo);
//        pages.setRecords(pageData);

        try {

            return ResponseResult.success().add("page",answer);
//            return ResponseResult.success().add("list",iMaterialApplicationDtlService.getMatBySpmsNParam(pages,applicationId,applicationItem,cpx,applicationUuid,werks,specs, materialEnDesc, userId, name, materialNo));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error(e.getMessage());
        }
    }


    @RequestMapping("/getMatSingle")
    @ApiOperation(value = "单个更新",notes="单个更新",httpMethod = "POST" )
    public ResponseResult getMatBySingle(@RequestBody JSONObject doc){
        String applicationUuid = doc.getString("applicationUuid");
        String applicationItem = doc.getString("applicationItem");
        String materialNo = doc.getString("materialNo");
        try{
            return ResponseResult.success().add("code",iMaterialApplicationDtlService.updateMaterialNoByList(materialNo,applicationUuid,applicationItem));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error(e.getMessage());
        }
    }
}
