package cn.ezhizao.project.business.controller;

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.domain.server.Sys;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.domain.*;
import cn.ezhizao.project.business.service.*;
import cn.ezhizao.project.system.domain.SysDept;
import cn.ezhizao.project.system.service.ISysDeptService;
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 java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 辅助工序Controller
 *
 * @author ezhizao
 * @date 2023-11-29
 */
@RestController
@RequestMapping("/business/auxiliaryDaywork")
public class BizDayworkAuxiliaryItemController extends BaseController {
    @Resource
    private ISysDeptService sysDeptService;
    @Resource
    private IBizDayworkService bizDayworkService;

    @Resource
    private IBizTechnologicalProcessDetailService bizTechnologicalProcessDetailService;

    @Resource
    private IBizLotTechnologicalProcessDetailService bizTechnologicalAmendDetailService;

    @Resource
    private IBizOutsourcedOrderDetailService bizOutsourcedOrderDetailService;

    @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 IBizCarrierService bizCarrierService;
    @Resource
    private IBizReturnReceiptDetailService bizReturnReceiptDetailService;
    @Resource
    private IBizProductionResourceGroupDetailService bizProductionResourceGroupDetailService;
    @Resource
    private IBizLotTechnologicalProcessService bizLotTechnologicalProcessService;
    @Resource
    private IBizProductionPlanDetailService bizProductionPlanDetailService;
    @Resource
    private IBizDayworkAuxiliaryItemService bizDayworkAuxiliaryItemService;
    @Resource
    private IBizDayworkAuxiliaryItemRejectService bizDayworkAuxiliaryItemRejectService;
    @Resource
    HttpServletRequest request;

    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('business:auxiliaryDaywork:list')")
    @Log(title = "获取辅助报工列表", businessType = BusinessType.EXPORT)
    public TableDataInfo list(BizDayworkAuxiliaryItem bizDayworkAuxilaryItem) {
        startPage();
        //查询当前生产子计划的批次报工列表
        List<BizDayworkAuxiliaryItem> list = bizDayworkAuxiliaryItemService.getList(bizDayworkAuxilaryItem);
        //最终返回当前子计划中批次报工的工序是这个人员负责的工序
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('business:auxiliaryDaywork:query')")
    @PostMapping("/getRejectList")
    @Log(title = "获取辅助报工废品列表", businessType = BusinessType.EXPORT)
    public AjaxResult getRejectList(@RequestBody BizDayworkAuxiliaryItemReject reject) {
        List<BizDayworkItemReject> rejects = bizDayworkItemRejectService.query().eq("daywork_auxiliary_item_reject_id", reject.getId()).list();
        return success(rejects);
    }

    /**
     * 获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:auxiliaryDaywork:query')")
    @GetMapping(value = "/getInfo/{id}")
    @Log(title = "获取辅助报工列表详情", businessType = BusinessType.EXPORT)
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        BizDayworkAuxiliaryItem itemConditions = new BizDayworkAuxiliaryItem();
        itemConditions.setId(id);
        BizDayworkAuxiliaryItem item = bizDayworkAuxiliaryItemService.getList(itemConditions).size() > 0 ? bizDayworkAuxiliaryItemService.getList(itemConditions).get(0) : null;
        if (item != null) {
            BizDayworkAuxiliaryItemReject rejectCondition = new BizDayworkAuxiliaryItemReject();
            rejectCondition.setDayworkAuxiliaryItemId(id);
            List<BizDayworkAuxiliaryItemReject> rejects = bizDayworkAuxiliaryItemRejectService.getList(rejectCondition);
            List<BizDayworkItem> items = bizDayworkItemService.query().in("id", rejects.isEmpty() ? Collections.singleton(0L) : rejects.stream().map(BizDayworkAuxiliaryItemReject::getDayworkItemId).collect(Collectors.toList())).list();
            rejects.forEach(v -> {
                v.setDayworkItem(items.stream().filter(i -> i.getId().equals(v.getDayworkItemId())).findFirst().orElse(null));
                v.setQualifiedNum(v.getDayworkItem() != null ? v.getDayworkItem().getQualifiedNum() : v.getQualifiedNum());
            });
            item.setRejectList(rejects);
        }
        return success(item);
    }

    @PreAuthorize("@ss.hasPermi('business:auxiliaryDaywork:edit')")
    @PostMapping("/update")
    @Transactional
    @Log(title = "更新辅助报工", businessType = BusinessType.EXPORT)
    public AjaxResult update(@RequestBody BizDayworkAuxiliaryItem bizDayworkAuxiliaryItem) {
        List<BizDayworkAuxiliaryItemReject> auxiliaryRejects = bizDayworkAuxiliaryItemRejectService.query().eq("daywork_auxiliary_item_id", bizDayworkAuxiliaryItem.getId()).list();
        AtomicReference<Integer> changeNum = new AtomicReference<>(0);
        auxiliaryRejects.forEach(v -> {
            BizDayworkAuxiliaryItemReject item = bizDayworkAuxiliaryItem.getRejectList().stream().filter(e -> e.getId().equals(v.getId())).findFirst().orElse(new BizDayworkAuxiliaryItemReject());
            changeNum.set(changeNum.get() + item.getRejectNum().intValue() - v.getRejectNum().intValue());
        });
        // 判断当前工序是否已完成，假设未完成不修改假设已完成则修改
        List<BizDayworkItem> bizDayworkItems = bizDayworkItemService.query().eq("daywork_id", bizDayworkAuxiliaryItem.getDayworkId()).orderByDesc("process_step_number").orderByDesc("create_time").list();
        BizDaywork bizDaywork = bizDayworkService.query().eq("id", bizDayworkAuxiliaryItem.getDayworkId()).one();
        bizDayworkAuxiliaryItemRejectService.updateBatchById(bizDayworkAuxiliaryItem.getRejectList());
        BizDayworkItem latest = bizDayworkItems.stream().filter(e -> e.getStatus().compareTo("4") < 0).findFirst().orElse(new BizDayworkItem());
        // 判断最新工序是否和当前工序相同假设相同该工序是否已完成，假设未完成，啥都不改。
        if (!latest.getTechnologicalProcessDetailId().equals(bizDayworkAuxiliaryItem.getTechnologicalProcessDetailId()) && !bizDayworkItems.stream().filter(v -> v.getTechnologicalProcessDetailId().equals(latest.getTechnologicalProcessDetailId())).noneMatch(v -> v.getStatus().equals("3"))) {
            bizDaywork.setTemporaryProcessQualifiedNum(bizDaywork.getTemporaryProcessQualifiedNum() != 0 ? bizDaywork.getTemporaryProcessQualifiedNum() - changeNum.get() : 0);
            bizDaywork.setProcessQualifiedNum(bizDaywork.getProcessQualifiedNum() - changeNum.get());
            if (!latest.getTechnologicalProcessDetailId().equals(bizDayworkAuxiliaryItem.getTechnologicalProcessDetailId()) && bizDayworkItems.stream().filter(v -> v.getTechnologicalProcessDetailId().equals(latest.getTechnologicalProcessDetailId())).noneMatch(v -> v.getStatus().equals("3"))) {
                bizDayworkItems.stream().filter(v -> v.getTechnologicalProcessDetailId().equals(latest.getTechnologicalProcessDetailId())).forEach(v -> {
                    v.setProdNum(v.getProdNum() - changeNum.get());
                });
            }
        }
        if (bizDaywork.getTemporaryProcessQualifiedNum().compareTo(0) < 0 || bizDaywork.getProcessQualifiedNum().compareTo(0) < 0) {
            return error("当前报工数量不能小于0");
        }
//        if (bizDayworkItems.stream().anyMatch(v -> v.getProdNum().compareTo(v.getQualifiedNum()) < 0)) {
//            return error("3");
//        }

//        List<BizDayworkItemReject> rejects = bizDayworkItemRejectService.query().eq("daywork_auxiliary_item_id", bizDayworkAuxiliaryItem.getId()).list();
//        List<BizDayworkAuxiliaryItemReject> rejectList = bizDayworkAuxiliaryItem.getRejectList();
//        for (BizDayworkItemReject reject : rejects) {
//            BizDayworkAuxiliaryItemReject auxiliaryReject = rejectList.stream().filter(v -> v.getId().equals(reject.getDayworkAuxiliaryItemRejectId())).findFirst().orElse(new BizDayworkAuxiliaryItemReject());
//            reject.setRejectNum(auxiliaryReject.getRejectNum());
//        }
        bizDayworkService.updateById(bizDaywork);
        bizDayworkItemService.updateBatchById(bizDayworkItems);
//        bizDayworkItemRejectService.updateBatchById(rejects);
        return toAjax(bizDayworkAuxiliaryItemService.updateById(bizDayworkAuxiliaryItem));
    }

    /**
     * 查询报工列表
     */
    @GetMapping("/listDaywork")
    @Log(title = "获取报工列表", businessType = BusinessType.EXPORT)
    public TableDataInfo list(BizDaywork bizDaywork) throws NoSuchFieldException, IllegalAccessException {
        if (!getLoginUser().getUser().isAdmin()) {
            SysDept conditionDept = new SysDept();
            conditionDept.setUserId(getUserId());
            List<SysDept> sysDepts = sysDeptService.selectDeptList(conditionDept);
            bizDaywork.setAuxiliaryDeptIds(sysDepts.isEmpty() ? Collections.singletonList(0L) : sysDepts.stream().map(SysDept::getDeptId).collect(Collectors.toList()));
        }

        startPage();
        setTenantId(bizDaywork);
        //查询当前生产子计划的批次报工列表
        List<BizDaywork> dayworkList = bizDayworkService.getListForAuxiliary(bizDaywork);
        for (BizDaywork daywork : dayworkList) {
            if (daywork.getTotalWorkingHours() == null) {
                daywork.setTotalWorkingHours(Long.valueOf(0));
            }
        }
        //最终返回当前子计划中批次报工的工序是这个人员负责的工序
        return getDataTable(dayworkList);
    }

    @PostMapping("/saveRejectList")
    @PreAuthorize("@ss.hasPermi('business:auxiliaryDaywork:edit')")
    @Log(title = "保存辅助报工废品列表", businessType = BusinessType.EXPORT)
    public AjaxResult saveRejectList(@RequestBody BizDayworkAuxiliaryItemReject reject) {
        // 查询已有的rejectList
        List<BizDayworkItemReject> rejects = bizDayworkItemRejectService.query().eq("daywork_auxiliary_item_reject_id", reject.getId()).list();
        List<BizDayworkItemReject> inputs = reject.getRejectList();
        List<BizDayworkItemReject> remove = rejects.stream().filter(v -> inputs.stream().noneMatch(t -> v.getId().equals(t.getId()))).collect(Collectors.toList());
        reject.setRejectNum(inputs.stream().mapToLong(BizDayworkItemReject::getRejectNum).sum());
        bizDayworkAuxiliaryItemRejectService.updateById(reject);
        BizDayworkAuxiliaryItem auxiliaryItem = bizDayworkAuxiliaryItemService.getById(reject.getDayworkAuxiliaryItemId());
        List<BizDayworkAuxiliaryItemReject> allRejects = bizDayworkAuxiliaryItemRejectService.query().eq("daywork_auxiliary_item_id", auxiliaryItem.getId()).list();
        auxiliaryItem.setRejectNum(allRejects.stream().mapToInt(v -> Math.toIntExact(v.getRejectNum())).sum());
        bizDayworkAuxiliaryItemService.updateById(auxiliaryItem);
        return (remove.isEmpty() || bizDayworkItemRejectService.removeBatchByIds(remove)) && (inputs.isEmpty() || bizDayworkItemRejectService.saveOrUpdateBatch(inputs)) ? success() : error("保存失败");
    }

}
