package com.jwipc.order.controller.pc;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.jwipc.dto.ExportDataDTO;
import com.jwipc.log.annotation.AuditLogInter;
import com.jwipc.order.dto.PurchaseOrderDevPlanBaseDTO;
import com.jwipc.order.logic.PurchaseOrderPlanLogic;
import com.jwipc.order.model.po.PurchaseOrderPlanPO;
import com.jwipc.order.model.query.PurchaseOrderPlanQuery;
import com.jwipc.page.PageView;
import com.jwipc.util.EasyExcelUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

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

/**
 * @Author: swq
 * {@code @Date:} 2024/4/1 10:16
 */
@RestController
@RequestMapping(MODULE_ROOT + "/purchaseOrderPlan/rest")
@RequiredArgsConstructor
@Slf4j
public class PurchaseOrderPlanRestController {
    private final PurchaseOrderPlanLogic purchaseOrderPlanLogic;

    /**
     * 交货计划行明细数据
     */
    @AuditLogInter(value = "查询", module = "交货计划明细行")
    @RequestMapping("/list")
    public PageView list(PurchaseOrderPlanQuery query) {
        return purchaseOrderPlanLogic.getList(query);
    }

    @AuditLogInter(value = "提交", module = "交货计划明细行")
    @PostMapping("/saveOrUpdate")
    public ResponseEntity saveOrUpdate(@RequestBody List<PurchaseOrderDevPlanBaseDTO> param) {
        purchaseOrderPlanLogic.saveOrUpdate(param);
        return ResponseEntity.ok().build();
    }

    /**
     * 采购订单明细导出
     */
    @PostMapping("export")
    public void export(HttpServletResponse response, String exportFiled, String queryStr) throws IOException {
        // 查询数据列表，直接调用列表的查询，无需特殊改动
        final PurchaseOrderPlanQuery purchaseOrderPlanQuery = JSON.parseObject(queryStr, PurchaseOrderPlanQuery.class);
        final List<PurchaseOrderPlanPO> exportData = purchaseOrderPlanLogic.listAll(
                purchaseOrderPlanQuery);

        List<ExportDataDTO> exportDataDTOS = JSON.parseArray(exportFiled, ExportDataDTO.class);
        List<ExportDataDTO> newExportDataDTOS = new ArrayList<>();
        exportDataDTOS.forEach(exportDataDTO -> {
            if (exportDataDTO.getTitle().equals("采购量")) {
                //供应商填写的需要加载头颜色
                exportDataDTO.setColor(IndexedColors.RED.getIndex());
                newExportDataDTOS.add(exportDataDTO);
            } else if (exportDataDTO.getTitle().equals("计划行号")) {
                //供应商填写的需要加载头颜色
                newExportDataDTOS.add(ExportDataDTO.builder().title("计划行号").field("scheduleLine")
                        .color(IndexedColors.YELLOW.getIndex()).build());
            } else if (exportDataDTO.getTitle().contains("计划交货日期")) {
                newExportDataDTOS.add(ExportDataDTO.builder().title("计划交货日期\n(YYYY-MM-DD)").field("scheduleDeliveryDate")
                        .color(IndexedColors.YELLOW.getIndex()).build());
            } else if (exportDataDTO.getTitle().equals("计划交货数量")) {
                newExportDataDTOS.add(ExportDataDTO.builder().title("计划交货数量").field("scheduleDeliveryQuantity")
                        .color(IndexedColors.YELLOW.getIndex()).build());
                // newExportDataDTOS.add(ExportDataDTO.builder().title("是否更新(是/否)").field("isUpdate").color
                // (IndexedColors.YELLOW.getIndex()).build());
            } else if (exportDataDTO.getTitle().equals("计划删除标识")) {
                newExportDataDTOS.add(ExportDataDTO.builder().title("计划删除标识").field("delFlag")
                        .color(IndexedColors.YELLOW.getIndex()).build());
            } else {
                newExportDataDTOS.add(exportDataDTO);
            }

        });
        newExportDataDTOS.forEach(exportDataDTO -> {
            if ("delFlag".equals(exportDataDTO.getField())) {
                //插入下拉框数据，也可以从字典里取数据，只插入字典名称
                exportDataDTO.setSelectList(ListUtil.toList("是", "否"));
            }
        });
        exportData.forEach(po -> {
            if (po.getNoClearNum()!=null&&po.getNoClearNum().compareTo(BigDecimal.ZERO)==0){
                po.setWeek1(StrUtil.isNotEmpty(po.getWeek1())?"0":"");
                po.setWeek2(StrUtil.isNotEmpty(po.getWeek2())?"0":"");
                po.setWeek3(StrUtil.isNotEmpty(po.getWeek3())?"0":"");
                po.setWeek4(StrUtil.isNotEmpty(po.getWeek4())?"0":"");
                po.setWeek5(StrUtil.isNotEmpty(po.getWeek5())?"0":"");
                po.setWeek6(StrUtil.isNotEmpty(po.getWeek6())?"0":"");
                po.setWeek7(StrUtil.isNotEmpty(po.getWeek7())?"0":"");
                po.setWeek8(StrUtil.isNotEmpty(po.getWeek8())?"0":"");
                po.setDay1(StrUtil.isNotEmpty(po.getDay1())?"0":"");
                po.setDay2(StrUtil.isNotEmpty(po.getDay2())?"0":"");
                po.setDay3(StrUtil.isNotEmpty(po.getDay3())?"0":"");
                po.setDay4(StrUtil.isNotEmpty(po.getDay4())?"0":"");
                po.setDay5(StrUtil.isNotEmpty(po.getDay5())?"0":"");
                po.setDay6(StrUtil.isNotEmpty(po.getDay6())?"0":"");
                po.setDay7(StrUtil.isNotEmpty(po.getDay7())?"0":"");
                po.setMonth1(StrUtil.isNotEmpty(po.getMonth1())?"0":"");
                po.setMonth2(StrUtil.isNotEmpty(po.getMonth2())?"0":"");
                po.setMonth3(StrUtil.isNotEmpty(po.getMonth3())?"0":"");
                po.setMonth4(StrUtil.isNotEmpty(po.getMonth4())?"0":"");
            }
        });

        //动态导出工具类，只需要修改导出excel名称//隐藏的第二行修改为不隐藏，采购说排序后会导致行不存在了，导致导入失败。 2024-09-10 邓京术
        EasyExcelUtils.trendsModelWriteTow(response,
                "交货计划行数据-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN), "sheet", exportData,
                newExportDataDTOS);
    }

    @PostMapping("/importPlan")
    public ResponseEntity<Set<String>> importPlan(@RequestPart("file") MultipartFile file
    )
    {
        Set<String> msg = purchaseOrderPlanLogic.importPlan(file);
        return ResponseEntity.ok(msg);
    }
}
