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.HttpServletResponse;

import cn.ezhizao.project.business.domain.*;
import cn.ezhizao.project.business.service.IBizOutsourcedOrderDetailProcessService;
import cn.ezhizao.project.business.service.IBizReturnReceiptDetailService;
import cn.ezhizao.project.business.service.IBizReturnReceiptService;
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;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
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 IBizReturnReceiptService bizReturnReceiptService;

    /**
     * 查询外协单从列表
     */
    @PreAuthorize("@ss.hasPermi('business:outsourceDetail:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizOutsourcedOrderDetail bizOutsourcedOrderDetail) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizOutsourcedOrderDetail);
        startPage();
        List<BizOutsourcedOrderDetail> list = bizOutsourcedOrderDetailService.getList(bizOutsourcedOrderDetail);
        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>(BizOutsourcedOrderDetail.class);
        util.exportExcel(response, list, "外协单从数据");
    }

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

    /**
     * 新增外协单从
     */
    @PreAuthorize("@ss.hasPermi('business:outsourceDetail:add')")
    @Log(title = "外协单从", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizOutsourcedOrderDetail bizOutsourcedOrderDetail) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizOutsourcedOrderDetail);
        return toAjax(bizOutsourcedOrderDetailService.save(bizOutsourcedOrderDetail));
    }

    /**
     * 修改外协单从
     */
    @PreAuthorize("@ss.hasPermi('business:outsourceDetail:edit')")
    @Log(title = "外协单从", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizOutsourcedOrderDetail bizOutsourcedOrderDetail) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizOutsourcedOrderDetail);
        return toAjax(bizOutsourcedOrderDetailService.updateById(bizOutsourcedOrderDetail));
    }
    /**
     * 查询已完成的外协单从列表
     */
    @PreAuthorize("@ss.hasPermi('business:outsourceDetail:list')")
    @GetMapping("/listDetailForReceipt")
    public TableDataInfo listDetailForReceipt(BizOutsourcedOrderDetail bizOutsourcedOrderDetail) throws NoSuchFieldException, IllegalAccessException
    {

        // 获取所有该外协商未完成的 外协明细对应的工序明细
        List<BizOutsourcedOrderDetailProcess> notFinishedDetail = bizOutsourcedOrderDetailProcessService.query()
                // 这里的tenantId，存储的是supplier_id
                .eq("supplier_id", bizOutsourcedOrderDetail.getSupplierId())
//                .eq("production_num", 0)
//                .eq("qualified_num", 0)
                .eq("status",0)
                .list();
        // 将所有未完成的外协明细的id，存在一个集合中
        List<Long> outsourcedOrderDetailIds = notFinishedDetail.stream().map(BizOutsourcedOrderDetailProcess::getDetailId).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).collect(Collectors.toList());
        bizOutsourcedOrderDetail.setAlreadyAddedDetailIds(alreadyAddedDetailIds);
        /*
         1、把未做收回的外协明细列出
         2、把已经报工完成的外协明细列出来
         */
        startPage();
        List<BizOutsourcedOrderDetail> list = bizOutsourcedOrderDetailService.getListForReceipt(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);
    }
    //通过发出单工序明细查出来报完工的发出单明细
    @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);

        // 获取所有该外协商未完成的 外协明细对应的工序明细
        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);
        startPage();
        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);
    }
    @GetMapping("/getNotFinishedOutsourceDetailList")
    public TableDataInfo getNotFinishedOutsourceDetailList(BizOutsourcedOrderDetail bizOutsourcedOrderDetail) throws NoSuchFieldException, IllegalAccessException
    {
        //将已添加的外协明细的id，存在一个集合中
        List<BizReturnReceiptDetail> alreadyAddedDetailList = bizReturnReceiptDetailService.query()
                .list();
        List<Long> alreadyAddedDetailIds = alreadyAddedDetailList.stream().map(BizReturnReceiptDetail::getOutsourceDetailId).collect(Collectors.toList());
        bizOutsourcedOrderDetail.setAlreadyAddedDetailIds(alreadyAddedDetailIds);
        /*
         1、把未做收回的外协明细列出
         2、把已经报工完成的外协明细列出来
         */
        startPage();
        List<BizOutsourcedOrderDetail> list = bizOutsourcedOrderDetailService.getListForReceipt(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);
    }
    /**
     * 查询所有的外协单从列表
     */
    @PreAuthorize("@ss.hasPermi('business:outsourceDetail:list')")
    @GetMapping("/listDetailForAllReceipt")
    public TableDataInfo listDetailForAllReceipt(BizOutsourcedOrderDetail bizOutsourcedOrderDetail) throws NoSuchFieldException, IllegalAccessException
    {
        //将已添加的外协明细的id，存在一个集合中,包含已经添加的收回明细，但没有提交的
        List<Long> returnReceiptListIds = bizReturnReceiptService.query().eq("supplier_id", bizOutsourcedOrderDetail.getSupplierId()).eq("is_submit",1)
                .list().stream().map(BizReturnReceipt::getId).collect(Collectors.toList());
        List<BizReturnReceiptDetail> alreadyAddedDetailList = new ArrayList<>();
        if(!returnReceiptListIds.isEmpty()){
            alreadyAddedDetailList = bizReturnReceiptDetailService.query()
                    .in("master_id", returnReceiptListIds)
                    .list();
        }
//        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、把已经报工完成的外协明细列出来
         */
        startPage();
        List<BizOutsourcedOrderDetail> list = bizOutsourcedOrderDetailService.getListForAllReceipt(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);
    }

    /**
     * 删除外协单从
     */
    @PreAuthorize("@ss.hasPermi('business:outsourceDetail:remove')")
    @Log(title = "外协单从", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids)
    {
        return toAjax(bizOutsourcedOrderDetailService.removeBatchByIds(ids));
    }
}
