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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 报工Controller
 *
 * @author ezhizao
 * @date 2023-11-29
 */
@RestController
@RequestMapping("/business/productionDaywork")
public class BizDayworkController extends BaseController {
    @Resource
    private IBizDayworkService bizDayworkService;

    @Resource
    private IBizTechnologicalProcessDetailService bizTechnologicalProcessDetailService;

    @Resource
    private IBizLotTechnologicalProcessDetailService bizTechnologicalAmendDetailService;

    @Resource
    private IBizDayworkCarrierService bizDayworkCarrierService;

    @Resource
    private IBizLotTechnologicalProcessDetailService bizLotTechnologicalProcessDetailService;

    @Resource
    private IBizLotService bizLotService;

    @Resource
    private IBizProcessService bizProcessService;
    @Resource
    private IBizDayworkQualifiedService bizDayworkQualifiedService;
    @Resource
    private IBizDayworkItemService bizDayworkItemService;
    @Resource
    private IBizDayworkItemRejectService bizDayworkItemRejectService;
    @Resource
    private IBizProductionResourceGroupDetailService bizProductionResourceGroupDetailService;

    @Resource
    HttpServletRequest request;

    /**
     * 查询报工列表
     */
    @PreAuthorize("@ss.hasPermi('business:daywork:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizDaywork bizDaywork) {
        startPage();
        //查询当前生产子计划的批次报工列表
        List<BizDaywork> dayworkList = bizDayworkService.getList(bizDaywork);
        for (BizDaywork daywork : dayworkList) {
            if (daywork.getTotalWorkingHours() == null) {
                daywork.setTotalWorkingHours(Long.valueOf(0));
            }
        }
        //最终返回当前子计划中批次报工的工序是这个人员负责的工序
        return getDataTable(dayworkList);
    }

    /**
     * 查询报工列表
     *
     * @param bizDayworkItem
     * @return TableDataInfo
     */
    @GetMapping("/listItem")
    public TableDataInfo listItem(BizDayworkItem bizDayworkItem) throws NoSuchFieldException, IllegalAccessException {
        startPage();
        //查询批次报工信息列表
        List<BizDayworkItem> itemList = bizDayworkService.getItemList(bizDayworkItem);

        List<BizLotTechnologicalProcessDetail> lotProcessList = new ArrayList<>();//新工序列表
        List<BizTechnologicalProcessDetail> processList = new ArrayList<>();//标准工序列表

        //是否废回用或单批但改
        if(bizDayworkItem.getIsAmend() == 1 || bizDayworkItem.getIsWasteRecycling() == 1){
            //查询新工序列表
            lotProcessList=bizLotTechnologicalProcessDetailService.query().eq("lot_id",itemList.get(0).getLotId()).list();
        }else {
            //查询标准工列表
            processList=bizTechnologicalProcessDetailService.query().eq("technological_process_id",itemList.get(0).getTechnologicalProcessId()).list();
        }
        for (BizDayworkItem item : itemList) {
            if (item.getRejectNum() == null) {
                item.setRejectNum(0);
            }
            //是单批单改或废品回用
            //根据当前工序id设置当前工序
            if(bizDayworkItem.getIsAmend() == 1 || bizDayworkItem.getIsWasteRecycling() == 1){
                lotProcessList.forEach(lotProcess -> {
                    if(item.getTechnologicalProcessDetailId().equals(lotProcess.getId())){
                        item.setProcessAlias(lotProcess.getProcessAlias());
                    }
                });
            }else{
                processList.forEach(process -> {
                    if(item.getTechnologicalProcessDetailId().equals(process.getId())){
                        item.setProcessAlias(process.getProcessAlias());
                    }
                });
            }
        }
        return getDataTable(itemList);
    }

    /**
     * 修改报工列表
     *
     * @param bizDayworkItem
     * @return TableDataInfo
     */
    @PostMapping("/updateItem")
    public AjaxResult updateItem(@RequestBody BizDayworkItem bizDayworkItem) {
//        String tenantId = request.getHeader("tenantId");
//        bizDayworkItem.setTenantId(Long.valueOf(tenantId));
        return toAjax(bizDayworkItemService.saveOrUpdate(bizDayworkItem));
    }

    /**
     * 获取工序列表
     */
    @GetMapping("/getProcessList")
    public AjaxResult getProcessList(BizDayworkItem bizDayworkItem) {
        return success(bizDayworkService.getProcessList(bizDayworkItem));
    }

    /**
     * 获取批次工序信息
     */
    @GetMapping("/getDayworkItemProcess/{id}")
    public AjaxResult getDayworkItemProcess(@PathVariable("id") String lotCode) {
        //查询批次信息
        HashMap<String, Object> map= new HashMap<>();
        try {
            BizLot lot=new BizLot();
            lot.setLotCode(lotCode);
            List<BizLot> lotList= bizLotService.getList(lot);
            lot=lotList.size()>0?lotList.get(0):null;
            if(lot!=null){
                //查询当前工序
                BizDaywork daywork=new BizDaywork();
                BizDayworkItem item=new BizDayworkItem();
                daywork.setLotId(lot.getId());
                daywork.setProductionPlanDetailId(lot.getProductionPlanDetailId());
                daywork.setLotCode(lotCode);
                //查询报工数据
                List<BizDaywork> dayworkList=bizDayworkService.getList(daywork);
                //没有数据表示未开始报工
                if(dayworkList.size()>0){
                    daywork=bizDayworkService.getList(daywork).get(0);
                    item.setDayworkId(daywork.getId());
                    item=bizDayworkItemService.getList(item).get(0);
                    BizTechnologicalProcessDetail processDetail=bizTechnologicalProcessDetailService.getById(item.getTechnologicalProcessDetailId());
                    item.setProcessStepNumber(processDetail.getProcessStepNumber());
                }else{
                    item=null;
                }

                //是否单批单改
                if(lot.getIsAmend()==1 ||lot.getIsWasteRecycling()==1){
                    BizLotTechnologicalProcessDetail amendDetail =new BizLotTechnologicalProcessDetail();
                    amendDetail.setLotTechnologicalProcessId(lot.getTechnologicalProcessId());
                    List<BizLotTechnologicalProcessDetail> amendDetailList=bizTechnologicalAmendDetailService.getList(amendDetail);
                    map.put("processDetails",amendDetailList);
                } else{
                    //查询工序列表
                    List<BizTechnologicalProcessDetail>  processDetails=bizTechnologicalProcessDetailService.getProcessDetailsByTechnicalProcessId(lot.getTechnologicalProcessId());
                    map.put("processDetails",processDetails);
                }
                map.put("dayworkItem",item);
                map.put("lot",lot);
            }else{
                throw new RuntimeException("未查询到该批次信息！");
            }
        } catch (Exception e) {
            throw new RuntimeException("批次信息异常！");
        }


        return success(map);
    }



    @PostMapping("/checkUseEquipment")
    public AjaxResult checkUseEquipment(@RequestBody List<BizProductionResourceGroupDetail> bizProductionResourceGroupDetailList) {
        List<BizProductionResourceGroupDetail> equipmentDetail = bizProductionResourceGroupDetailList.stream().filter(item ->
                item.getCommonType().equals("equipmentDetail")).collect(Collectors.toList());
        String errorMessage = "";
        for (BizProductionResourceGroupDetail item : equipmentDetail) {
            List<BizDayworkItem> list = bizProductionResourceGroupDetailService.checkUseEquipment(item);
            if (list.size() > 0) {
                errorMessage = errorMessage + item.getCommonName() + ",";
            }
        }
        if ("".equals(errorMessage)) {
            return success();
        }
        return error(errorMessage + "设备正在使用不能删除");
    }
    /**
     * 获取报工记录的工段
     */
    @GetMapping("/getDeptInfo")
    public AjaxResult getDeptList(BizDayworkItem bizDayworkItem) {
        return success(bizDayworkItemService.getDeptInfo(bizDayworkItem));
    }

    /**
     * 获取计划详情
     */
    @GetMapping("/getDayworkInfo")
    public TableDataInfo getDayworkInfo(BizDaywork daywork) {
        return getDataTable(bizDayworkService.getDayworkInfo(daywork));
    }
    @GetMapping("/getProducedLot")
    public TableDataInfo getProducedLot(BizProductionPlanDetail data) {
        return getDataTable(bizDayworkService.getProducedLot(data));
    }
    /**
     * 获取计划详情的工段列表
     */
    @GetMapping("/getDeptList")
    public AjaxResult getDeptList(BizDaywork daywork) {
        return success(bizDayworkService.getDeptList(daywork));
    }
    /**
     * 获取计划详情的工序列表
     */
    @GetMapping("/getDayworkProcessList")
    public AjaxResult getDayworkProcessList( BizDaywork daywork) {
        return success(bizDayworkService.getDayworkProcessList(daywork));
    }
    /**
     * 导出批次报工列表
     */
    @Log(title = "报工", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizDaywork bizDaywork) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizDaywork);
        List<BizDaywork> list = bizDayworkService.getList(bizDaywork);
        ExcelUtil<BizDaywork> util = new ExcelUtil<>(BizDaywork.class);
        util.exportExcel(response, list, "报工数据");
    }

    /**
     * 获取报工详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bizDayworkService.getById(id));
    }

    /**
     * 获取报工废品数信息
     */
    @GetMapping("/getDayworkItemRejectList")
    public AjaxResult getDayworkItemRejectList(BizDayworkItemReject bizDayworkItemReject) {
        return success(bizDayworkItemRejectService.getList(bizDayworkItemReject));
    }

    /**
     * 查询当前是否为首序
     */
    @Log(title = "是否为首序拆线呢", businessType = BusinessType.SELECT)
    @GetMapping(value = "/getIsFirstOrder/{dayWorkId}")
    public AjaxResult getIsFirstOrder(@PathVariable("dayWorkId") Long dayWorkId) {
        HashMap<String, Object> map = new HashMap<>();
        //根据dayWorkId查询出当前工序的报工记录(按照工序筛选每道工序只查询一条数据)
        List<BizDayworkItem> list = bizDayworkItemService.getItemScreen(dayWorkId);
        //查询出来的数据等于1条则为首序
        if(list.size() == 1){
            map.put("isFirstOrder",true);
        }else{
            map.put("isFirstOrder",false);
        }
        return success(map);
    }

    /**
     * 修改dayworkItem和dayworkItemReject
     *
     * @param bizDayworkItem
     * @return TableDataInfo
     */
    @Transactional
    @PostMapping("/updateDayworkItemInfo")
    public AjaxResult updateDayworkItemInfo(@RequestBody BizDayworkItem bizDayworkItem) {
//        String tenantId = request.getHeader("tenantId");
//        bizDayworkItem.setTenantId(Long.valueOf(tenantId));
        if (bizDayworkItem.getStatus().equals("3")) {
            //往合格数中间表新增数据
            BizDayworkQualified bizDayworkQualified = new BizDayworkQualified();
            bizDayworkQualified.setDayworkId(bizDayworkItem.getDayworkId());
            bizDayworkQualified.setTemporaryProcessQualifiedNum(bizDayworkItem.getTemporaryProcessQualifiedNum());
            bizDayworkQualified.setProcessId(bizDayworkItem.getProcessId());
            bizDayworkQualified.setProcessQualifiedNum(bizDayworkItem.getProdNum());
            bizDayworkQualified.setProductionPlanDetailId(bizDayworkItem.getProductionPlanDetailId());
            bizDayworkQualifiedService.save(bizDayworkQualified);
        }
        //前端判断，如果状态从工序已完成变成报工结束时，将中间表数据删除
        if (bizDayworkItem.getFlag() != null) {
            QueryWrapper<BizDayworkQualified> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("deleted", 0);
            queryWrapper.eq("daywork_id", bizDayworkItem.getDayworkId());
            queryWrapper.eq("process_id", bizDayworkItem.getProcessId());
            List<BizDayworkQualified> list = bizDayworkQualifiedService.list(queryWrapper);
            if (list.size() > 0) {
                bizDayworkQualifiedService.removeById(list.get(0));
            }

        }
        //修改biz_daywork表的process_qualified_num(这道序的合格总数）
        QueryWrapper<BizDaywork> query = new QueryWrapper<>();
        query.eq("deleted", 0);
        query.eq("id", bizDayworkItem.getDayworkId());
        BizDaywork daywork = bizDayworkService.list(query).get(0);
        daywork.setTemporaryProcessQualifiedNum(bizDayworkItem.getTemporaryProcessQualifiedNum());
        bizDayworkService.updateById(daywork);
        //修改报工信息
        bizDayworkItemService.updateDayworkItem((bizDayworkItem));
        //修改报工信息的废弃表
        QueryWrapper<BizDayworkItemReject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("daywork_item_id", bizDayworkItem.getId());
        queryWrapper.eq("deleted", 0);
        List<BizDayworkItemReject> oldList = bizDayworkItemRejectService.list(queryWrapper);
        saveOrUpdateBatch(bizDayworkItemRejectService, bizDayworkItem.getGroupRejectList(), oldList);
        return success();
    }
}
