package cn.ezhizao.project.business.controller;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.ezhizao.common.utils.SecurityUtils;
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 org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 分选包装审核申请Controller
 *
 * @author ezhizao
 * @date 2024-07-29
 */
@RestController
@RequestMapping("/business/examine")
public class BizDayworkItemExamineController extends BaseController {
    @Resource
    private IBizDayworkItemExamineService bizDayworkItemExamineService;
    @Resource
    private IBizDayworkCarrierService bizDayworkCarrierService;
    @Resource
    private IBizDayworkItemService bizDayworkItemService;
    @Resource
    private IBizDayworkService bizDayworkService;
    @Resource
    private IBizTechnologicalProcessDetailService bizTechnologicalProcessDetailService;
    @Resource
    private IBizLotTechnologicalProcessDetailService bizLotTechnologicalProcessDetailService;


    /**
     * 查询分选包装审核申请列表
     */
    @GetMapping("/list")
    @Log(title = "查询分选包装审核申请列表", businessType = BusinessType.SELECT)
    public TableDataInfo list(BizDayworkItemExamine bizDayworkItemExamine) throws NoSuchFieldException, IllegalAccessException {
        startPage();
        if (bizDayworkItemExamine.getStartTime() != null) {
            bizDayworkItemExamine.setStartTime(bizDayworkItemExamine.getStartTime() + " 00:00:00");
        }
        if (bizDayworkItemExamine.getEndTime() != null) {
            bizDayworkItemExamine.setEndTime(bizDayworkItemExamine.getEndTime() + " 23:59:59");
        }
        List<BizDayworkItemExamine> list = bizDayworkItemExamineService.getList(bizDayworkItemExamine);
        //拿到每一个批次工艺路线的工序列表
        if(!list.isEmpty()) {
            List<BizDaywork> dayworkList = bizDayworkService.query().in("id", list.stream().map(BizDayworkItemExamine::getDayworkId).collect(Collectors.toList())).list();
            List<BizTechnologicalProcessDetail> normalTechnologicalProcessDetailList = bizTechnologicalProcessDetailService.query().in("technological_process_id", dayworkList.stream().map(BizDaywork::getTechnologicalProcessId).collect(Collectors.toList())).ne("tenant_id",9).list();
            List<BizLotTechnologicalProcessDetail> abNormalTechnologicalProcessDetailList = bizLotTechnologicalProcessDetailService.query().in("lot_technological_process_id", dayworkList.stream().map(BizDaywork::getTechnologicalProcessId).collect(Collectors.toList())).list();
        list.forEach(item ->{
            dayworkList.forEach(info ->{
                if(item.getDayworkId().equals(info.getId())) {
                    if(info.getIsAmend() == 1 || info.getIsWasteRecycling() == 1) {
                        Long latestTechnologicalProcessDetailId = abNormalTechnologicalProcessDetailList.stream().filter(detail -> detail.getLotTechnologicalProcessId().equals(info.getTechnologicalProcessId())).sorted(Comparator.comparing(BizLotTechnologicalProcessDetail::getProcessStepNumber).reversed()).collect(Collectors.toList()).get(0).getId();
                        if(latestTechnologicalProcessDetailId.equals(item.getLastTechnologicalProcessDetailId())) {
                            //最后一道序已经开始报工
                            item.setIsNextProcess(true);
                        }else{
                            item.setIsNextProcess(false);
                        }
                    }else{
                        Long latestTechnologicalProcessDetailId = normalTechnologicalProcessDetailList.stream().filter(detail -> detail.getTechnologicalProcessId().equals(info.getTechnologicalProcessId())).sorted(Comparator.comparing(BizTechnologicalProcessDetail::getProcessStepNumber).reversed()).collect(Collectors.toList()).get(0).getId();
                        if(latestTechnologicalProcessDetailId.equals(item.getLastTechnologicalProcessDetailId())) {
                            //最后一道序已经开始报工
                            item.setIsNextProcess(true);
                        }else{
                            item.setIsNextProcess(false);
                        }
                    }
                }
            });
        });
        }
        return getDataTable(list);
    }

    /**
     * 导出分选包装审核申请列表
     */
    @PreAuthorize("@ss.hasPermi('business:examine:export')")
    @Log(title = "导出分选包装审核申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizDayworkItemExamine bizDayworkItemExamine) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizDayworkItemExamine);
        List<BizDayworkItemExamine> list = bizDayworkItemExamineService.getList(bizDayworkItemExamine);
        ExcelUtil<BizDayworkItemExamine> util = new ExcelUtil<BizDayworkItemExamine>(BizDayworkItemExamine.class);
        util.exportExcel(response, list, "分选包装审核申请数据");
    }

    /**
     * 获取分选包装审核申请详细信息
     */
    @GetMapping(value = "/{id}")
    @Log(title = "查询分选包装审核详情", businessType = BusinessType.SELECT)
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bizDayworkItemExamineService.getDetailById(id));
    }

    /**
     * 新增分选包装审核申请
     */
    @Log(title = "新增分选包装审核申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody List<BizDayworkItemExamine> bizDayworkItemExamine) throws NoSuchFieldException, IllegalAccessException {
        //新增判断，如果已经添加过，则删除旧数据再新增
        //拿到dayworkIds
        List<Long> dayworkIds = bizDayworkItemExamine.stream().map(BizDayworkItemExamine::getDayworkId).collect(Collectors.toList());
        //判断表里该批次是否已经存在
        List<BizDayworkItemExamine> examineListByDayworkIds = bizDayworkItemExamineService.query().in("daywork_id", dayworkIds).list();
        if(!examineListByDayworkIds.isEmpty()) {
            //先删除再添加
            bizDayworkItemExamineService.removeBatchByIds(examineListByDayworkIds);
        }
        return toAjax(bizDayworkItemExamineService.saveBatch(bizDayworkItemExamine));
    }

    /**
     * 修改分选包装审核申请
     */
    @Log(title = "分选包装审核申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizDayworkItemExamine bizDayworkItemExamine) throws NoSuchFieldException, IllegalAccessException {
        bizDayworkItemExamine.setReviewerId(SecurityUtils.getLoginUser().getUser().getUserId());
        setTenantId(bizDayworkItemExamine);
        return toAjax(bizDayworkItemExamineService.updateById(bizDayworkItemExamine));
    }
    //批量检查
    @PutMapping("/multiplyEdit")
    @Log(title = "批量修改分选包装审核列表", businessType = BusinessType.UPDATE)
    public AjaxResult multiplyEdit(@RequestBody List<BizDayworkItemExamine> bizDayworkItemExamine) throws NoSuchFieldException, IllegalAccessException {
       bizDayworkItemExamine.forEach(item ->{
           item.setReviewerId(SecurityUtils.getLoginUser().getUser().getUserId());
       });
        return toAjax(bizDayworkItemExamineService.updateBatchById(bizDayworkItemExamine));
    }
    @PostMapping("/getDayworkItemByCarrierName")
    @Log(title = "根据载具查询待分选包装报工", businessType = BusinessType.SELECT)
    public AjaxResult getDayworkItemByCarrierName(@RequestBody BizDayworkCarrier bizDayworkCarrier) {
        List<BizDayworkCarrier> dayworkCarrierList = bizDayworkCarrierService.query().like("carrier_code", bizDayworkCarrier.getCarrierCode()).eq("process_inspection_id",0).eq("is_changed", 0).list();
        if (dayworkCarrierList.isEmpty()) {
            return success(new ArrayList<>());
        } else {
            //通过查箱号获得dayworkId
            List<Long> dayworkIds = dayworkCarrierList.stream().map(BizDayworkCarrier::getDayworkId).collect(Collectors.toList());
            //审核申请里审核过得批次
            List<BizDayworkItemExamine> examineList = bizDayworkItemExamineService.query()
                    .in("daywork_id", dayworkIds)
                    .eq("status", 1)
                    .or()
                    .eq("status", 2)
                    .list();
            if(!examineList.isEmpty()) {
                List<Long> examineListIds = examineList.stream().map(BizDayworkItemExamine::getDayworkId).collect(Collectors.toList());
                dayworkIds = dayworkIds.stream().filter(item -> !examineListIds.contains(item)).collect(Collectors.toList());
            }
            if(!dayworkIds.isEmpty()) {
                List<BizDayworkItem> dayworkItemList = bizDayworkItemService.getListByDayworkIds(dayworkIds);
                List<Long> dayworkItemIds = new ArrayList<>();
                dayworkIds.forEach(item -> {
                    BizDayworkItem bizDayworkItem = dayworkItemList.stream().filter(info -> info.getDayworkId().equals(item)).sorted(Comparator.comparing(BizDayworkItem::getCreateTime).reversed()).collect(Collectors.toList()).get(0);
                    dayworkItemIds.add(bizDayworkItem.getId());
                });
                List<BizDayworkItemExamine> allowAddedList = bizDayworkItemExamineService.getAllowAddedList(dayworkItemIds);
                allowAddedList.forEach(item -> {
                    //为了前端选择批次的时候，一箱多批的没选
                    item.setCarrierId(dayworkCarrierList.stream().filter(info -> info.getDayworkId().equals(item.getDayworkId())).collect(Collectors.toList()).get(0).getCarrierId());
                });
                return AjaxResult.success(allowAddedList);
            }else{
                return success(new ArrayList<>());
            }
        }
    }

    /**
     * 删除分选包装审核申请
     */
    @Log(title = "分选包装审核申请", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(bizDayworkItemExamineService.removeBatchByIds(ids));
    }
}
