//package com.sw.mes.yb.pc.controller;
//
//import com.alibaba.fastjson.JSONObject;
//import com.sw.mes.core.context.BaseContextHandler;
//import com.sw.mes.core.response.ResponsePage;
//import com.sw.mes.core.response.Result;
//import com.sw.mes.core.response.ResultGenerator;
//import com.sw.mes.base.system.service.DictionaryItemService;
//import com.sw.mes.core.utils.DynamicSpecifications;
//import com.sw.mes.core.utils.HTTPRequestUtil;
//import com.sw.mes.core.utils.RequestPage;
//
//
//import com.sw.mes.yb.check.entity.PieceCheck;
//import com.sw.mes.yb.check.service.PieceCheckService;
//import com.sw.mes.yb.pad.entity.ProductionPaintingLineDetail;
//import com.sw.mes.yb.pad.entity.ReCut;
//import com.sw.mes.yb.pad.service.ProductionPaintingLineDetailService;
//import com.sw.mes.yb.pad.service.FbReCutService;
//import com.sw.mes.yb.pad.service.SectionDetailService;
//import com.sw.mes.yb.pc.entity.*;
//import com.sw.mes.yb.pc.service.*;
//import com.sw.mes.yb.turnstore.entity.TurnstoreInItem;
//import com.sw.mes.yb.turnstore.entity.TurnstoreOutItem;
//import com.sw.mes.yb.turnstore.service.TurnstoreInItemService;
//import com.sw.mes.yb.turnstore.service.TurnstoreOutItemService;
//import io.swagger.annotations.*;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.StringUtils;
//import org.modelmapper.ModelMapper;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.jpa.domain.Specification;
//import org.springframework.web.bind.annotation.*;
//import org.springframework.web.multipart.MultipartFile;
//
//import javax.servlet.ServletRequest;
//import javax.servlet.http.HttpServletRequest;
//import javax.validation.Valid;
//import java.io.UnsupportedEncodingException;
//import java.net.URLEncoder;
//import java.util.*;
//
//@RestController
//@RequestMapping("/inspect")
//@Slf4j
//@Api(description = "检验接口")
//public class InspectController {
//
//    @Autowired
//    private InspectService inspectService;
//
//    @Autowired
//    private SectionDetailService sectionDetailService;
//
//    @Autowired
//    private PieceCheckService pieceCheckService;
//
//    @Autowired
//    private TurnstoreInItemService turnstoreInItemService;
//
//    @Autowired
//    private TurnstoreOutItemService turnstoreOutItemService;
//
//    @Autowired
//    private FbReCutService fbReCutService;
//
//    @Autowired
//    private QualityPrintLogService qualityPrintLogService;
//
//    @Autowired
//    private QualityPrintService qualityPrintService;
//
//    @Autowired
//    private PrinterService printerService;
//
//    @Autowired
//    private DictionaryItemService dictionaryItemService;
//
//    @Autowired
//    private QualityPrintBarService qualityPrintBarService;
//
//    @Autowired
//    private ProductionPaintingLineDetailService productionPaintingLineDetailService;
//
//    @Autowired
//    ModelMapper modelMapper;
//
//    @ApiOperation(value = "根据晶段编号获取上一段检验信息")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "sectionNo", value = "晶段编号", paramType = "path", dataType = "String"),
//    })
//    @RequestMapping(value = "/getLastInspectInfo/{sectionNo}", method = RequestMethod.GET)
//    public @ResponseBody
//    Result getLastInspectInfo(@PathVariable String sectionNo) {
//        InspectData lastInspectDataInfo = inspectService.getLastInspectInfo(sectionNo);
////        Map<String, Inspect> map = inspectService.getPreAndNextInspectData(sectionNo);
//        //判断单晶是否分段，以及是否已经入库
//        ReCut reCut = fbReCutService.findBySectionNo(sectionNo);
//        if (reCut != null) {
//            return ResultGenerator.fail("该单晶已分段！");
//        }
//        List<TurnstoreOutItem> turnstoreOutItems = turnstoreOutItemService.findByTypeAndStateAndSectionNoOrderByIdDesc("退料到圆棒", "已出库", sectionNo);
//        TurnstoreInItem turnstoreInItem = turnstoreInItemService.getLastByTypeAndStateAndSectionNoOrderByIdDesc("圆棒入库", "已入库", sectionNo);
//        if (turnstoreInItem != null) {
//            if (!turnstoreOutItems.isEmpty()) {
//                TurnstoreOutItem turnstoreOutItem = turnstoreOutItems.get(0);
//                if (turnstoreInItem.getTime().compareTo(turnstoreOutItem.getTime()) > 0) {
//                    return ResultGenerator.fail("该单晶已入库！");
//                }
//            } else {
//                return ResultGenerator.fail("该单晶已入库！");
//            }
//        }
//
//        return ResultGenerator.success(lastInspectDataInfo);
//    }
//
//    @ApiOperation(value = "根据晶段编号获取前后段检验信息")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "sectionNo", value = "晶段编号", paramType = "path", dataType = "String"),
//    })
//    @RequestMapping(value = "/getPreAndNextInspectInfo/{sectionNo}", method = RequestMethod.GET)
//    public @ResponseBody
//    Result getPreAndNextInspectInfo(@PathVariable String sectionNo) {
//        //判断单晶是否分段，以及是否已经入库
//        ReCut reCut = fbReCutService.findBySectionNo(sectionNo);
//        if (reCut != null) {
//            return ResultGenerator.fail("该单晶已分段！");
//        }
//        List<TurnstoreOutItem> turnstoreOutItems = turnstoreOutItemService.findByTypeAndStateAndSectionNoOrderByIdDesc("退料到圆棒", "已出库", sectionNo);
//        TurnstoreInItem turnstoreInItem = turnstoreInItemService.getLastByTypeAndStateAndSectionNoOrderByIdDesc("圆棒入库", "已入库", sectionNo);
//        if (turnstoreInItem != null) {
//            if (!turnstoreOutItems.isEmpty()) {
//                TurnstoreOutItem turnstoreOutItem = turnstoreOutItems.get(0);
//                if (turnstoreInItem.getTime().compareTo(turnstoreOutItem.getTime()) > 0) {
//                    return ResultGenerator.fail("该单晶已入库！");
//                }
//            } else {
//                return ResultGenerator.fail("该单晶已入库！");
//            }
//        }
//        Map<String, InspectData> map = inspectService.getPreAndNextInspectData(sectionNo);
//
//        return ResultGenerator.success(map);
//    }
//
//    @ApiOperation(value = "创建检验")
//    @RequestMapping(value = "/create", method = RequestMethod.POST)
//    public @ResponseBody
//    Result create(@RequestBody @Valid InspectData inspectData) {
//
//        String sectionNo = inspectData.getSectionNo();
//        if (StringUtils.isBlank(sectionNo)) {
//            return ResultGenerator.fail("晶段编号不能为空！");
//        }
//        ProductionPaintingLineDetail detail = productionPaintingLineDetailService.findBySegmentNo(sectionNo);
//        if (detail == null) {
//            return ResultGenerator.fail("晶段编号错误，画线信息不存在！");
//        }
//
//        //判断单晶是否分段，以及是否已经入库
//        ReCut reCut = fbReCutService.findBySectionNo(sectionNo);
//        if (reCut != null) {
//            return ResultGenerator.fail("该单晶已分段！");
//        }
//        List<TurnstoreOutItem> turnstoreOutItems = turnstoreOutItemService.findByTypeAndStateAndSectionNoOrderByIdDesc("退料到圆棒", "已出库", sectionNo);
//        TurnstoreInItem turnstoreInItem = turnstoreInItemService.getLastByTypeAndStateAndSectionNoOrderByIdDesc("圆棒入库", "已入库", sectionNo);
//        if (turnstoreInItem != null) {
//            if (!turnstoreOutItems.isEmpty()) {
//                TurnstoreOutItem turnstoreOutItem = turnstoreOutItems.get(0);
//                if (turnstoreInItem.getTime().compareTo(turnstoreOutItem.getTime()) > 0) {
//                    return ResultGenerator.fail("该单晶已入库！");
//                }
//            } else {
//                return ResultGenerator.fail("该单晶已入库！");
//            }
//        }
//        //入库长度=圆棒长度-细减长-崩晶线
////        inspect.setWareHouseLength(Utlis.getInstoreLength(inspect.getActualLength(), inspect.getFineCutLength(), inspect.getCollapseLine()));
//
//        inspectData.setInspector(BaseContextHandler.getUsername());
//        try {
//            inspectService.save(inspectData, 1);
//        } catch (Exception e) {
//            return ResultGenerator.fail("录入异常：" + e.getMessage());
//        }
//
//        return ResultGenerator.success();
//    }
//
//    @ApiOperation(value = "检验详细信息")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "id", value = "检验ID", paramType = "path", dataType = "Integer"),
//    })
//    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
//    public Result preUpdate(@PathVariable Long id) {
//        InspectData inspectData = inspectService.get(id);
//        return ResultGenerator.success(inspectData);
//    }
//
//    @ApiOperation(value = "更新检验")
//    @PostMapping(value = "/update")
//    public @ResponseBody
//    Result update(@Valid @RequestBody InspectData inspectData) {
//        inspectData.setInspector(BaseContextHandler.getUsername());
//
//        try {
//            inspectService.save(inspectData, 2);
//        } catch (Exception e) {
//            return ResultGenerator.fail("编辑异常：" + e.getMessage());
//        }
//
//        return ResultGenerator.success();
//    }
//
//    @ApiOperation(value = "修改检验等级")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "id", value = "检验ID", paramType = "query", dataType = "Long"),
//            @ApiImplicitParam(name = "productLevel", value = "产品等级", paramType = "query", dataType = "String")
//    })
//    @GetMapping(value = "/updateLevel")
//    public @ResponseBody
//    Result updateLevel(Long id, String productLevel) {
//        InspectData inspectData = inspectService.get(id);
//        if (inspectData != null) {
//            inspectData.setProductLevel(productLevel);
//            inspectService.saveOrUpdate(inspectData);
//        }
//        return ResultGenerator.success();
//    }
//
//    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
//    public @ResponseBody
//    Result delete(@PathVariable Long id) {
//        InspectData inspectData = inspectService.get(id);
//        inspectService.delete(id);
//        return ResultGenerator.success();
//    }
//
//    @ApiOperation(value = "删除检验")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "ids", value = "检验ID", dataType = "string", paramType = "query")
//    })
//    @RequestMapping(value = "/delete", method = RequestMethod.POST)
//    public @ResponseBody
//    Result deleteMany(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
//        for (int i = 0; i < ids.length; i++) {
//            InspectData inspectData = inspectService.get(ids[i]);
//            inspectService.delete(inspectData.getId());
//        }
//
//        return ResultGenerator.success();
//    }
//
//    @ApiOperation(value = "分页查询检验列表")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
//            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
//            @ApiImplicitParam(name = "search_LIKE_sectionNo", value = "晶段编号", dataType = "string", paramType = "query"),
//            @ApiImplicitParam(name = "search_LIKE_crystalNo", value = "单晶编号", dataType = "string", paramType = "query")
//    })
//    @RequestMapping(value = "/list", method = RequestMethod.GET)
//    public Result<ResponsePage<InspectData>> list(ServletRequest request, RequestPage page) {
//        Specification<InspectData> specification = DynamicSpecifications.bySearchFilter(request, InspectData.class);
//        page.setOrderField("inspectTime");
//        page.setOrderDirection(RequestPage.ORDER_DIRECTION_DESC);
//        List<InspectData> inspectData = inspectService.findByExample(specification, page);
//
//        ResponsePage responsePage = new ResponsePage(inspectData, page.getTotal());
//
//        return ResultGenerator.success(responsePage);
//    }
//
//    @ApiOperation(value = "分页查询检验列表")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
//            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
//            @ApiImplicitParam(name = "search_LIKE_sectionNo", value = "晶段编号", dataType = "string", paramType = "query"),
//            @ApiImplicitParam(name = "search_LIKE_crystalNo", value = "单晶编号", dataType = "string", paramType = "query")
//    })
//    @RequestMapping(value = "/listNew", method = RequestMethod.GET)
//    public Result<ResponsePage<InspectData>> listNew(RequestPage page, String sectionNo, String crystalNo, String startTime, String endTime, String inspector, String code, String checkResult) {
//        Integer rows = page.getRows();
//        Long start = Long.valueOf(page.getPage() - 1) * rows;
//        List<InspectData> list = inspectService.getListNew(sectionNo, crystalNo, startTime, endTime, inspector, code, checkResult, start, rows);
//        List<Map<String, Object>> count = inspectService.getListNewCount(sectionNo, crystalNo, startTime, endTime, inspector, code, checkResult);
//        ResponsePage responsePage = new ResponsePage(list, Long.valueOf(count.get(0).get("count").toString()));
//        return ResultGenerator.success(responsePage);
//    }
//
//    @ApiOperation(value = "检验详细信息")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "id", value = "检验ID", paramType = "path", dataType = "Integer"),
//    })
//    @RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
//    public Result view(@PathVariable Long id) {
//        InspectData inspectData = inspectService.get(id);
//        return ResultGenerator.success(inspectData);
//    }
//
//
//    @ApiOperation(value = "根据晶段编号获取样片数据")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "sectionNo", value = "晶段编号", paramType = "query", dataType = "String")
//    })
//    @RequestMapping(value = "/getPieceList", method = RequestMethod.GET)
//    public Result getPieceList(String sectionNo) {
//
////        Map<String, String> pieceNoMap = sectionDetailService.findPieceNosNew(sectionNo);
//        Map<String, String> pieceNoMap = sectionDetailService.getPieceNoBySectionNo(sectionNo);
////        String head = sectionDetailService.getHeadPieceSectionBySectionNo(sectionNo, 1);
////        String tail = sectionDetailService.getHeadPieceSectionBySectionNo(sectionNo, -1);
//
//        String head = pieceNoMap.get("head");
//        String tail = pieceNoMap.get("tail");
//
//        Map<String, PieceCheck> pieceCheckMap = new HashMap<>();
//
//        if (StringUtils.isNotBlank(head)) {
//            PieceCheck pieceCheck = pieceCheckService.getByPieceNo(head);
//            pieceCheckMap.put("head", pieceCheck);
//        }
//        if (StringUtils.isNotBlank(tail)) {
//            PieceCheck pieceCheck = pieceCheckService.getByPieceNo(tail);
//            pieceCheckMap.put("tail", pieceCheck);
//        }
//
//        return ResultGenerator.success(pieceCheckMap);
//    }
//
//    @ApiOperation(value = "导入晶段检验数据（产品等级）")
//    @PostMapping("/excelImport")
//    public Result excelImport(MultipartFile file) {
//
//        try {
//            List<String> sectionNos = inspectService.readExcelFile(file);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ResultGenerator.fail(e.getMessage());
//        }
//        return ResultGenerator.success();
//    }
//
//    @ApiOperation(value = "导入晶段检验数据")
//    @PostMapping("/resultsImport")
//    public Result resultsImport(MultipartFile file) {
//
//        try {
//            List<String> sectionNos = inspectService.readResultsImport(file);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ResultGenerator.fail(e.getMessage());
//        }
//        return ResultGenerator.success();
//    }
//
//    //获取IP
//    public static String getIpAddress(HttpServletRequest request) {
//        String ip = request.getHeader("x-forwarded-for");
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("Proxy-Client-IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("WL-Proxy-Client-IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("HTTP_CLIENT_IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getRemoteAddr();
//        }
//        return ip;
//    }
//
//
//    @ApiOperation(value = "打印记录")
//    @PostMapping(value = "/qualityPrintLog")
//    public @ResponseBody
//    Result qualityPrintLog(@Valid @RequestBody List<String> list) {
//        String userName = BaseContextHandler.getUsername();
//        Date nowDate = new Date();
//        List<QualityPrintLog> logList = new ArrayList<>();
//        for (String str : list) {
//            if (str != null && !"".equals(str)) {
//                QualityPrintLog entity = new QualityPrintLog();
//                entity.setPrintTime(nowDate);
//                entity.setSectionNo(str);
//                entity.setUserName(userName);
//                logList.add(entity);
//            }
//        }
//        if (logList != null && logList.size() > 0) {
//            qualityPrintLogService.saveAll(logList);
//        } else {
//            return ResultGenerator.fail("打印内容错误,无数据！");
//        }
//        return ResultGenerator.success();
//    }
//
//    @ApiOperation(value = "根据单晶编号LIST获取单晶检验信息")
//    @RequestMapping(value = "/batchPrint", method = RequestMethod.POST)
//    public @ResponseBody
//    Result batchPrint(@RequestBody @Valid List<String> sectionNoItems) {
//        List<QualityPrint> resultList = new ArrayList<>();
//        if (sectionNoItems == null || sectionNoItems.size() == 0) {
//            return ResultGenerator.success(resultList);
//        }
//        String sectionNos = String.join(",", sectionNoItems);
//        Date nowDate = new Date();
//        Calendar caNow = Calendar.getInstance();
//        caNow.setTime(nowDate);
//        caNow.add(Calendar.DATE, -30);
//        //resultList = qualityPrintService.getInfoBatch(sectionNos,caNow.getTime());
//        resultList = qualityPrintService.getInfoBatchNew(sectionNoItems);
////        List<QualityPrint> resultListNew = new ArrayList<>();
////        for (String str : sectionNoItems) {
////            for (QualityPrint qualityPrint : resultList) {
////                if (qualityPrint != null && qualityPrint.getSectionNo() != null && qualityPrint.getSectionNo().equals(str)) {
////                    resultListNew.add(qualityPrint);
////                    break;
////                }
////            }
////        }
//        //从字典表中查询特殊圆棒等级
//        List<String> specialRoundLevels = dictionaryItemService.findValueByThemeValueAndEnable("特殊圆棒产品等级", true);
//        List<QualityPrint> resultListNew = new ArrayList<>();
//        for (String str : sectionNoItems) {
//            for (QualityPrint qualityPrint : resultList) {
//                if (qualityPrint != null && qualityPrint.getSectionNo() != null && qualityPrint.getSectionNo().equals(str)) {
//                    if (specialRoundLevels.contains(qualityPrint.getProductLevelSecond())) {
//                        qualityPrint.setIsSpecialRoundLevel(1);
//                    }
//                    resultListNew.add(qualityPrint);
//                    break;
//                }
//            }
//        }
//        return ResultGenerator.success(resultListNew);
//    }
//
//
//    // TODO 需要调整到PrintService 接口
//    @ApiOperation(value = "批量打印合格证条码")
//    @RequestMapping(value = "/batchPrintBar", method = RequestMethod.POST)
//    public @ResponseBody
//    Result batchPrintBar(HttpServletRequest request, @RequestBody @Valid List<String> sectionNoItems) {
//        List<QualityPrintBar> resultList = new ArrayList<>();
//        if (sectionNoItems == null || sectionNoItems.size() == 0) {
//            return ResultGenerator.success(resultList);
//        }
////        String sectionNos = String.join(",", sectionNoItems);
////        resultList = qualityPrintBarService.getInfoBatchBar(sectionNos);
//        resultList = qualityPrintBarService.getInfoBatchBarNew(sectionNoItems);
//        List<QualityPrintBar> resultListNew = new ArrayList<>();
//        for (String str : sectionNoItems) {
//            for (QualityPrintBar qualityPrintBar : resultList) {
//                if (qualityPrintBar != null && qualityPrintBar.getSectionNo() != null && qualityPrintBar.getSectionNo().equals(str)) {
//                    resultListNew.add(qualityPrintBar);
//                    break;
//                }
//            }
//        }
//        if (resultListNew == null || resultListNew.size() == 0) {
//            return ResultGenerator.fail("查询晶段信息失败");
//        }
//        String url = request.getHeader("X-Real-IP");
//        //String url = getIpAddress(request);
//        //url = "10.60.120.58";
//        String printUrl = "";
//        Printer printer = null;
//        if (StringUtils.isNotBlank(url)) {
//            printer = printerService.getByPositionCode(url);
//        }
//        if (printer == null) {
//            return ResultGenerator.fail("未找到配置打印机");
//        }
//        printUrl = printer.getUrl();
//        String jsonString = "";
//        try {
//            jsonString = "JsonData=" + URLEncoder.encode(JSONObject.toJSONString(resultListNew), "GB2312");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//            return ResultGenerator.fail("打印数据转换失败");
//        }
//        String result = "";
//        try {
//            result = HTTPRequestUtil.get(printUrl, jsonString);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ResultGenerator.fail("打印异常");
//        }
//        Map<String, Object> returnMap = new HashMap<>();
//        if (StringUtils.isBlank(result)) {
//            returnMap.put("status", 0);
//            returnMap.put("msg", "打印失败！");
//        } else {
//            JSONObject jsonObject = JSONObject.parseObject(result);
//            Integer jcode = jsonObject.getInteger("code");
//            String jmsg = jsonObject.getString("msg");
//            returnMap.put("status", jcode);
//            returnMap.put("msg", jmsg);
//        }
//        if (returnMap.get("status") != null) {
//            Integer status = (Integer) returnMap.get("status");
//            if (0 == status) {
//                String msg = (String) returnMap.get("msg");
//                return ResultGenerator.fail(msg);
//            }
//        }
//        return ResultGenerator.success();
//    }
//
//}
