package cn.ezhizao.project.business.service.impl;

import java.io.IOException;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import cn.ezhizao.common.utils.MyHandler;
import cn.ezhizao.project.business.domain.BizOutsourcedOrderDetail;
import cn.ezhizao.project.system.domain.SysUser;
import cn.ezhizao.project.system.mapper.SysUserMapper;
import cn.hutool.core.io.IoUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import cn.ezhizao.project.business.mapper.BizOutsourcedOrderMapper;
import cn.ezhizao.project.business.domain.BizOutsourcedOrder;
import cn.ezhizao.project.business.service.IBizOutsourcedOrderService;


/**
 * 外协单主
带箱方式，是整单的。如果换新箱子，明细中，都需要更换箱子Service业务层处理
 *
 * @author ezhizao
 * @date 2024-04-26
 */
@Service
public class BizOutsourcedOrderServiceImpl  extends ServiceImpl<BizOutsourcedOrderMapper, BizOutsourcedOrder> implements IBizOutsourcedOrderService
{
    @Resource
    private BizOutsourcedOrderMapper bizOutsourcedOrderMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Value("${file.excelTemplate.url}")
    private  String templatePath;



    /**
     * 查询外协单主
带箱方式，是整单的。如果换新箱子，明细中，都需要更换箱子列表
     *
     * @param bizOutsourcedOrder 外协单主
带箱方式，是整单的。如果换新箱子，明细中，都需要更换箱子
     * @return 外协单主
带箱方式，是整单的。如果换新箱子，明细中，都需要更换箱子
     */
    @Override
    public List<BizOutsourcedOrder> getList(BizOutsourcedOrder bizOutsourcedOrder)
    {
        return bizOutsourcedOrderMapper.getList(bizOutsourcedOrder);
    }

    @Override
    public List<BizOutsourcedOrder> getAllList() {
        return bizOutsourcedOrderMapper.getAllList();
    }

    /**
     * 物理删除
     * @param bizOutsourcedOrder
     * @return 删除结果
     */
    @Override
    public int physicalDelete(BizOutsourcedOrder bizOutsourcedOrder){ return bizOutsourcedOrderMapper.physicalDelete(bizOutsourcedOrder); }


    @Override
    public void exportTemplateProvinceAreaData(HttpServletResponse response, BizOutsourcedOrder bizOutsourcedOrder) throws IOException {
        List<BizOutsourcedOrderDetail> result = bizOutsourcedOrder.getDetails();
        //因为新箱子保存的时候，是用“id|code,id|code”的字符串形式存储的所以查询的时候需要进行拆分
        //如果保存的时候没有选择新箱子则会把旧箱号复制到新箱号中，所有不会有“|”所以下方需要进行判断
        result.forEach(item->{
            // 因为需要显示箱号，所以需要拆分出code重新拼接到NewCarrier
            List<String> codeList = new ArrayList<>();
            //使用 StringTokenizer 来分割字符串
            StringTokenizer tokenizer = new StringTokenizer(item.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]);

                    }
                }else{
                    codeList.add(token);
                }
            }
            item.setNewCarrier(String.join(",", codeList));
        });
        SysUser  sysUser = sysUserMapper.selectUserById(bizOutsourcedOrder.getCreatorId());


        String template = "outsourcedSend";
        String templateFilePath =  templatePath + template + ".xlsx";
        //本地导出
        //excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build();
        //流输出
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
                .withTemplate(templateFilePath)
                .build();

        WriteSheet writeSheet = EasyExcel.writerSheet().registerWriteHandler(new MyHandler()).build();

        //配置多组数据填充完后，需要换行，防止覆盖模板中的单组数据模板
        FillConfig fillConfig = FillConfig.builder().forceNewRow(true).build();
        // 直接写入list数据
        excelWriter.fill(result, fillConfig, writeSheet);
        // 写入自定义的表头
        Map<String, Object> map = new HashMap<>();
        map.put("formCode",bizOutsourcedOrder.getFormCode());
        map.put("supplierName",bizOutsourcedOrder.getSupplierName());
        map.put("formDate",bizOutsourcedOrder.getFormDate());
        map.put("name",sysUser.getNickName());
        map.put("remark",bizOutsourcedOrder.getRemark());
        excelWriter.fill(map, writeSheet);
        excelWriter.finish();

        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=test.xlsx");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }

}
