package cn.ezhizao.project.business.controller;

import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.domain.*;
import cn.ezhizao.project.business.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 生产计划明细Controller
 *
 * @author ruoyi
 * @date 2023-11-15
 */
@RestController
@RequestMapping("/business/productionPlanDetail")
public class BizProductionPlanDetailController extends BaseController {
    @Resource
    private IBizProductionPlanDetailService bizProductionPlanDetailService;

    @Resource
    private IBizTechnologicalProcessDetailService bizTechnologicalProcessDetailService;
    @Resource
    private IBizDayworkService bizDayworkService;
    @Resource
    private IBizDayworkItemService bizDayworkItemService;

    @Resource
    private IBizLotService bizLotService;
    @Resource
    HttpServletRequest request;

    /**
     * 查询生产计划明细列表
     */
//    @PreAuthorize("@ss.hasPermi('business:productionBatch:list')")
    @GetMapping("/list")
    @Log(title = "查询生产计划明细列表", businessType = BusinessType.SELECT)
    public TableDataInfo list( BizProductionPlanDetail data) throws NoSuchFieldException, IllegalAccessException {
//        String tenantId = request.getHeader("tenantId");
//        data.setTenantId(Long.valueOf(tenantId));
        startPage();
        List<BizProductionPlanDetail> list = bizProductionPlanDetailService.getList(data);
        return getDataTable(list);
    }

    /**
     * 查询生产计划明细报表列表
     */
//    @PreAuthorize("@ss.hasPermi('business:productionBatch:list')")
    @GetMapping("/reportList")
    @Log(title = "查询生产计划明细报表列表", businessType = BusinessType.SELECT)
    public TableDataInfo reportList( BizProductionPlanDetail data) throws NoSuchFieldException, IllegalAccessException {
//        String tenantId = request.getHeader("tenantId");
//        data.setTenantId(Long.valueOf(tenantId));
        //查询当前工段在产批数
//        List<Long> inDayworkIds = new ArrayList<>();
//        inDayworkIds.add(0L);
//        List<Long> afterDayworkIds = new ArrayList<>();
//        afterDayworkIds.add(0L);
//            QueryWrapper<BizDaywork> queryWrapper = new QueryWrapper<>();
//            if(data.getDeptId()!= null && data.getDeptId() != 0){
//                queryWrapper.eq("dept_id", data.getDeptId());
//            }
//            List<BizDaywork> currentDayworkList = bizDayworkService.list(queryWrapper);
//            List<Long> currentDayworkIds = currentDayworkList.stream().map(BizDaywork::getId).collect(Collectors.toList());
//            if(!currentDayworkIds.isEmpty()) {
//                List<BizDayworkItem> currentDayworkItemList = bizDayworkItemService.getListByDayworkIds(currentDayworkIds);
//                for (int i = 0; i < currentDayworkIds.size(); i++) {
//                    Long currentId = currentDayworkIds.get(i);
//                    BizDayworkItem bizDayworkItem = currentDayworkItemList.stream().filter(item -> item.getDayworkId().equals(currentId)).sorted(Comparator.comparing(BizDayworkItem::getCreateTime).reversed()).collect(Collectors.toList()).get(0);
//                    if (Integer.parseInt(bizDayworkItem.getStatus()) < 3) {
//                        inDayworkIds.add(currentId);
//                    }
//                    String processStepNumber = bizDayworkItem.getProcessStepNumber();
//                    List<String> status = currentDayworkItemList.stream().filter(info -> info.getDayworkId().equals(currentId) && info.getProcessStepNumber().equals(processStepNumber)).map(BizDayworkItem::getStatus).collect(Collectors.toList());
//                    if (status.contains("3") && !status.contains("4") && !status.contains("5") && !status.contains("7")) {
//                        afterDayworkIds.add(currentId);
//                    }
//                }
//            }
//        data.setAfterDayworkIds(afterDayworkIds);
//        data.setInDayworkIds(inDayworkIds);
        startPage();
        List<BizProductionPlanDetail> list = bizProductionPlanDetailService.reportList(data);
        List<Long> productionPlanDetailIds = list.stream().map(BizProductionPlanDetail::getId).collect(Collectors.toList());
        List<BizDaywork> dayworkList = bizDayworkService.query().in("production_plan_detail_id", productionPlanDetailIds.isEmpty()? Collections.singletonList("0"):list.stream().map(BizProductionPlanDetail::getId).collect(Collectors.toList())).list();
        List<Long> dayworkIds = dayworkList.stream().map(BizDaywork::getId).collect(Collectors.toList());
        dayworkIds.add(0L);
        List<BizDayworkItem> dayworkItemList = bizDayworkItemService.getListByDayworkIds(dayworkIds);
        //查出来投产的批次，在外面对正在干的批次数量和已完成的数量进行赋值
        if(!list.isEmpty()) {
            list.forEach(info -> {
                int inProduction = 0;
                int afterProduction = 0;
                int notProduction = 0;
                //同一计划单，同工段下的报工
                List<BizDaywork> currentDayworkList = dayworkList.stream().filter(item -> item.getProductionPlanDetailId().equals(info.getId()) && item.getDeptId().equals(info.getCurrentDeptId())).collect(Collectors.toList());
                List<Long> currentDayworkIds = currentDayworkList.stream().map(BizDaywork::getId).collect(Collectors.toList());
                for (int j = 0; j < currentDayworkIds.size(); j++) {
                    Long currentId = currentDayworkIds.get(j);
                    //拿到该批次最新工序步骤
                    BizDayworkItem item = dayworkItemList.stream().filter(v -> v.getDayworkId().equals(currentId)).max(Comparator.comparing(BizDayworkItem::getProcessStepNumber)).orElse(null);
                    String latestProcessStepNumber;
                    if (item != null) {
                        latestProcessStepNumber = item.getProcessStepNumber();
                    } else {
                        latestProcessStepNumber = "";
                    }
//                     = dayworkItemList.stream().filter(item -> item.getDayworkId().equals(currentId)).sorted(Comparator.comparing(BizDayworkItem::getProcessStepNumber).reversed()).collect(Collectors.toList()).get(0).getProcessStepNumber();
//
                    List<String> latestStatus = dayworkItemList.stream().filter(v -> v.getDayworkId().equals(currentId) && v.getProcessStepNumber().equals(latestProcessStepNumber)).map(BizDayworkItem::getStatus).collect(Collectors.toList());
                    if (!latestStatus.contains("0") &&!latestStatus.contains("3") && !latestStatus.contains("4") && !latestStatus.contains("5") && !latestStatus.contains("7")) {
                        inProduction++;
                    }
                    if (latestStatus.contains("3") && !latestStatus.contains("4") && !latestStatus.contains("5") && !latestStatus.contains("7")) {
                        afterProduction++;
                    }
                    if (latestStatus.contains("4") || latestStatus.contains("5") || latestStatus.contains("7") || latestStatus.contains("0")) {
                        notProduction++;
                    }
                }
                info.setInProduction(inProduction);
                info.setAfterProduction(afterProduction);
                info.setNotProduction(notProduction);
            });
        }
        return getDataTable(list);
    }
    /**
     * 查询生产计划明细列表
     */
    @GetMapping("/getList")
    @Log(title = "查询生产计划明细列表", businessType = BusinessType.SELECT)
    public TableDataInfo getInfo( BizProductionPlanDetail data) throws NoSuchFieldException, IllegalAccessException {
//        String tenantId = request.getHeader("tenantId");
//        data.setTenantId(Long.valueOf(tenantId));
        startPage();
        List<BizProductionPlanDetail> list = bizProductionPlanDetailService.getInfo(data);
        int index = 0;
        for (int i =0; i < list.size(); i++) {
             index = 0;
            for (int j = 0; j<list.get(i).getDayWorkList().size(); j++) {
                if(list.get(i).getDayWorkList().get(j).getDeptId().equals(data.getDeptId())) {
                    index ++;
                }

            }
            list.get(i).setDayWorkLot(index);
        }
        return getDataTable(list);
    }
    /*追加批次*/
    @PostMapping("/addLot")
    @Transactional
    @Log(title = "追加批次", businessType = BusinessType.SELECT)
    public AjaxResult addLot(@RequestBody BizProductionPlanDetail bizProductionPlanDetail) throws NoSuchFieldException, IllegalAccessException {
        List<BizLot> oldList = bizLotService.query().eq("production_plan_detail_id", bizProductionPlanDetail.getId()).eq("is_superaddition", 1).list();
        bizProductionPlanDetail.getLotList().forEach(l -> {
            if (l.getTenantId() ==null) {
                l.setTenantId(getLoginUser().getUser().getTenantId());
            }
        });
        saveOrUpdateBatch(bizLotService,bizProductionPlanDetail.getLotList(),oldList);
       return success(bizProductionPlanDetailService.updateById(bizProductionPlanDetail));
    }

    /**
     * 获取生产计划明细详细信息
     */


    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bizProductionPlanDetailService.getById(id));
    }

    /**
     * 新增生产计划明细
     */
    @PreAuthorize("@ss.hasPermi('business:productionPlanDetail:add')")
    @Log(title = "新增生产计划明细", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizProductionPlanDetail bizProductionPlanDetail) throws NoSuchFieldException, IllegalAccessException {
//        String tenantId = request.getHeader("tenantId");
//        bizProductionPlanDetail.setTenantId(Long.valueOf(tenantId));
        return toAjax(bizProductionPlanDetailService.save(bizProductionPlanDetail));
    }

    /**
     * 修改生产批号状态
     */
    @Log(title = "修改生产批号状态", businessType = BusinessType.UPDATE)
    @PutMapping("/updateLotCodeStatus")
    public AjaxResult updateLotCodeStatus(@RequestBody BizProductionPlanDetail bizProductionPlanDetail)  {
//        String tenantId = request.getHeader("tenantId");
//        bizProductionPlanDetail.setTenantId(Long.valueOf(tenantId));

        return toAjax(bizProductionPlanDetailService.updateLotCodeStatus(bizProductionPlanDetail));
    }
    /**
     * 获取工艺版本
     */
    @GetMapping("/getTechnologicalVersion")
    @Log(title = "获取工艺版本", businessType = BusinessType.SELECT)
    public AjaxResult getTechnologicalVersion(BizTechnologicalProcess bizTechnologicalProcess) {
        return success(bizProductionPlanDetailService.getTechnologicalVersion(bizTechnologicalProcess));
    }

    @GetMapping("/getTechnologicalProcessDetailList")
    @Log(title = "获取工艺明细列表", businessType = BusinessType.SELECT)
    public AjaxResult getTechnologicalProcessDetailList(BizTechnologicalProcessDetail bizTechnologicalProcessDetail) {
        QueryWrapper<BizTechnologicalProcessDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("technological_process_id", bizTechnologicalProcessDetail.getTechnologicalProcessId());
        return success(bizTechnologicalProcessDetailService.list(queryWrapper));
    }

    /**
     * 修改生产计划批号状态
     */
    @PreAuthorize("@ss.hasPermi('business:productionPlanDetail:edit')")
    @Log(title = "修改生产计划批号状态", businessType = BusinessType.UPDATE)
    @Transactional
    @PutMapping
    public AjaxResult edit(@RequestBody BizProductionPlanDetail bizProductionPlanDetail) throws NoSuchFieldException, IllegalAccessException {
         //修改生产版本，向新表存历史记录，同时修改biz_lot表里未投产的
        BizChangeTechnologicalVersion bizChangeTechnologicalVersion = new BizChangeTechnologicalVersion();
        bizChangeTechnologicalVersion.setProductionPlanDetailId(bizProductionPlanDetail.getId());
        bizChangeTechnologicalVersion.setOldTechnologicalProcessId(bizProductionPlanDetail.getOldTechnologicalProcessId());
        bizChangeTechnologicalVersion.setOldTechnologyVersion(bizProductionPlanDetail.getOldTechnologyVersion());
        bizChangeTechnologicalVersion.setNewTechnologyVersion(bizProductionPlanDetail.getTechnologyVersion());
        bizChangeTechnologicalVersion.setNewTechnologicalProcessId(bizProductionPlanDetail.getTechnologicalProcessId());
        List<BizLot> notStartList = bizLotService.getNotStartList(bizProductionPlanDetail);
        notStartList.forEach(item ->
        {item.setTechnologyVersion(bizProductionPlanDetail.getTechnologyVersion());
                item.setTechnologicalProcessId(bizProductionPlanDetail.getTechnologicalProcessId());});
        if(notStartList.size() > 0) {
            bizLotService.updateBatchById(notStartList) ;
        }
        //修改生产计划表的版本
        BizProductionPlanDetail productionPlanDetail = bizProductionPlanDetailService.getById(bizProductionPlanDetail.getId());
        productionPlanDetail.setTechnologicalProcessId(bizProductionPlanDetail.getTechnologicalProcessId());
        productionPlanDetail.setTechnologyVersion(bizProductionPlanDetail.getTechnologyVersion());

        return toAjax(bizProductionPlanDetailService.updateById(productionPlanDetail));
    }

    /**
     * 删除生产计划明细
     */
    @PreAuthorize("@ss.hasPermi('business:productionPlanDetail:remove')")
    @Log(title = "删除生产计划明细", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(bizProductionPlanDetailService.removeBatchByIds(ids));
    }
    @Log(title = "下载计划报表", businessType = BusinessType.EXPORT)
    @PostMapping("/download")
    public void download(HttpServletResponse response, BizProductionPlanDetail data) throws NoSuchFieldException, IllegalAccessException {
        List<BizProductionPlanDetail> list = bizProductionPlanDetailService.reportList(data);
        List<Long> productionPlanDetailIds = list.stream().map(BizProductionPlanDetail::getId).collect(Collectors.toList());
        List<BizDaywork> dayworkList = bizDayworkService.query().in("production_plan_detail_id", productionPlanDetailIds.isEmpty()? Collections.singletonList("0"):list.stream().map(BizProductionPlanDetail::getId).collect(Collectors.toList())).list();
        List<Long> dayworkIds = dayworkList.stream().map(BizDaywork::getId).collect(Collectors.toList());
        dayworkIds.add(0L);
        List<BizDayworkItem> dayworkItemList = bizDayworkItemService.getListByDayworkIds(dayworkIds);
        //查出来投产的批次，在外面对正在干的批次数量和已完成的数量进行赋值
        if(!list.isEmpty()) {
            list.forEach(info -> {
                int inProduction = 0;
                int afterProduction = 0;
                int notProduction = 0;
                //同一计划单，同工段下的报工
                List<BizDaywork> currentDayworkList = dayworkList.stream().filter(item -> item.getProductionPlanDetailId().equals(info.getId()) && item.getDeptId().equals(info.getCurrentDeptId())).collect(Collectors.toList());
                List<Long> currentDayworkIds = currentDayworkList.stream().map(BizDaywork::getId).collect(Collectors.toList());
                for (int j = 0; j < currentDayworkIds.size(); j++) {
                    Long currentId = currentDayworkIds.get(j);
                    //拿到该批次最新工序步骤
                    BizDayworkItem item = dayworkItemList.stream().filter(v -> v.getDayworkId().equals(currentId)).max(Comparator.comparing(BizDayworkItem::getProcessStepNumber)).orElse(null);
                    String latestProcessStepNumber;
                    if (item != null) {
                        latestProcessStepNumber = item.getProcessStepNumber();
                    } else {
                        latestProcessStepNumber = "";
                    }
//                    String latestProcessStepNumber = dayworkItemList.stream().filter(item -> item.getDayworkId().equals(currentId)).sorted(Comparator.comparing(BizDayworkItem::getProcessStepNumber).reversed()).collect(Collectors.toList()).get(0).getProcessStepNumber();
                    List<String> latestStatus = dayworkItemList.stream().filter(v -> v.getDayworkId().equals(currentId) && v.getProcessStepNumber().equals(latestProcessStepNumber)).map(BizDayworkItem::getStatus).collect(Collectors.toList());
                    if (!latestStatus.contains("3") && !latestStatus.contains("4") && !latestStatus.contains("5") && !latestStatus.contains("7")) {
                        inProduction++;
                    }
                    if (latestStatus.contains("3") && !latestStatus.contains("4") && !latestStatus.contains("5") && !latestStatus.contains("7")) {
                        afterProduction++;
                    }
                    if (latestStatus.contains("4") || latestStatus.contains("5") || latestStatus.contains("7") || latestStatus.contains("0")) {
                        notProduction++;
                    }
                }
                info.setInProduction(inProduction);
                info.setAfterProduction(afterProduction);
                info.setNotProduction(notProduction);
            });
        }
        ExcelUtil<BizProductionPlanDetail> util = new ExcelUtil<>(BizProductionPlanDetail.class);
        util.exportExcel(response, list, "计划报表");
    }
}
