package com.jwipc.order.controller.pc;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.jwipc.exception.DaoException;
import com.jwipc.order.dto.ShortagePlanReleaseDTO;
import com.jwipc.order.dto.ShortagePlanReplyDTO;
import com.jwipc.order.entity.FileLog;
import com.jwipc.order.entity.ShortageData;
import com.jwipc.order.entity.ShortagePlan;
import com.jwipc.order.logic.FileLogLogic;
import com.jwipc.order.logic.ShortagePlanLogic;
import com.jwipc.order.logic.ShortagePlanLogicAsn;
import com.jwipc.order.model.po.FileLogDTO;
import com.jwipc.order.model.query.BasicForeignQuotaQuery;
import com.jwipc.order.model.query.BasicPlanQuery;
import com.jwipc.order.service.IFileLogService;
import com.jwipc.order.service.IShortageDataService;
import com.jwipc.order.service.IShortagePlanService;
import com.jwipc.order.utils.DataCheckUtils;
import com.jwipc.page.PageView;
import com.jwipc.prop.SysProp;
import com.jwipc.security.LoginUtil;
import com.jwipc.sys.client.DictClient;
import com.jwipc.sys.client.dto.DictDTO;
import com.jwipc.sys.dto.FileResposeDTO;
import com.jwipc.util.DateUtils;
import com.jwipc.util.EasyExcelImportUtils;
import com.jwipc.util.FileNameUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.jwipc.order.constant.ModuleConst.MODULE_ROOT;

/**
 * @Author: swq
 * @Date: 2024/4/28 17:08
 */
@RestController
@RequiredArgsConstructor
@RequestMapping(MODULE_ROOT + "/shortagePlan/rest")
@Slf4j
public class ShortagePlanRestController {

    private final ShortagePlanLogic shortagePlanLogic;
    private final ShortagePlanLogicAsn shortagePlanLogicAsn;
    private final IShortageDataService shortageDataService;
    private final IShortagePlanService shortagePlanService;
    private final StringRedisTemplate stringRedisTemplate;
    private final FileLogLogic fileLogLogic;
    private final RedisTemplate redisTemplate;
    private final IFileLogService fileLogService;
    private final SysProp sysProp;
    private final DictClient dictClient;

    /**
     * 标准预测计划 列表加载
     *
     * @param query
     * @return
     */
    @RequestMapping("/list")
    public PageView list(BasicPlanQuery query) {
        if (LoginUtil.isSupplier()) {
            query.setSupplierId(LoginUtil.getSupplierId());
            query.setSupplierCode(LoginUtil.getSupplierCode());
        }
        PageView pageView = shortagePlanLogic.selectListByPage(query);
        return pageView;
    }

    /**
     * 欠料管理-文件操作记录 文件操作列表
     * @param query
     * @return
     */
    @RequestMapping("/fileLogList")
    public PageView fileLogList(BasicPlanQuery query) {
        if (LoginUtil.isSupplier()) {
            query.setSupplierId(LoginUtil.getSupplierId());
            query.setSupplierCode(LoginUtil.getSupplierCode());
            query.setCreateId(LoginUtil.getSupplierId());
        } else if (LoginUtil.getUserId() != 1L) {
            query.setCreateId(LoginUtil.getUserId());
        }
        PageView pageView = fileLogLogic.selectListByPage(query);
        return pageView;
    }

    /**
     * 欠料管理-文件操作记录 文件下载
     * @param id
     * @param response
     * @return
     */
    @GetMapping("/download/{id}")
    public ResponseEntity<byte[]> downloadV2File(@PathVariable("id") Long id,
                                                 HttpServletResponse response)
    {
        FileResposeDTO fileResposeDTO = fileLogLogic.getForDownload2(id);
        if (fileResposeDTO == null) {
            return ResponseEntity.notFound().build();
        }
        String fileName = fileResposeDTO.getFileName();
        String filePath = fileResposeDTO.getFilePath();
        if(!FileUtil.exist(filePath)){
            return ResponseEntity.notFound().build();
        }
        String encodedFileName = FileNameUtil.replace(fileName);

        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        // 下载文件能正常显示中文
        response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName);
        // 实现文件下载
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(filePath);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ResponseEntity.ok().build();
    }

    /**
     * 发布页面，查询功能
     * @param basicPlanQuery
     * @return
     */
    @GetMapping("getToPublishedData")
    public PageView getToPublishedData(BasicPlanQuery basicPlanQuery) {
        PageView pageView = shortagePlanLogic.getToPublishedData(basicPlanQuery);
        return pageView;
    }

    /**
     * 待发布数据导出（按钮）
     *
     * @return
     */
    @PostMapping("exportToPublishedData")
    public void exportToPublishedData(HttpServletResponse response, String exportFiled, String queryStr) throws
            IOException
    {
        //需要变色的列  供应商 供应商编码 上线日期， 备注上线日期， 取消更新以下数据， 邓京术 2025-03-12
//        Set<String> colorList = Set.of("shortageQuantity", "demandDate", "launchDate");
        BasicPlanQuery basicPlanQuery = JSON.parseObject(queryStr, BasicPlanQuery.class);
        shortagePlanLogic.exportToPublishedData(response,exportFiled,basicPlanQuery);
    }

    /**
     * 补充供应商数据导出   这个作废 页面功能废止 （邓京术 2025-03-12）
     *
     * @return
     */
//    @PostMapping("exportToFillSupplier")
//    public void exportToFillSupplier(HttpServletResponse response, String exportFiled, String queryStr) throws
//            IOException
//    {
//        //需要变色的列
//        Set<String> colorList = Set.of("supplierCode");
//        BasicPlanQuery basicPlanQuery = JSON.parseObject(queryStr, BasicPlanQuery.class);
//        if(StringUtils.isNotEmpty(basicPlanQuery.getExportType()) && "1".equals(basicPlanQuery.getExportType())){
//            basicPlanQuery.setDataType(String.valueOf(ShortageDataType.MANUAL.getCode()));
//        }else if(StringUtils.isNotEmpty(basicPlanQuery.getExportType()) && "2".equals(basicPlanQuery.getExportType())){
//            basicPlanQuery.setDataType(String.valueOf(ShortageDataType.QUOTA.getCode()));
//        }else{
//            basicPlanQuery.setDataType(String.valueOf(ShortageDataType.MANUAL.getCode()));
//        }
//        List<ShortagePlanReleaseDTO> list = shortagePlanLogic.exportToPublishedData(basicPlanQuery);
//        // 查询数据列表，直接调用列表的查询，无需特殊改动
//        List<ExportDataDTO> exportDataDTOS = JSON.parseArray(exportFiled, ExportDataDTO.class);
//        final ExportDataDTO exportDataDTO = ExportDataDTO.builder().field("id").title("").build();
//        exportDataDTOS.add(0, exportDataDTO);
//        for (ExportDataDTO dataDTO : exportDataDTOS) {
//            if (colorList.contains(dataDTO.getField())) {
//                dataDTO.setColor(IndexedColors.YELLOW.getIndex());
//            }
//        }
//        EasyExcelUtils.trendsModelWriteTow(response,
//                "欠料补充供应商数据模板-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN), "sheet", list,
//                exportDataDTOS);
//    }

    /**
     * 欠料计划导入  这个作废 页面功能废止 （邓京术 2025-03-12）
     *
     * @param file      计划文件
     * @param startDate 开始时间
     * @return 导入是否成功
     */
    @PostMapping("/import")
    public ResponseEntity importData(@RequestPart("file") MultipartFile file, String startDate) {

        if (!shortagePlanLogic.importShortagePlan(file, startDate, LoginUtil.getUserId())) {
            return ResponseEntity.badRequest().body("操作失败");
        }
        return ResponseEntity.ok(StringPool.EMPTY);
    }

    /**
     * 该方法前端已废止 邓京术 2025-03-13
     * @param planId
     * @param request
     * @param response
     */
    @GetMapping("downloadSapData")
    public void downloadSapData(Long planId, HttpServletRequest request, HttpServletResponse response) {
        shortagePlanLogic.downloadSapData(planId, request, response);
    }

    /**
     * 欠料计划发布导入  发布页面，（上传按钮）
     *
     * @param file 计划文件
     * @return 导入是否成功
     */
    @PostMapping("/importForPublished")
    public ResponseEntity importForPublished(@RequestPart("file") MultipartFile file) {
        Long userId = LoginUtil.getUserId();
        try {
            String go_import_published = stringRedisTemplate.opsForValue().get("import_published_" + userId);
            if (null != go_import_published && go_import_published.equals("Y")) {
                throw new DaoException("数据正在导入中，请勿重复操作！");
            }
            //如果大于最大限制条件，抛出异常提醒，邓京术 2025-05-26
            List<DictDTO> dictDTOS = dictClient.getDicByType("excel_export_data_count");
            List<ShortagePlanReleaseDTO> result = Lists.newArrayList();
            List<Map<String, String>> dataList = EasyExcelImportUtils.parseExcelToData(file.getInputStream(), 2);
            String exportCount = dictDTOS.get(0).getCode();
            //异步执行导出
            if (dataList.size() > Integer.parseInt(exportCount)) {
                throw new DaoException(StrUtil.format("导入数据超过{}条", exportCount));
            }
            int i = 2;
            StringBuilder sb = new StringBuilder();
            for (Map<String, String> stringStringMap : dataList) {
                i ++ ;
                //上线日期格式校验  2025-03-12
                if (StringUtils.isNotEmpty(stringStringMap.get("launchDate"))) {
                    try {
                        String launchDateStr = stringStringMap.get("launchDate").replaceAll("/","-");
                        LocalDateTime launchDate = DateUtils.formatYYYYMMDDDash(launchDateStr);
                        stringStringMap.put("launchDate",launchDateStr);
                    } catch (Exception e) {
                        sb.append("第" + i + "行上线日期格式错误，请检查\n\r");
                    }
                }
                final ShortagePlanReleaseDTO shortagePlanReleaseDTO = BeanUtil.mapToBean(stringStringMap,
                        ShortagePlanReleaseDTO.class, true);
                //上线日期格式校验
                result.add(shortagePlanReleaseDTO);
                //如果错误达到5000长度，就抛出异常 2025-05-21 邓京术
                if (StringUtils.isNotEmpty(sb.toString()) && sb.toString().length() > 5000) {
                    throw new DaoException(sb.toString());
                }
            }
            if (StringUtils.isNotEmpty(sb.toString())) {
                throw new DaoException(sb.toString());
            }
            //如果数据超过1万条，走异步
            if (dataList.size() > sysProp.getExportMaxCount()) {
                FileLogDTO fileLogDTO = new FileLogDTO();
                fileLogDTO.setFileName(file.getResource().getFilename());
                fileLogDTO.setCreateTime(LocalDateTime.now());
                fileLogDTO.setCreateUser(userId);
                fileLogDTO.setFileSize(file.getSize());
                fileLogDTO.setFileType(2);
                fileLogDTO.setStatus("5");
                fileLogDTO.setDeleteFlag(0);
                fileLogDTO.setMsg("数据正在导入中,请耐心等待...");
                long id = fileLogLogic.createFile(fileLogDTO);
                shortagePlanLogicAsn.importForPublished(result,userId,id);
                return ResponseEntity.ok().body("数据正在导入中，请稍候在文件操作记录查看结果!");
//                return ResponseEntity.ok("数据正在导入中，请稍候在文件操作记录查看结果!");
            } else {
                shortagePlanLogic.importForPublished(result);
                return ResponseEntity.ok("导入成功!");
            }
        } catch (IOException e) {
            stringRedisTemplate.opsForValue().set("import_published_" + userId, "N", 30, TimeUnit.SECONDS);
            throw new DaoException("读取Excel失败");
        }
    }

    /**
     * 欠料计划发布导入
     *
     * @param file 计划文件
     * @return 导入是否成功
     */
    @PostMapping("/importForFillSupplier")
    public ResponseEntity importForFillSupplier(@RequestPart("file") MultipartFile file) {
        try {
            List<ShortagePlanReleaseDTO> result = Lists.newArrayList();
            List<Map<String, String>> dataList = EasyExcelImportUtils.parseExcelToData(file.getInputStream(), 2);
            for (Map<String, String> stringStringMap : dataList) {
                final ShortagePlanReleaseDTO shortagePlanReleaseDTO = BeanUtil.mapToBean(stringStringMap,
                        ShortagePlanReleaseDTO.class, true);
                shortagePlanReleaseDTO.setSupplierName(shortagePlanReleaseDTO.getSupplierCode());
                result.add(shortagePlanReleaseDTO);
            }
            shortagePlanLogic.fillSupplier(result);
            return ResponseEntity.ok().build();
        } catch (IOException e) {
            throw new DaoException("读取Excel失败");
        }
    }

//    /**
//     * 上线日期导入
//     * @param file
//     * @return
//     */
//    @PostMapping("/importForFillDate")
//    public ResponseEntity importForFillDate(@RequestPart("file") MultipartFile file) {
//        try {
//            List<ShortagePlanReleaseDTO> result = Lists.newArrayList();
//            List<Map<String, String>> dataList = EasyExcelImportUtils.parseExcelToData(file.getInputStream(), 2);
//            for (Map<String, String> stringStringMap : dataList) {
//                final ShortagePlanReleaseDTO shortagePlanReleaseDTO = BeanUtil.mapToBean(stringStringMap,
//                        ShortagePlanReleaseDTO.class, true);
//                shortagePlanReleaseDTO.setSupplierName(shortagePlanReleaseDTO.getSupplierCode());
//                result.add(shortagePlanReleaseDTO);
//            }
//            shortagePlanLogic.fillLaunchDate(result);
//            return ResponseEntity.ok().build();
//        } catch (IOException e) {
//            throw new DaoException("读取Excel失败");
//        }
//    }

    /**
     * 发布页面批量补充供应商，点保存时调用
     * @param list
     * @return
     */
    @PostMapping("batchFillSupplier")
    public ResponseEntity batchFillSupplier(@RequestBody List<ShortagePlanReleaseDTO> list) {
        shortagePlanLogic.fillSupplier(list);
        return ResponseEntity.ok().build();
    }


    /**
     * 发布页面，点击发布按钮事件
     * @param query
     * @return
     */
    @PostMapping("/published")
    public ResponseEntity published(@RequestBody BasicPlanQuery query) {
        if (LoginUtil.isSupplier()) {
            query.setSupplierId(LoginUtil.getSupplierId());
            query.setSupplierCode(LoginUtil.getSupplierCode());
        }
        List<ShortagePlanReleaseDTO> list = shortagePlanLogic.fildToPublishedData(query);
        //判断是否发布给供应商，2025-03-21号， 邓京术，

        if (CollUtil.isEmpty(list)) {
            throw new DaoException("没有需要发布的数据!");
        }
        shortagePlanLogic.published(list, query.getDeployToSupplier());
        return ResponseEntity.ok().build();
    }

    @PostMapping("/savePublished")
    public ResponseEntity savePublished(@RequestBody List<ShortagePlanReleaseDTO> list) {
        if (null == list || list.size() == 0) {
            return ResponseEntity.ok().build();
        }
        shortagePlanLogic.savePublished(list);
        return ResponseEntity.ok().build();
    }


    /**
     * 明细查看
     *
     * @param planId 计划ID
     * @return 明细查看数据
     */
    @PostMapping("/get/date/interval")
    public ResponseEntity getDateDataInterval(long planId) {
        List<ShortageData> dataList = shortagePlanLogic.selectDataList(planId);
        return ResponseEntity.ok(dataList);
    }

    /**
     * 供应商回复 查看汇总列表
     */
    @GetMapping("getReplyData")
    public PageView getSupplierReply(BasicForeignQuotaQuery q) {
        return shortagePlanLogic.getReplyData(q);
    }


    /**
     * 回复导出
     *
     * @param response 响应
     */
    @PostMapping("exportReplyData")
    public void exportReplyData(HttpServletRequest request, HttpServletResponse response, String exportFiled,
                                String queryStr) throws
            IOException
    {

        BasicForeignQuotaQuery basicPlanQuery = JSON.parseObject(queryStr, BasicForeignQuotaQuery.class);
        shortagePlanLogic.getExportReplyData(response,exportFiled,basicPlanQuery);
//        shortagePlanLogic.exportReplyData(response,exportFiled,basicPlanQuery);
    }

    /**
     * 导入回复的欠料计划，并保存至数据库
     * @param file
     * @return
     */
    @PostMapping("replyImport")
    public ResponseEntity<List<ShortagePlanReplyDTO>> replyImport(@RequestPart("file") MultipartFile file) {
        Long userId = LoginUtil.getUserId();
        try {
            List<ShortagePlanReplyDTO> result = Lists.newArrayList();
            String importReplyStr = stringRedisTemplate.opsForValue().get("import_reply_data_" + userId);
            if (null != importReplyStr && importReplyStr.equals("Y")) {
                throw new DaoException("数据正在导入中，请勿重复操作！");
            }
            List<Map<String, String>> dataList = EasyExcelImportUtils.parseExcelToData(file.getInputStream(), 2);
            //导入回复限制
            //如果大于最大限制条件，抛出异常提醒，邓京术 2025-05-26
            List<DictDTO> dictDTOS = dictClient.getDicByType("excel_export_data_count");
            String exportCount = dictDTOS.get(0).getCode();
            //异步执行导出
            if (dataList.size() > Integer.parseInt(exportCount)) {
                throw new DaoException(StrUtil.format("导入数据超过{}条", exportCount));
            }

            StringBuilder sb = new StringBuilder();
            int i = 2;
            for (Map<String, String> stringStringMap : dataList) {
                i ++;
                //校验回复的版本号是否为当天的，如果不是当天的不给回复 邓京术 2025-03-26
//                sb.append(DataCheckUtils.checkIsVersion(stringStringMap.get("shortageVersion"), i));
                //导入回复日期校验 yyyy-MM-dd 所有日期都必须大于或等于今天 ，否则报错 邓京术
                if (StringUtils.isNotEmpty(stringStringMap.get("mainMaterialReplyDate"))) {
                    initMap(stringStringMap, "mainMaterialReplyDate");
                    sb.append(DataCheckUtils.checkIsDate(stringStringMap.get("mainMaterialReplyDate"), i));
                }
                //分批交货交期回复校验 yyyy-MM-dd*数量;yyyy-MM-dd*数量
                if (StringUtils.isNotEmpty(stringStringMap.get("mainMaterialReply"))) {
                    initMap(stringStringMap, "mainMaterialReply");
                    sb.append(DataCheckUtils.checkIsDateTwo(stringStringMap.get("mainMaterialReply"), i));
                }
                sb.append(DataCheckUtils.checkIsNumber(stringStringMap.get("successorMaterialReplyQuantity"), i));
                if (StringUtils.isNotEmpty(stringStringMap.get("successorMaterialDeliveryDateReply"))) {
                    initMap(stringStringMap, "successorMaterialDeliveryDateReply");
                    sb.append(DataCheckUtils.checkIsDate(stringStringMap.get("successorMaterialDeliveryDateReply"), i));
                }
                sb.append(DataCheckUtils.checkIsNumber(stringStringMap.get("substituteMaterial1ReplyQuantity"), i));
                if (StringUtils.isNotEmpty(stringStringMap.get("substituteMaterial1DeliveryDate"))) {
                    initMap(stringStringMap, "substituteMaterial1DeliveryDate");
                    sb.append(DataCheckUtils.checkIsDate(stringStringMap.get("substituteMaterial1DeliveryDate"), i));
                }
                sb.append(DataCheckUtils.checkIsNumber(stringStringMap.get("substituteMaterial2ReplyQuantity"), i));
                if (StringUtils.isNotEmpty(stringStringMap.get("substituteMaterial2DeliveryDate"))) {
                    initMap(stringStringMap, "substituteMaterial2DeliveryDate");
                    sb.append(DataCheckUtils.checkIsDate(stringStringMap.get("substituteMaterial2DeliveryDate"), i));
                }
                sb.append(DataCheckUtils.checkIsNumber(stringStringMap.get("substituteMaterial3ReplyQuantity"), i));
                if (StringUtils.isNotEmpty(stringStringMap.get("substituteMaterial3DeliveryDate"))) {
                    initMap(stringStringMap, "substituteMaterial3DeliveryDate");
                    sb.append(DataCheckUtils.checkIsDate(stringStringMap.get("substituteMaterial3DeliveryDate"), i));
                }
                final ShortagePlanReplyDTO shortagePlanReleaseDTO = BeanUtil.mapToBean(stringStringMap,
                        ShortagePlanReplyDTO.class, true);
                result.add(shortagePlanReleaseDTO);
                //如果错误条件超过1000，则立即抛至前端，邓京术
                if (sb.toString().length() > 1000) {
                    throw new DaoException(sb.toString());
                }
            }
            //如果数据校验不通过，则抛给前端显示。
            if (sb.toString().length() > 0) {
                throw new DaoException(sb.toString());
            }
            //先把导入的数据缓存到redis, 只缓存到24：00点， 前端点击同意发布按钮时，在把缓存的数据取出来，发布到sap
            if (result.size() > sysProp.getExportMaxCount()) {
                ShortageData shortageDataTemp = shortageDataService.getById(result.get(0).getId());
                if (shortageDataTemp == null) {
                    sb.append("回复版本不是当天的版本,请检查。\n\r");
                } else {
                    ShortagePlan shortagePlan = shortagePlanService.getById(shortageDataTemp.getPlanId());
                    sb.append(DataCheckUtils.checkIsVersion(shortagePlan.getSerialNumber()));
                }
                //如果数据校验不通过，则抛给前端显示。
                if (sb.toString().length() > 0) {
                    throw new DaoException(sb.toString());
                }
                //先保存异步操作日志，邓京术
                FileLogDTO fileLogDTO = new FileLogDTO();
                fileLogDTO.setFileName(file.getResource().getFilename());
                fileLogDTO.setCreateTime(LocalDateTime.now());
                fileLogDTO.setCreateUser(userId);
                fileLogDTO.setFileSize(file.getSize());
                fileLogDTO.setFileType(4);
                fileLogDTO.setStatus("5");
                fileLogDTO.setDeleteFlag(0);
                fileLogDTO.setMsg("数据正在导入中，请耐心等待...");
                long id = fileLogLogic.createFile(fileLogDTO);
//                return ResponseEntity.ok().body("数据正在导入中，请稍候在文件操作记录查看结果!");
                //超过1万条以上的导入数据，把校验提前，然后进行异步保存操作，邓京术 2025-05-27
                shortagePlanLogic.pushReplyImportToCash(result);
                shortagePlanLogicAsn.importForReply(result,userId,id);
                return ResponseEntity.ok(result.subList(0, Math.min(result.size(), 10000)));
            } else {
                shortagePlanLogic.pushReplyImportToCash(result);
                shortagePlanLogic.saveReply(result);
                stringRedisTemplate.opsForValue().set("import_reply_data_" + LoginUtil.getUserId(), "N", 30, TimeUnit.SECONDS);
            }
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            stringRedisTemplate.opsForValue().set("import_reply_data_" + LoginUtil.getUserId(), "N", 30, TimeUnit.SECONDS);
            throw new DaoException("读取Excel失败");
        }
    }

    private void initMap(Map<String, String> stringStringMap, String key) {
        String dateStr = stringStringMap.get(key);
        dateStr = dateStr.replaceAll("/", "-");
        stringStringMap.put(key, dateStr);
    }

    /**
     * 提交到sap,页面先导入，导入的数据保存至数据库，然后先缓存到redis, 确认后，从缓存中取出推送至sap
     * @return
     */
    @PostMapping("confirmReplyImport")
    public ResponseEntity confirmReply() {
        shortagePlanLogic.confirmReply();
        return ResponseEntity.ok().build();
    }

    /**
     * 只保存需要回复的数据，不推送到sap
     * @param list
     * @return
     */
    @PostMapping("saveReply")
    public ResponseEntity saveReplay(@RequestBody List<ShortagePlanReplyDTO> list) {
        shortagePlanLogic.saveReply(list);
        return ResponseEntity.ok().build();
    }

    /**
     * 提交到sap,按查询条件
     * @param query
     * @return
     */
    @PostMapping("confirmReply")
    public ResponseEntity confirmReply(@RequestBody BasicForeignQuotaQuery query) {
        shortagePlanLogic.confirmReply(query);
        return ResponseEntity.ok().build();
    }

    /**
     * 文件操作记录页面， 导入回复数据成功，推送失败后支持重新推送sap,从缓存中取数据
     * @param logId
     * @return
     */
    @PostMapping("rePushConfirmReplyImport")
    public ResponseEntity rePushConfirmReplyImport(Long logId) {
        Long userId = LoginUtil.getUserId();
        String import_reply_data = stringRedisTemplate.opsForValue().get("confirm_reply_data_" + userId);
        if (null != import_reply_data && import_reply_data.equals("Y")) {
            throw new DaoException("数据正提交中,请耐心等待...");
        }
        Object dataobj = redisTemplate.opsForValue().get("import_reply_" + userId);
        if (null == dataobj) {
            FileLog fileLog = fileLogService.getById(logId);
            fileLog.setStatus("7");
            fileLog.setMsg("没有要推送sap的欠料数据");
            fileLogService.updateById(fileLog);
            throw new RuntimeException("没有要提交sap的数据.");
        }
        shortagePlanLogicAsn.confirmReply(true,userId,logId);
        return ResponseEntity.ok().build();
    }



    /**
     * 根据计划类型和计划ID下载计划文件  该方法已废止 邓京术 2025-03-13
     *
     * @param planId   计划ID
     * @param type     计划类型 要货计划、标准预测、外协预测 外包物料到货需求
     * @param request  请求
     * @param response 响应
     * @return 文件
     */
    @GetMapping("/download/plan/file")
    public String downloadPlanFileByTypeAndPlanId(Long planId,
                                                  @RequestParam(value = "type", defaultValue = "") String type,
                                                  HttpServletRequest request,
                                                  HttpServletResponse response,
                                                  @RequestParam(value = "downFileName", defaultValue = "") String downFileName,
                                                  @RequestParam(value = "downFilePath", defaultValue = "") String downFilePath)
    {
        return shortagePlanLogic.downloadPlanFileByTypeAndPlanId(planId, type, request, response, downFileName,
                downFilePath);
    }

    /**
     * 列表
     *
     * @return
     */
    @RequestMapping("/planList")
    public ResponseEntity<List<ShortagePlan>> planList() {

        return ResponseEntity.ok(shortagePlanLogic.selectPlanList());
    }


    /**
     * 删除欠料标准预测分配表的记录
     *
     * @param id 待删除的数据ID
     * @return 结果
     */
    @PostMapping("/remove")
    public ResponseEntity remove(String id) {
        if (Strings.isNullOrEmpty(id)) {
            return ResponseEntity.badRequest().body("参数错误, 请检查");
        }
        shortagePlanLogic.remove(id);
        return ResponseEntity.ok(true);
    }

}
