package com.sw.mes.yb.pad.controller;


import com.sw.mes.core.api.system.FbFeignClients;
import com.sw.mes.core.dto.CooperateDataInfoDto;
import com.sw.mes.core.response.ResponsePage;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultCode;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.DynamicSpecifications;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.inspect.entity.YbInspectData;
import com.sw.mes.inspect.service.YbInspectDataService;
import com.sw.mes.yb.pad.dto.RecutDto;
import com.sw.mes.yb.pad.entity.ProductionBackCuttingRecord;
import com.sw.mes.yb.pad.entity.ProductionPaintingLineDetail;
import com.sw.mes.yb.pad.entity.ReCut;
import com.sw.mes.yb.pad.entity.SectionNoDetail;
import com.sw.mes.yb.pad.service.FbReCutService;
import com.sw.mes.yb.pad.service.ProductionPaintingLineDetailService;
import com.sw.mes.yb.pad.service.ProductionRecutService;
import com.sw.mes.yb.pad.service.SectionNoDetailService;
import com.sw.mes.yb.production.service.RecycledMaterialManageDetailService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/OperateReCut")
@Slf4j
@Api(description = "方棒返切画线接口")
public class FbReCutController {

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private FbReCutService fbReCutService;

    @Autowired
    private RecycledMaterialManageDetailService recycledMaterialManageDetailService;

    @Autowired
    private FbFeignClients fbFeignClients;

    @Autowired
    private YbInspectDataService ybInspectDataService;

    @Autowired
    private ProductionRecutService productionRecutService;
    @Autowired
    private ProductionPaintingLineDetailService productionPaintingLineDetailService;
    @Autowired
    private SectionNoDetailService sectionNoDetailService;

    @ApiOperation(value = "分页查询规格返切画线列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_startTime", value = "划线开始时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "search_LTE_endTime", value = "划线结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_segmentNo", value = "晶段编号", dataType = "string", paramType = "query")
    })
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<ResponsePage<ReCut>> list(ServletRequest request, RequestPage page) {
        Specification<ReCut> specification = DynamicSpecifications.bySearchFilter(request, ReCut.class);
        List<ReCut> reCuts = fbReCutService.findByExample(specification, page);
        ResponsePage responsePage = new ResponsePage(reCuts, page.getTotal());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "创建不合格返切画线")
    @PostMapping(value = "/create")
    public Result create(@RequestBody @Valid RecutDto recutDto) {
        return fbReCutService.saveSegmentNoNew(recutDto);
    }

    @ApiOperation(value = "删除方棒返切记录")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
        for (Long id : ids) {
            fbReCutService.deleteReCut(id);
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "根据托号获取方棒编号")
    @GetMapping("/findSectionNosByTrayNo")
    public Result<Map<String, Object>> findSectionNosByTrayNo(@RequestParam String trayNo) {
        return fbReCutService.findByTrayNo(trayNo);
    }

    @ApiOperation(value = "根据方棒编号直接获取方棒信息")
    @GetMapping("/findInfoByFbNo")
    public Result<BigDecimal> getSectionNoFbInfo(@RequestParam String sectionNoFb) {
        return fbReCutService.findLengthBySecitonNo(sectionNoFb);
    }

    @ApiOperation(value = "根据方棒编号直接获取方棒信息，生成晶段编号")
    @PostMapping("/getSectionNoFbRecutInfo")
    public Result<RecutDto> getSectionNoFbRecutInfo(@RequestBody RecutDto recutDto) {
        return fbReCutService.getSectionNoFbRecutInfoNew(recutDto);
    }

    @ApiOperation(value = "根据方棒编号直接获取反切记录")
    @GetMapping("/getReCutBySectionNoFb")
    public Result<ReCut> getReCut(@RequestParam String sectionNoFb) {
        return fbReCutService.getReCutBySectionNo(sectionNoFb);
    }


    @ApiOperation(value = "配棒信息-生成编号、创建画线信息")
    @PostMapping("/getCooperateInfo")
    public Result getCooperateInfo(@RequestBody CooperateDataInfoDto cooperateDataInfoDto) {
        return fbReCutService.getCooperateInfo(cooperateDataInfoDto);
    }

    @ApiOperation(value = "校验晶编是否存在于反切记录或检验数据或余料详情里")
    @GetMapping("/checkFbSection")
    public Result queryInfoBySurplusCode(@RequestParam String kostl, @RequestParam String sectionNofb) {
        //校验是否存在于回收料详情
        List<String> surplusCodes = new ArrayList<>();
        surplusCodes.add(sectionNofb);
        List<String> usedRecycleNos = recycledMaterialManageDetailService.getDetailByRecycleNos(surplusCodes);
        if (usedRecycleNos != null && !usedRecycleNos.isEmpty() && usedRecycleNos.size() > 0) {
            return ResultGenerator.fail("单晶编码:" + surplusCodes + "已被组托!");
        }
        if ("3".equals(kostl)) {
            //截断,查询圆棒检验数据或者圆棒反切数据
            YbInspectData bySectionNo = ybInspectDataService.getSectionNo(sectionNofb);
            if (null == bySectionNo) {
                ProductionBackCuttingRecord cuttingRecord = productionRecutService.findTopBySegmentNoOrderByIdDesc(sectionNofb);
                if (null == cuttingRecord) {
                    ProductionPaintingLineDetail detail = productionPaintingLineDetailService.findBySegmentNo(sectionNofb);
                    if (null == detail) {
                        SectionNoDetail sectionNoDetail = sectionNoDetailService.findBySectionNo(sectionNofb);
                        if (null == sectionNoDetail) {
                            return ResultGenerator.fail("晶编:" + sectionNofb + "在圆棒检验或圆棒反切数据或划线明细或晶段详情信息追溯表中不存在!");
                        } else {
                            return ResultGenerator.success();
                        }
                    } else {
                        return ResultGenerator.success();
                    }
                } else {
                    return ResultGenerator.success();
                }
            } else {
                return ResultGenerator.success();
            }

        } else if ("4".equals(kostl)) {
            //刀剖
            ReCut reCutInfoBySectionNo = fbReCutService.findReCutInfoBySectionNo(sectionNofb);
            if (null == reCutInfoBySectionNo) {
                Result dataByFbSectionNo = fbFeignClients.findDataByFbSectionNo(sectionNofb);
                if (ResultCode.SUCCESS.getCode() != dataByFbSectionNo.getCode()) {
                    return ResultGenerator.fail("查询方棒检验数据异常!");
                } else {
                    if (null == dataByFbSectionNo.getData()) {
                        return ResultGenerator.fail("晶编:" + sectionNofb + "在方棒检验或方棒反切数据中不存在!");
                    }
                }
            }
        }
        return ResultGenerator.success();
    }

    public ReCut fromDto(RecutDto dto) {
        return modelMapper.map(dto, ReCut.class);
    }
}
