package cn.ezhizao.project.business.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.*;
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.common.utils.poi.ExcelUtil;
import cn.ezhizao.framework.web.page.TableDataInfo;

/**
 * 外协单从对应的外协工序的从Controller
 *
 * @author 庄德政
 * date    2024-04-26
 */
@RestController
@RequestMapping("/business/outsourceDetailProcess")
public class BizOutsourcedOrderDetailProcessController extends BaseController
{
    @Resource
    private IBizOutsourcedOrderDetailProcessService bizOutsourcedOrderDetailProcessService;
    @Resource
    private IBizReturnReceiptDetailService returnReceiptDetailService;
    @Resource
    private IBizOutsourcedOrderDetailService bizOutsourcedOrderDetailService;
    @Resource
    private IBizSupplierService bizSupplierService;
    @Resource
    private IBizDayworkCarrierService bizDayworkCarrierService;
    @Resource
    private HttpServletRequest request;

    /**
     * 查询外协单从对应的外协工序的从列表
     */
    @PreAuthorize("@ss.hasPermi('business:outsourceDetail:list')")
    @Log(title = "外协发出明细工序查询", businessType = BusinessType.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(BizOutsourcedOrderDetailProcess bizOutsourcedOrderDetailProcess) throws NoSuchFieldException, IllegalAccessException
    {
        if(bizOutsourcedOrderDetailProcess.getStartTime()!=null) {
            bizOutsourcedOrderDetailProcess.setStartTime(bizOutsourcedOrderDetailProcess.getStartTime()+ " 00:00:00");
        }
        if(bizOutsourcedOrderDetailProcess.getEndTime()!=null) {
            bizOutsourcedOrderDetailProcess.setEndTime(bizOutsourcedOrderDetailProcess.getEndTime()+ " 23:59:59");
        }
        //已经确认的外协单
        List<Long> hasReturnDetailId = returnReceiptDetailService.query().eq("is_audit", 1).list().stream().map(BizReturnReceiptDetail::getOutsourceDetailId).distinct().collect(Collectors.toList());
        bizOutsourcedOrderDetailProcess.setHasReturnDetailId(hasReturnDetailId);
        startPage();
        bizOutsourcedOrderDetailProcess.setSupplierId(Long.valueOf(request.getHeader("tenantId")));
        List<BizOutsourcedOrderDetailProcess> list = bizOutsourcedOrderDetailProcessService.getList(bizOutsourcedOrderDetailProcess);
        List<BizOutsourcedOrderDetail> details = bizOutsourcedOrderDetailService.query().in("id", list.isEmpty() ? Collections.singletonList(0L) : list.stream().map(BizOutsourcedOrderDetailProcess::getDetailId).collect(Collectors.toList())).list();
        BizSupplier supplier = bizSupplierService.getById(Long.valueOf(request.getHeader("tenantId")));
        List<BizDayworkCarrier> currentCarriers = new ArrayList<>();
        if(supplier.getIsInnerOutsource().equals(1) && !details.isEmpty()) {
            currentCarriers.addAll(bizDayworkCarrierService.query().eq("is_changed", 0).in("daywork_id", details.stream().map(BizOutsourcedOrderDetail::getDayworkId).collect(Collectors.toList())).list());
        }
        //收回状态
        list.forEach(item ->{
            item.setReturnStatus(0);
            if(item.getReturnReceiptDetails()!=null &&item.getReturnReceiptDetails().size()>0&&item.getReturnReceiptDetails().get(0).getIsAudit() == 1 ) {
                item.setReturnStatus(1);
            }
            BizOutsourcedOrderDetail detail = details.stream().filter(v -> v.getId().equals(item.getDetailId())).findFirst().orElse(null);
            if(detail != null) {
                if(supplier.getIsInnerOutsource().equals(1)) {
                    // 将字符串拆分转为对象
                    List<BizCarrier> carriers = new ArrayList<>();
                    // 为了减少前段的逻辑，所以需要先将拆分后的id也拼接起来
                    List<Long> carrierIds = new ArrayList<>();
                    currentCarriers.stream().filter(v -> v.getDayworkId().equals(detail.getDayworkId())).forEach(l -> {
                        BizCarrier carrier = new BizCarrier();
                        carrierIds.add(l.getCarrierId());
                        carrier.setCode(l.getCarrierCode());
                        carrier.setId(l.getCarrierId());
                        carriers.add(carrier);
                    });
                    item.setNewCarriers(carriers);
                    item.setCarrierIds(carrierIds);
                    item.setCarriers(carriers);
                    item.setNewCarrierName(carriers.stream().map(BizCarrier::getCode).collect(Collectors.joining(",")));
                } else {
                    // 将字符串拆分转为对象
                    List<BizCarrier> carriers = new ArrayList<>();
                    // 为了减少前段的逻辑，所以需要先将拆分后的id也拼接起来
                    List<Long> carrierIds = new ArrayList<>();
                    //使用 StringTokenizer 来分割字符串
                    StringTokenizer tokenizer = new StringTokenizer(detail.getNewCarrier(), ",");
                    while (tokenizer.hasMoreTokens()) {
                        String token = tokenizer.nextToken();
                        // 检查当前 token 是否包含 "|" 字符 如果没有表示不是新箱，则跳过当前 token
                        if (token.contains("|")) {
                            String[] idCode = token.split("\\|"); // 安全地分割 token
                            if (idCode.length == 2) {
                                carrierIds.add(Long.parseLong(idCode[0]));
                                BizCarrier bizCarrier = new BizCarrier();
                                bizCarrier.setId(Long.parseLong(idCode[0]));
                                bizCarrier.setCode(idCode[1]);
                                carriers.add(bizCarrier);
                            }
                        }
                    }
                    item.setNewCarriers(carriers);
                    item.setCarrierIds(carrierIds);
                    item.setCarriers(carriers);
                }
            }
        });
        return getDataTable(list);
    }
    @Log(title = "外协报工查询工序合格数", businessType = BusinessType.SELECT)
    @PostMapping("/getLastProcessQualifitedNum")
    public AjaxResult getLastProcessQualifitedNum(@RequestBody BizOutsourcedOrderDetailProcess bizOutsourcedOrderDetailProcess) throws NoSuchFieldException, IllegalAccessException
    {
        //拿到该外协单的工序
        List<BizOutsourcedOrderDetailProcess> detailList = bizOutsourcedOrderDetailProcessService.query().eq("detail_id",bizOutsourcedOrderDetailProcess.getDetailId()).orderByAsc("process_step_number").list();
        int index =-1;
        for(int i = 0;i<detailList.size();i++) {
            if(detailList.get(i).getProcessStepNumber().equals(bizOutsourcedOrderDetailProcess.getProcessStepNumber())) {
                index = i;
            }
        }
        if(index>0) {
            if(detailList.get(index-1).getProductionNum() == 0) {
                return error("上一道序未报工，不允许报此道序");
            }
            else{
                return success(detailList.get(index-1).getQualifiedNum());
            }
        }else{
            return success(bizOutsourcedOrderDetailProcess.getProductNum());
        }
    }

    /**
     * 导出外协单从对应的外协工序的从列表
     */
    @PreAuthorize("@ss.hasPermi('business:outsourceDetail:export')")
    @Log(title = "外协发出工序导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizOutsourcedOrderDetailProcess bizOutsourcedOrderDetailProcess) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizOutsourcedOrderDetailProcess);
        List<BizOutsourcedOrderDetailProcess> list = bizOutsourcedOrderDetailProcessService.getList(bizOutsourcedOrderDetailProcess);
        ExcelUtil<BizOutsourcedOrderDetailProcess> util = new ExcelUtil<>(BizOutsourcedOrderDetailProcess.class);
        util.exportExcel(response, list, "外协单从对应的外协工序的从数据");
    }
    /**
     * 修改外协单从对应的外协工序的合格数和投产数
     */
    @PreAuthorize("@ss.hasPermi('business:outsourceDetail:edit')")
    @Log(title = "外协报工修改外协工序的合格数和投产数", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/editOutsourcedOrderDetailProcess")
    public AjaxResult editOutsourcedOrderDetailProcess(@RequestBody BizOutsourcedOrderDetailProcess bizOutsourcedOrderDetailProcess)
    {
        //保存时添加状态
        bizOutsourcedOrderDetailProcess.setStatus(1);
        return success(bizOutsourcedOrderDetailProcessService.updateById(bizOutsourcedOrderDetailProcess));
    }
    /**
     * 查询收回单明细
     */
    @Log(title = "查询外协发出工序", businessType = BusinessType.SELECT)
    @PostMapping(value = "/getOrderDetailProcess")
    public AjaxResult getOrderDetailProcess(@RequestBody BizOutsourcedOrderDetailProcess bizOutsourcedOrderDetailProcess)
    {
        List<BizOutsourcedOrderDetailProcess> list = bizOutsourcedOrderDetailProcessService.getDetailList(bizOutsourcedOrderDetailProcess);
        list.forEach(detail -> {
            // 将字符串拆分转为对象
            List<BizCarrier> carriers = new ArrayList<>();
            // 因为需要显示箱号，所以需要拆分出code重新拼接到NewCarrier
            List<String> codeList = new ArrayList<>();
            // 为了减少前段的逻辑，所以需要先将拆分后的id也拼接起来
            List<Long> carrierIds = new ArrayList<>();
            //使用 StringTokenizer 来分割字符串
            StringTokenizer tokenizer = new StringTokenizer(detail.getNewCarrier(), ",");
            while (tokenizer.hasMoreTokens()) {
                String token = tokenizer.nextToken();
                // 检查当前 token 是否包含 "|" 字符 如果没有表示不是新箱，则跳过当前 token
                if (token.contains("|")) {
                    String[] idCode = token.split("\\|"); // 安全地分割 token
                    if (idCode.length == 2) {
                        codeList.add(idCode[1]);
                        carrierIds.add(Long.parseLong(idCode[0]));
                        BizCarrier bizCarrier = new BizCarrier();
                        bizCarrier.setId(Long.parseLong(idCode[0]));
                        bizCarrier.setCode(idCode[1]);
                        carriers.add(bizCarrier);
                    }
                }
            }
            if(codeList.size()>0){
                detail.setNewCarrier(String.join(",", codeList));
            }
        });
        return success(list);
    }

    /**
     * 获取外协单从对应的外协工序的从详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:outsourceDetail:query')")
    @Log(title = "外协发出工序查询详细信息", businessType = BusinessType.SELECT)
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bizOutsourcedOrderDetailProcessService.getById(id));
    }
}
