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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.entity.SysLog;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.base.system.service.SysLogService;
import com.sw.mes.core.api.system.FbFeignClients;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.exception.BusinessException;
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.inspect.entity.YbInspectData;
import com.sw.mes.inspect.service.YbInspectDataService;
import com.sw.mes.issue.dto.FlsYbIssueRecordDto;
import com.sw.mes.issue.service.YbIssueRecordService;
import com.sw.mes.utils.StringUtils;
import com.sw.mes.yb.fls.dto.*;
import com.sw.mes.yb.fls.entity.KfReturnMaterial;
import com.sw.mes.yb.fls.service.FlsToMesService;
import com.sw.mes.yb.fls.service.KfReturnMaterialService;
import com.sw.mes.yb.mcs.dto.McsFbInventoryDto;
import com.sw.mes.yb.turnstore.service.ProductionBindingTrayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: GaoXinJian
 * @Date: 2022-01-11 14:51
 */
@RestController
@Api(description = "Fls调用Mes接口")
@RequestMapping("/flsToMesController")
@EnableAsync
public class FlsToMesController {
    @Autowired
    FlsToMesService flsToMesService;

    @Autowired
    YbInspectDataService inspectDataBaseService;

    @Autowired
    private KfReturnMaterialService kfReturnMaterialService;

    @Autowired
    private FbFeignClients fbFeignClients;

    @Autowired
    DictionaryItemService dictionaryItemService;

    @Autowired
    SysLogService sysLogService;

    @Autowired
    ProductionBindingTrayService productionBindingTrayService;

    @Autowired
    YbIssueRecordService ybIssueRecordService;

    @ApiOperation(value = "圆棒进入分选口")
    @PostMapping("/ybEntersSortingPort")
    public Result<YbEntersSortingPortDto> ybEntersSortingPort(
            @RequestBody ybEntersSortingPortRequestDto ybEntersSortingPortRequestDto) {
        try {

            return ResultGenerator
                    .success(flsToMesService.ybEntersSortingPort(ybEntersSortingPortRequestDto.getTrayCode()));
        } catch (BusinessException b) {
            return ResultGenerator.message(201, b.getMessage(), null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.fail(e.getMessage());
        }
    }

    // AGV发料
    @ApiOperation(value = "圆棒发料自动过站")
    @PostMapping("/ybSortingPortUpload")
    public Result ybSortingPortUpload(@RequestBody YbSortingPortUploadDto ybSortingPortUploadDto) {

        return flsToMesService.ybSortingPortUpload(ybSortingPortUploadDto);
    }

    @ApiOperation(value = "晶段信息获取接口")
    @PostMapping("/getSectionInfo")
    public Result<SectionInfoDto> getSectionInfo(@RequestBody GetSectionInfoDto getSectionInfoDto) {
        YbInspectData inspectDataBase = inspectDataBaseService.findBySectionNo(getSectionInfoDto.getSectionNo());
        if (inspectDataBase == null) {
            throw new RuntimeException("检验数据不存在");
        }
        SectionInfoDto sectionInfoDto = new SectionInfoDto();
        DecimalFormat df = new DecimalFormat("###");
        if (inspectDataBase.getSticksCount() == 1) {
            sectionInfoDto.setActualLength(
                    inspectDataBase.getActualLength() == null ? null : df.format(inspectDataBase.getActualLength()));
            sectionInfoDto.setIsJoin(1);
        } else {
            sectionInfoDto.setActualLength(inspectDataBase.getSpellBarLength() == null ? null
                    : df.format(inspectDataBase.getSpellBarLength()));
            sectionInfoDto.setIsJoin(2);
        }
        sectionInfoDto.setDiameterMax(
                inspectDataBase.getDiameterMax() == null ? null : df.format(inspectDataBase.getDiameterMax()));
        sectionInfoDto.setDiameterMin(
                inspectDataBase.getDiameterMax() == null ? null : df.format(inspectDataBase.getDiameterMax()));
//        sectionInfoDto.setAvgDiameter(inspectDataBase.getAvgDiameter() == null ? null : inspectDataBase.getAvgDiameter().toString());
        Result<String> sideLengthResult = fbFeignClients.getFbSideLength(getSectionInfoDto.getSectionNo());
        String sideLength = null;
        if (sideLengthResult.getCode() == ResultCode.SUCCESS.getCode()) {
            sideLength = sideLengthResult.getData();
        }
        if (sideLength == null) {
            List<DictionaryItem> dictionaryItems = dictionaryItemService
                    .findByThemeValueAndEnable("specificationOption", true);
            for (DictionaryItem dictionaryItem : dictionaryItems) {
                if (dictionaryItem.getValue() != null
                        && dictionaryItem.getValue().contains(inspectDataBase.getProductTypeSecond())) {
                    String productType = dictionaryItem.getValue();
                    String[] split = productType.split("\\*");
                    if (split.length >= 2) {
                        sideLength = split[1];
                    }
                }
            }

        }
        sectionInfoDto.setSideLength(sideLength);
        sectionInfoDto.setIsBevel(inspectDataBase.getIsBevel());
//        sectionInfoDto.setProductTypeSecond(inspectDataBase.getConductiveType());
        return ResultGenerator.success(sectionInfoDto);
    }

    @ApiOperation(value = "开方退料接口")
    @PostMapping("/kfReturnMaterial")
    public Result create(
            @RequestBody @Valid @ApiParam(value = "KfReturnMaterial对象") KfReturnMaterialDto kfReturnMaterialDto,
            BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        KfReturnMaterial kfReturnMaterial = JSONObject.parseObject(JSONObject.toJSONString(kfReturnMaterialDto),
                KfReturnMaterial.class);
        kfReturnMaterial.setStatus("0");
        kfReturnMaterial.setCreateTime(new Date());
        kfReturnMaterialService.saveOrUpdate(kfReturnMaterial);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "拼棒完成报告接口")
    @PostMapping("/joinCircleFinish")
    public Result joinCircleFinish(
            @RequestBody @Valid @ApiParam(value = "JoinCircleFinishDto对象") JoinCircleFinishDto joinCircleFinishDto,
            BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            return flsToMesService.joinCircleFinish(joinCircleFinishDto);
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "fls托盘自动解绑接口")
    @PostMapping("/trayAutoUnBinding")
    public Result trayAutoUnBinding(@RequestBody TrayAutoUnBinding trayAutoUnBinding) {
        trayAutoUnBinding
                .setPoint(StringUtils.isNotBlank(trayAutoUnBinding.getPoint()) ? trayAutoUnBinding.getPoint() : "");
        trayAutoUnBinding
                .setReason(StringUtils.isNotBlank(trayAutoUnBinding.getReason()) ? trayAutoUnBinding.getReason() : "");
        flsToMesService.trayAutoUnBinding(trayAutoUnBinding, "SMCS");
        return ResultGenerator.success();
    }

    @ApiOperation(value = "自动组托入库补数据")
    @GetMapping("/autoInitiateReceipt")
    public Result autoInitiateReceipt(@RequestParam String sectionNos) {
        if (StringUtils.isNotBlank(sectionNos)) {
            String[] split = sectionNos.split(",");
            if (split.length > 0) {
                for (String s : split) {
                    String trim = s.trim();
                    flsToMesService.autoInitiateReceipt(trim);
                }
            }
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "自动组托入库补数据-无限制")
    @GetMapping("/autoInitiateReceiptData")
    public Result autoInitiateReceiptData(@RequestParam String sectionNos) {
        if (StringUtils.isNotBlank(sectionNos)) {
            String[] split = sectionNos.split(",");
            if (split.length > 0) {
                for (String s : split) {
                    String trim = s.trim();
                    flsToMesService.autoInitiateReceiptData(trim);
                }
            }
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "验证是否可以拼棒")
    @PostMapping("/spellValidation")
    public Result spellValidation(
            @RequestBody @Valid @ApiParam(value = "SpellValidationDto对象") SpellValidationDto spellValidationDto,
            BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            return flsToMesService.spellValidation(spellValidationDto);
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "方棒退料晶段与托盘绑定")
    @PostMapping(value = "/trayBinding")
    public Result trayBinding(@RequestBody BindingDto bindingDto) {
        try {
            return flsToMesService.trayBinding(bindingDto);
        } catch (Exception e) {
            return ResultGenerator.message(500, "系统异常:" + e.getMessage(), null);
        }
    }

    @ApiOperation(value = "方棒打托去向 0打托，1NG库")
    @PostMapping(value = "/matchMakeTrayRule")
    public Result matchMakeTrayRule(@RequestBody BindingDto bindingDto) {
        try {
//            return flsToMesService.matchMakeTrayRule(bindingDto);
            return flsToMesService.matchMakeTrayRuleV2(bindingDto);
        } catch (Exception e) {
            return ResultGenerator.message(500, "系统异常:" + e.getMessage(), null);
        }
    }

    @ApiOperation(value = "fls中断打托回调接口")
    @PostMapping(value = "/suspendTrayRule")
    public Result suspendTrayRule(@RequestBody List<McsFbInventoryDto> fbInventoryDto) {
        try {
            return flsToMesService.suspendTrayRule(fbInventoryDto);
        } catch (Exception e) {
            return ResultGenerator.message(500, "系统异常:" + e.getMessage(), null);
        }
    }

    @ApiOperation(value = "根据单晶编号查询方棒出库记录")
    @PostMapping(value = "/queryMcsSquareLog")
    public Result queryMcsSquareLog(@RequestBody BindingDto bindingDto) {
        try {
            return flsToMesService.queryMcsSquareLog(bindingDto);
        } catch (Exception e) {
            return ResultGenerator.message(500, "系统异常:" + e.getMessage(), null);
        }
    }

    @ApiOperation(value = "FLS下发单晶编号至MES,获取单晶编号、托位号、回收料分类名称")
    @PostMapping("/sendSectionForInfo")
    public Result sendSectionForInfo(@RequestBody SectionRequestDto gainSectionRequestDto) {
        try {
            return flsToMesService.sendSectionForInfo(gainSectionRequestDto);
        } catch (Exception e) {
            return ResultGenerator.message(500, "系统异常:" + e.getMessage(), null);
        }
    }

    @ApiOperation(value = "边皮-回收料打托完成信息上传")
    @PostMapping(value = "/recycledMaterialUpload")
    public Result recycledMaterialUpload(@RequestBody @Valid RecycledMaterialUploadDto recycledMaterialUploadDto,
            BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        try {
            return flsToMesService.recycledMaterialUpload(recycledMaterialUploadDto);
        } catch (Exception e) {
            return ResultGenerator.message(500, "系统异常:" + e.getMessage(), null);
        }
    }

    @ApiOperation(value = "fls回收料打码信息上传(记录日志)")
    @PostMapping(value = "/recycledMaterialCodingUpload")
    public Result recycledMaterialCodingUpload(@RequestBody @Valid RecycledMaterialToAGVDto recycledMaterialUploadDto,
            BindingResult bindingResult) {
        SysLog sysLog = new SysLog();
        sysLog.setContent(JSON.toJSONString(recycledMaterialUploadDto));
        sysLog.setCreateTime(new Date());
        sysLog.setCreateUserId(BaseContextHandler.getUserID());
        sysLog.setCreateUserName(BaseContextHandler.getUsername());
        sysLog.setMethodName("recycledMaterialCodingUpload");
        sysLog.setName("fls回收料打码信息上传");
        sysLog.setResult("");
        sysLog.setType("info");
        sysLog.setStatus(200);
        sysLogService.save(sysLog);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "fls自动解绑载具车号")
    @PostMapping(value = "/flsUnbindingPailNum")
    public Result flsUnbindingPailNum(@RequestBody @Valid flsUnPailNumRequestDto flsUnPailNumRequestDto,
            BindingResult bindingResult) {
        productionBindingTrayService.flsUnbindingPailNum(flsUnPailNumRequestDto.getPailNum());
        return ResultGenerator.success();
    }

    @ApiOperation(value = "通过托号获取圆棒发料记录")
    @GetMapping("/queryYbIssueRecord")
    public Result queryYbIssueRecord(@RequestParam String trayNo) {
        if(StringUtils.isBlank(trayNo)) {
            return ResultGenerator.fail("托号不是为空！");
        }
        return ResultGenerator.success(ybIssueRecordService.queryByTrayNo(trayNo));
    }

    @ApiOperation(value = "通过车号获取圆棒发料记录")
    @GetMapping("/queryYbIssueRecordByBranchCode")
    public Result<List<FlsYbIssueRecordDto>> queryYbIssueRecordByBranchCode(@RequestParam String branchCode) {
        if(StringUtils.isBlank(branchCode)) {
            return ResultGenerator.fail("车号不是为空！");
        }
        return ResultGenerator.success(ybIssueRecordService.queryByBranchCode(branchCode));
    }

    @ApiOperation(value = "FLS发送车号发料信号")
    @GetMapping("/sendBranchCodeToYbIssueRecord")
    public Result sendBranchCodeToYbIssueRecord(@RequestParam String branchCode, @RequestParam Integer sendStatus) {
        if (StringUtils.isBlank(branchCode)) {
            return ResultGenerator.fail("车号不是为空！");
        }
        //sendStatus : 1 已发料
        if (null != sendStatus && 1 != sendStatus) {
            return ResultGenerator.fail("发料信号标识异常！");
        }
        return ResultGenerator.success(ybIssueRecordService.sendBranchCodeToYbIssueRecord(branchCode, sendStatus));
    }
}