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

import com.alibaba.fastjson.JSONObject;

import com.sw.mes.core.enums.EnumValues;
import com.sw.mes.core.enums.EnumValuesFactory;
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.ResultCode;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.DynamicSpecifications;
import com.sw.mes.core.utils.EasyExcelUtils;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.utils.StringUtils;
import com.sw.mes.base.workinprocess.dto.CurrentWipStorageStatusDto;
import com.sw.mes.base.workinprocess.entity.WipStorage;
import com.sw.mes.yb.pc.dto.FbjoinDto;
import com.sw.mes.yb.pc.dto.SectionDto;
import com.sw.mes.yb.pc.dto.StickTogetherParam;
import com.sw.mes.yb.pc.dto.TrayBindingRecordDto;
import com.sw.mes.yb.pc.entity.Fbjoin;
import com.sw.mes.yb.pc.entity.Section;
import com.sw.mes.yb.pc.entity.SpellInfo;
import com.sw.mes.yb.pc.entity.TrayBindingRecord;
import com.sw.mes.yb.pc.service.SectionService;
import com.sw.mes.yb.pc.service.SpellInfoService;
import com.sw.mes.yb.pc.service.TrayBindingRecordService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/ybJoin")
@Slf4j
@Api(description = "粘圆棒接口")
public class YbJoinController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private SectionService sectionService;

    @Autowired
    private TrayBindingRecordService trayBindingRecordService;

    @Autowired
    private SpellInfoService spellInfoService;

    @ApiOperation(value = "分页查询圆棒拼棒列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_state", value = "状态(1：绑定，0：未绑定)", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_sectionNo", value = "圆棒编号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_operateTime", value = "绑定时间(开始时间)", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LT_operateTime", value = "绑定时间(结束时间)", dataType = "string", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<Section>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<Section> specification = DynamicSpecifications.bySearchFilter(request, Section.class);
        Page<Section> page = sectionService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<SectionDto> list = page.getContent().stream()
                .map(entity -> toLazyDto1(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(list, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation("拼接圆棒")
    @PostMapping("/merge")
    public Result merge(@RequestBody StickTogetherParam stickTogetherParam) {
        try {
            return sectionService.stickTogetherBySectionNos(stickTogetherParam.getSectionNos(), stickTogetherParam.getCreateUser());
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "后台页面根据圆棒拼棒记录id解除绑定")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "relieveReason", value = "解绑原因", dataType = "string", paramType = "query"),
    })
    @PostMapping("/ybRelieve")
    public Result ybJoinUnbind(Long id, String relieveReason) {
        sectionService.ybRelieve(id, relieveReason);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "Pda根据编码解除圆棒绑定关系")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionNo", value = "晶段编码", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "relieveReason", value = "解绑原因", dataType = "string", paramType = "query"),
    })
    @PostMapping("/pdaRelieveBySectionNo")
    public Result pdaRelieveBySectionNo(String sectionNo, String relieveReason) {
        if (StringUtils.isBlank(sectionNo)) {
            ResultGenerator.fail("晶段编码为空！");
        }
        try {
            SpellInfo info = spellInfoService.findBySectionNo(sectionNo);
            if (info != null) {
                sectionService.ybRelieve(info.getSectionId(), relieveReason);
            } else {
                throw new RuntimeException("错误，该晶段没有拼棒记录");
            }
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "分页查询托盘绑定操作记录列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByTrayPage")
    public Result<ResponsePage<TrayBindingRecordDto>> yblistByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<TrayBindingRecord> specification = DynamicSpecifications.bySearchFilter(request, TrayBindingRecord.class);
        Page<TrayBindingRecord> page = trayBindingRecordService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<TrayBindingRecordDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto1(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    //region 废弃接口
//    @ApiOperation(value = "拼圆棒Pda根据托盘解除绑定")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "code", value = "托盘编号", dataType = "string", paramType = "query"),
//            @ApiImplicitParam(name = "userName", value = "解绑人", dataType = "string", paramType = "query"),
//            @ApiImplicitParam(name = "relieveReason", value = "解绑原因", dataType = "string", paramType = "query"),
//    })
//    @PostMapping("/ybJoinPda/unbind")
//    public Result ybJoinPdaUnbind(@RequestBody JSONObject params) {
//        if (null == params) {
//            return ResultGenerator.fail("传入参数为空！");
//        }
//        String code = params.getString("code");
//        String userName = params.getString("userName");
//        String relieveReason = params.getString("relieveReason");
//        if (StringUtils.isBlank(code)) {
//            ResultGenerator.fail("托盘编号为空！");
//        }
//        try {
//            sectionService.ybJoinPdaUnbind(code, userName, relieveReason);
//            return ResultGenerator.success();
//        } catch (Exception e) {
//            return ResultGenerator.fail(e.getMessage());
//        }
//    }
//
//    @ApiOperation(value = "删除圆棒记录")
//    @PostMapping("/delete")
//    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
//        for (Long id : ids) {
//            sectionService.deleteById(id);
//        }
//        return ResultGenerator.success();
//    }
    //endregion

    @ApiOperation(value = "导出圆棒拼棒记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "search_EQ_state", value = "状态(1：绑定，0：未绑定)", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_sectionNo", value = "圆棒编号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_operateTime", value = "绑定时间(开始时间)", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LT_operateTime", value = "绑定时间(结束时间)", dataType = "string", paramType = "query"),
    })
    @GetMapping("/export")
    public void export(ServletRequest request, @ApiIgnore RequestPage requestPage, HttpServletResponse response) {
        try {
            Specification<Section> specification = DynamicSpecifications.bySearchFilter(request, Section.class);
            List<Section> list1 = sectionService.findByExampleSort(specification, Sort.by(Sort.Direction.DESC, "id"));
            List<SectionDto> list = list1.stream()
                    .map(entity -> toLazyDto1(entity))
                    .collect(Collectors.toList());
            EasyExcelUtils.write(response, SectionDto.class, "圆棒拼棒记录", "圆棒拼棒记录", list);
        } catch (Exception e) {
            throw new RuntimeException("圆棒拼棒记录导出失败，错误信息：" + e.getMessage());
        }
    }

    public FbjoinDto toLazyDto(Fbjoin entity) {
        return modelMapper.map(entity, FbjoinDto.class);
    }

    public SectionDto toLazyDto1(Section entity) {
        return modelMapper.map(entity, SectionDto.class);
    }

    public FbjoinDto toEagerDto(Fbjoin entity) {
        FbjoinDto dto = modelMapper.map(entity, FbjoinDto.class);
        return dto;
    }

    public Fbjoin fromDto(FbjoinDto dto) {
        return modelMapper.map(dto, Fbjoin.class);
    }

    public TrayBindingRecordDto toLazyDto1(TrayBindingRecord entity) {
        TrayBindingRecordDto dto = modelMapper.map(entity, TrayBindingRecordDto.class);
        if (dto.getStatus() != null) {
            dto.setStatusName(EnumValues.trayBindingRecordStatus.getText(dto.getStatus()));
        }
        return dto;
    }


}
