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

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.sw.mes.base.workinprocess.dao.WipStorageDao;
import com.sw.mes.base.workinprocess.dto.WipProcessDetailedInfoDto;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import com.sw.mes.core.dto.sap.ReportSapChargItemDto;
import com.sw.mes.core.dto.sap.ReportSapGoodsmvtDto;
import com.sw.mes.core.entity.SearchFilter;
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.core.utils.*;
import com.sw.mes.sap.entity.ReportSapGoodsmvt;
import com.sw.mes.sap.service.ReportSapGoodsmvtService;
import com.sw.mes.yb.production.dto.ProcessPathDto;
import com.sw.mes.yb.production.entity.ProcessPath;
import com.sw.mes.yb.report.dto.WorkOrderProgressReportDto;
import com.sw.mes.yb.report.service.WorkOrderProgressReportService;
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.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author JS107742
 */
@RestController
@RequestMapping("/workOrderProgressReport")
@Slf4j
@Api(description = "工单实时进度看板")
public class WorkOrderProgressReportController {

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private WorkOrderProgressReportService workOrderProgressReportService;

    @Autowired
    private ReportSapGoodsmvtService reportSapGoodsmvtService;

    @Autowired
    private WipStorageService wipStorageService;



    @ApiOperation(value = "查询工单收货报工信息列表-方法1")
    @PostMapping("/findOrderProgress")
    public Result<List<WorkOrderProgressReportDto>> findOrderProgress(@RequestBody @Valid @ApiParam(value = "工单收货报工查询") WorkOrderProgressReportDto workOrderProgressReportDto) {

        //按工单查询工单收获报工信息列表
        List<WorkOrderProgressReportDto> orderProgress = workOrderProgressReportService.findOrderProgress(workOrderProgressReportDto);
        return ResultGenerator.success(orderProgress);
    }

//    @ApiOperation(value = "查询工单收货报工信息列表-方法1")
//    @PostMapping("/findOrderProgress1")
//    public Result<List<WorkOrderProgressReportDto>> findOrderProgress(ServletRequest request, @ApiIgnore RequestPage requestPage) {
//
//        //按工单查询工单收获报工信息列表
//        List<WorkOrderProgressReportDto> orderProgress = workOrderProgressReportService.findOrderProgress1(request, requestPage);
//        return ResultGenerator.success(orderProgress);
//    }


    @ApiOperation(value = "分页查询收货列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_procName", value = "工序名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_aufnr", value = "工单编号", dataType = "String", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<ReportSapGoodsmvtDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Set<SearchFilter> searchSet = new HashSet<>();
        String aufnr = request.getParameter("search_EQ_aufnr");
        if (!StringUtils.isBlank(aufnr)) {
            searchSet.add(new SearchFilter("aufnr", SearchFilter.Operator.EQ, aufnr));
        }
        String procName = request.getParameter("search_LIKE_procName");
        if (!StringUtils.isBlank(procName)) {
            searchSet.add(new SearchFilter("procName", SearchFilter.Operator.LIKE, procName));
        }
        searchSet.add(new SearchFilter("bwart", SearchFilter.Operator.IN, new String[]{"101", "531", "261", "102", "532", "262"}));
        searchSet.add(new SearchFilter("status", SearchFilter.Operator.EQ, 0));
        Specification<ReportSapGoodsmvt> specification = DynamicSpecifications.bySearchFilter(ReportSapGoodsmvt.class, searchSet);
        Page<ReportSapGoodsmvt> page = reportSapGoodsmvtService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<ReportSapGoodsmvtDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        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_EQ_orderCode", value = "工单编号", dataType = "String", paramType = "query"),
    })
    @GetMapping("/findData")
    public Result<ResponsePage<List<WipProcessDetailedInfoDto>>> findData(ServletRequest request, @ApiIgnore RequestPage requestPage) {
//        Set<SearchFilter> searchSet = new HashSet<>();
        String orderCode = request.getParameter("search_EQ_orderCode");
//        if (!StringUtils.isBlank(orderCode)) {
//            searchSet.add(new SearchFilter("orderCode", SearchFilter.Operator.EQ, orderCode));
//        }
//        String procName = request.getParameter("search_LIKE_procName");
//        if (!StringUtils.isBlank(procName) && procName.equals("截断")) {
//            searchSet.add(new SearchFilter("process_name", SearchFilter.Operator.IN, new String[]{"圆棒检验", "圆棒反切", "配圆棒"}));
//        }
//        if (!StringUtils.isBlank(procName) && procName.equals("刀剖")) {
//            searchSet.add(new SearchFilter("process_name", SearchFilter.Operator.IN, new String[]{"磨削", "方棒检验", "方棒反切"}));
//        }
//        Specification<WipProcessDetailedInfoDto> specification = DynamicSpecifications.bySearchFilter(WipProcessDetailedInfoDto.class, searchSet);
//
//        Set<SearchFilter> searchSet1 = new HashSet<>();
//        if (!StringUtils.isBlank(orderCode)) {
//            searchSet1.add(new SearchFilter("orderCode", SearchFilter.Operator.EQ, orderCode));
//        }
//        if (!StringUtils.isBlank(procName) && procName.equals("截断")) {
//            searchSet1.add(new SearchFilter("process_name", SearchFilter.Operator.EQ, "毛棒截断"));
//        }
//        if (!StringUtils.isBlank(procName) && procName.equals("刀剖")) {
//            searchSet1.add(new SearchFilter("process_name", SearchFilter.Operator.EQ, "刀剖"));
//        }
//        searchSet1.add(new SearchFilter("status", SearchFilter.Operator.EQ, 1));
//        Specification<WipProcessDetailedInfoDto> specification1 = DynamicSpecifications.bySearchFilter(WipProcessDetailedInfoDto.class, searchSet);
//
//        Specification<WipProcessDetailedInfoDto> specification2 = specification.or(specification1);
        ResponsePage<List<WipProcessDetailedInfoDto>> responsePage = wipStorageService.getProcessInfoPage(orderCode, PageUtil.createPageable(requestPage, new String[]{"overtime DESC", "id DESC"}));
        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_EQ_orderCode", value = "工单编号", dataType = "String", paramType = "query"),
    })
    @GetMapping("/export")
    public void findData(ServletRequest request, HttpServletResponse response) {
        try {
            String orderCode = request.getParameter("search_EQ_orderCode");
            List<WipProcessDetailedInfoDto> allData = wipStorageService.getAllData(orderCode);
            EasyExcelUtils.write(response, WipProcessDetailedInfoDto.class, "导出工单在制品信息", "导出工单在制品信息", allData);
        } catch (IOException e) {
            throw new RuntimeException("工单在制品信息导出失败，错误信息：" + e.getMessage());
        }
    }

    public ReportSapGoodsmvtDto toLazyDto(ReportSapGoodsmvt entity) {
        ReportSapGoodsmvtDto dto = modelMapper.map(entity, ReportSapGoodsmvtDto.class);
        dto.setChargItems(new Gson().fromJson(entity.getChargItem(),new TypeToken<List<ReportSapChargItemDto>>(){}.getType()));
        return dto;
    }
}
