package cn.ezhizao.project.business.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.ezhizao.project.business.domain.BizCarrier;
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.domain.BizOutsourcedOrderDetailProcess;
import cn.ezhizao.project.business.service.IBizOutsourcedOrderDetailProcessService;
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;

    /**
     * 查询外协单从对应的外协工序的从列表
     */
    @PreAuthorize("@ss.hasPermi('business:outsourceDetail:list')")
    @GetMapping("/list")
    @Log(title = "查询外协明细工序列表", businessType = BusinessType.SELECT)
    public TableDataInfo list(BizOutsourcedOrderDetailProcess bizOutsourcedOrderDetailProcess) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizOutsourcedOrderDetailProcess);
        startPage();
        List<BizOutsourcedOrderDetailProcess> list = bizOutsourcedOrderDetailProcessService.getList(bizOutsourcedOrderDetailProcess);
        return getDataTable(list);
    }

    /**
     * 导出外协单从对应的外协工序的从列表
     */
    @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>(BizOutsourcedOrderDetailProcess.class);
        util.exportExcel(response, list, "外协单从对应的外协工序的从数据");
    }

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

    /**
     * 新增外协单从对应的外协工序的从
     */
    @PreAuthorize("@ss.hasPermi('business:outsourceDetail:add')")
    @Log(title = "新增外协单从对应的外协工序的从", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizOutsourcedOrderDetailProcess bizOutsourcedOrderDetailProcess) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizOutsourcedOrderDetailProcess);
        return toAjax(bizOutsourcedOrderDetailProcessService.save(bizOutsourcedOrderDetailProcess));
    }

    /**
     * 修改外协单从对应的外协工序的从
     */
    @PreAuthorize("@ss.hasPermi('business:outsourceDetail:edit')")
    @Log(title = "修改外协单从对应的外协工序的从", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizOutsourcedOrderDetailProcess bizOutsourcedOrderDetailProcess) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizOutsourcedOrderDetailProcess);
        return toAjax(bizOutsourcedOrderDetailProcessService.updateById(bizOutsourcedOrderDetailProcess));
    }
    @PostMapping(value = "/getOrderDetailProcess")
    @Log(title = "查询外协工序明细列表", businessType = BusinessType.SELECT)
    public AjaxResult getOrderDetailProcess(@RequestBody BizOutsourcedOrderDetailProcess bizOutsourcedOrderDetailProcess)
    {
        List<BizOutsourcedOrderDetailProcess> list = bizOutsourcedOrderDetailProcessService.getDetailList(bizOutsourcedOrderDetailProcess);
        list.forEach(detail -> {
            detail.setReceiptNum(detail.getQualifiedNum()>0?detail.getQualifiedNum():0);
            detail.setAuditNum(detail.getReceiptNum()>0?detail.getReceiptNum():0);
            // 将字符串拆分转为对象
            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:remove')")
    @Log(title = "删除外协单从对应的外协工序的从", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids)
    {
        return toAjax(bizOutsourcedOrderDetailProcessService.removeBatchByIds(ids));
    }
}
