package cn.ezhizao.project.business.controller;

import java.util.ArrayList;
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.BizCarrier;
import cn.ezhizao.project.business.domain.BizOutsourcedOrderDetailProcess;
import cn.ezhizao.project.business.domain.BizReturnReceiptDetail;
import cn.ezhizao.project.business.service.IBizOutsourcedOrderDetailProcessService;
import cn.ezhizao.project.business.service.IBizReturnReceiptDetailService;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.project.business.domain.BizOutsourcedOrderDetail;
import cn.ezhizao.project.business.service.IBizOutsourcedOrderDetailService;
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/outsourceDetail")
public class BizOutsourcedOrderDetailController extends BaseController {
    @Resource
    private IBizOutsourcedOrderDetailService bizOutsourcedOrderDetailService;
    @Resource
    private IBizOutsourcedOrderDetailProcessService bizOutsourcedOrderDetailProcessService;
    @Resource
    private IBizReturnReceiptDetailService bizReturnReceiptDetailService;
    @Resource
    private HttpServletRequest request;

    /**
     * 查询外协单从列表
     */
    @PreAuthorize("@ss.hasPermi('business:outsourceDetail:list')")
    @Log(title = "外协单明细查询", businessType = BusinessType.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(BizOutsourcedOrderDetail bizOutsourcedOrderDetail) throws NoSuchFieldException, IllegalAccessException {
        if (bizOutsourcedOrderDetail.getStartTime() != null) {
            bizOutsourcedOrderDetail.setStartTime(bizOutsourcedOrderDetail.getStartTime() + " 00:00:00");
        }
        if (bizOutsourcedOrderDetail.getEndTime() != null) {
            bizOutsourcedOrderDetail.setEndTime(bizOutsourcedOrderDetail.getEndTime() + " 23:59:59");
        }
        setTenantId(bizOutsourcedOrderDetail);
        startPage();
        List<BizOutsourcedOrderDetail> list = bizOutsourcedOrderDetailService.getList(bizOutsourcedOrderDetail);
        return getDataTable(list);
    }

    //查询已经报工完成orderDetail
    @Log(title = "外协查询已经报公完成的明细", businessType = BusinessType.SELECT)
    @GetMapping("/getFinishedOutsourceDetailList")
    public TableDataInfo getFinishedOutsourceDetailList(BizOutsourcedOrderDetail bizOutsourcedOrderDetail) throws NoSuchFieldException, IllegalAccessException {
        if (bizOutsourcedOrderDetail.getStartTime() != null) {
            bizOutsourcedOrderDetail.setStartTime(bizOutsourcedOrderDetail.getStartTime() + " 00:00:00");
        }
        if (bizOutsourcedOrderDetail.getEndTime() != null) {
            bizOutsourcedOrderDetail.setEndTime(bizOutsourcedOrderDetail.getEndTime() + " 23:59:59");
        }
        setTenantId(bizOutsourcedOrderDetail);
        startPage();
        // 获取所有该外协商未完成的 外协明细对应的工序明细
        List<BizOutsourcedOrderDetailProcess> notFinishedDetail = bizOutsourcedOrderDetailProcessService.query()
                // 这里的tenantId，存储的是supplier_id
                .eq("supplier_name", bizOutsourcedOrderDetail.getSupplierName())
                .eq("status", 0)
                .list();
        // 将所有未完成的外协明细的id，存在一个集合中
        List<Long> outsourcedOrderDetailIds = notFinishedDetail.stream().map(BizOutsourcedOrderDetailProcess::getDetailId).collect(Collectors.toList());
        bizOutsourcedOrderDetail.setNotFinishedDetailIds(outsourcedOrderDetailIds);
        List<BizOutsourcedOrderDetail> list = bizOutsourcedOrderDetailService.getFinishedOutsourceDetailList(bizOutsourcedOrderDetail);
        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 getDataTable(list);
    }

    /**
     * 导出外协单从列表
     */
    @Log(title = "外协单明细导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizOutsourcedOrderDetail bizOutsourcedOrderDetail) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizOutsourcedOrderDetail);
        List<BizOutsourcedOrderDetail> list = bizOutsourcedOrderDetailService.getList(bizOutsourcedOrderDetail);
        ExcelUtil<BizOutsourcedOrderDetail> util = new ExcelUtil<>(BizOutsourcedOrderDetail.class);
        util.exportExcel(response, list, "外协单从数据");
    }

    /**
     * 获取外协单从详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:outsourceDetail:query')")
    @Log(title = "外协单明细查询详细信息", businessType = BusinessType.EXPORT)
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bizOutsourcedOrderDetailService.getById(id));
    }

    /**
     * 查询默认外协发出单从列表
     */
    @PreAuthorize("@ss.hasPermi('business:outsourceDetail:list')")
    @Log(title = "外协收回选择收回的发出明细", businessType = BusinessType.EXPORT)
    @GetMapping("/listDetailForReceipt")
    public TableDataInfo listDetailForReceipt(BizOutsourcedOrderDetail bizOutsourcedOrderDetail) throws NoSuchFieldException, IllegalAccessException {
//        setTenantId(bizOutsourcedOrderDetail);
        String tenantId = request.getHeader("tenantId");
        bizOutsourcedOrderDetail.setSupplierId(Long.valueOf(tenantId));
        // 获取所有该外协商未完成的 外协明细对应的工序明细
        List<BizOutsourcedOrderDetailProcess> notFinishedDetail = bizOutsourcedOrderDetailProcessService.query()
                // 这里的tenantId，存储的是supplier_id
                .eq("supplier_id", bizOutsourcedOrderDetail.getSupplierId())
                .eq("production_num", 0)
                .eq("qualified_num", 0)
                .list();
        // 将所有未完成的外协明细的id，存在一个集合中
        List<Long> outsourcedOrderDetailIds = notFinishedDetail.stream().map(BizOutsourcedOrderDetailProcess::getDetailId).distinct().collect(Collectors.toList());
        bizOutsourcedOrderDetail.setNotFinishedDetailIds(outsourcedOrderDetailIds);
        //将已添加的外协明细的id，存在一个集合中
        List<BizReturnReceiptDetail> alreadyAddedDetailList = bizReturnReceiptDetailService.query()
                .eq("supplier_id", bizOutsourcedOrderDetail.getSupplierId())
                .list();
        List<Long> alreadyAddedDetailIds = alreadyAddedDetailList.stream().map(BizReturnReceiptDetail::getOutsourceDetailId).distinct().collect(Collectors.toList());
        bizOutsourcedOrderDetail.setAlreadyAddedDetailIds(alreadyAddedDetailIds);
        /*
         1、把未做收回的外协明细列出
         2、把已经报工完成的外协明细列出来
         */
        bizOutsourcedOrderDetail.setSupplierId(Long.valueOf(tenantId));
        bizOutsourcedOrderDetail.setIsInnerOutsource(0);
        startPage();
        List<BizOutsourcedOrderDetail> list = bizOutsourcedOrderDetailService.getListForReceipt(bizOutsourcedOrderDetail);
        //因为新箱子保存的时候，是用“id|code,id|code”的字符串形式存储的所以查询的时候需要进行拆分
        //如果保存的时候没有选择新箱子则会把旧箱号复制到新箱号中，所有不会有“|”所以下方需要进行判断
        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 getDataTable(list);
    }

    /**
     * 查询内部外协发出单明细
     */
    @PreAuthorize("@ss.hasPermi('business:outsourceDetail:list')")
    @GetMapping("/listDetailForInterReceipt")
    public TableDataInfo listDetailForInterReceipt(BizOutsourcedOrderDetail bizOutsourcedOrderDetail) throws NoSuchFieldException, IllegalAccessException {
//        setTenantId(bizOutsourcedOrderDetail);
        String tenantId = request.getHeader("tenantId");
        bizOutsourcedOrderDetail.setSupplierId(Long.valueOf(tenantId));
        bizOutsourcedOrderDetail.setIsInnerOutsource(1);
        // 获取所有该外协商未完成的 外协明细对应的工序明细
        List<BizOutsourcedOrderDetailProcess> notFinishedDetail = bizOutsourcedOrderDetailProcessService.query()
                // 这里的tenantId，存储的是supplier_id
                .eq("supplier_id", bizOutsourcedOrderDetail.getSupplierId())
                .eq("production_num", 0)
                .eq("qualified_num", 0)
                .list();
        // 将所有未完成的外协明细的id，存在一个集合中
//        List<Long> outsourcedOrderDetailIds = notFinishedDetail.stream().map(BizOutsourcedOrderDetailProcess::getDetailId).distinct().collect(Collectors.toList());
        List<Long> outsourcedOrderDetailIds = bizOutsourcedOrderDetailService.getIdsForInterReturn(bizOutsourcedOrderDetail);
        bizOutsourcedOrderDetail.setNotFinishedDetailIds(outsourcedOrderDetailIds);
        //将已添加的外协明细的id，存在一个集合中
        List<BizReturnReceiptDetail> alreadyAddedDetailList = bizReturnReceiptDetailService.query()
                .eq("supplier_id", bizOutsourcedOrderDetail.getSupplierId())
                .list();
        List<Long> alreadyAddedDetailIds = alreadyAddedDetailList.stream().map(BizReturnReceiptDetail::getOutsourceDetailId).distinct().collect(Collectors.toList());
        bizOutsourcedOrderDetail.setAlreadyAddedDetailIds(alreadyAddedDetailIds);
        /*
         1、把未做收回的外协明细列出
         2、把已经报工完成的外协明细列出来
         */
        bizOutsourcedOrderDetail.setSupplierId(Long.valueOf(tenantId));
        startPage();
        List<BizOutsourcedOrderDetail> list = bizOutsourcedOrderDetailService.getListForReceipt(bizOutsourcedOrderDetail);
        //因为新箱子保存的时候，是用“id|code,id|code”的字符串形式存储的所以查询的时候需要进行拆分
        //如果保存的时候没有选择新箱子则会把旧箱号复制到新箱号中，所有不会有“|”所以下方需要进行判断
        list.forEach(detail -> {
            detail.setNewCarrier(detail.getCurrentCarriers());
        });
        return getDataTable(list);
    }
}
