package com.jwipc.inquiry.controller.rest;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.jwipc.constant.DictCode;
import com.jwipc.dto.ExportDataDTO;
import com.jwipc.dto.ExportEnumDataDTO;
import com.jwipc.exception.DaoException;
import com.jwipc.inquiry.dto.*;
import com.jwipc.inquiry.entity.InquiryMaterialSupplier;
import com.jwipc.inquiry.logic.InquiryLogic;
import com.jwipc.inquiry.logic.InquiryMaterialLogic;
import com.jwipc.inquiry.logic.InquiryMaterialSupplierLogic;
import com.jwipc.inquiry.logic.InquirySupplierLogic;
import com.jwipc.inquiry.model.query.InquiryMaterialQuery;
import com.jwipc.inquiry.model.query.InquiryQuoteQuery;
import com.jwipc.inquiry.model.query.PriceInfoQuery;
import com.jwipc.log.annotation.AuditLogInter;
import com.jwipc.order.clent.dto.PurchaseDetailDTO;
import com.jwipc.order.client.PurchaseOrderClient;
import com.jwipc.page.PageView;
import com.jwipc.security.LoginUtil;
import com.jwipc.supplier.clent.dto.SupplierDTO;
import com.jwipc.supplier.client.SupplierClient;
import com.jwipc.sys.client.DictClient;
import com.jwipc.sys.client.dto.DictDTO;
import com.jwipc.sys.client.dto.TaxDTO;
import com.jwipc.util.EasyExcelUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

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

/**
 * @author shenyang.ou
 * @date 2024/2/4 19:48
 * @desc 询价定价
 */
@RestController
@RequestMapping(MODULE_ROOT+ "/fix/rest")
@RequiredArgsConstructor
public class InquiryFixRestController {
    private final InquiryLogic inquiryLogic;
    private final InquirySupplierLogic inquirySupplierLogic;
    private final InquiryMaterialSupplierLogic inquiryMaterialSupplierLogic;
    private final InquiryMaterialLogic inquiryMaterialLogic;
    private final DictClient dictClient;
    private final PurchaseOrderClient purchaseOrderClient;
    private final SupplierClient supplierClient;
    /**
     * 物料供应商列表
     * @param query 参数
     */
    @RequestMapping("/material/supplier/list")
    public ResponseEntity<List<InquiryMaterialSupplierDTO>> materialSupplierList(InquiryQuoteQuery query) {
        List<InquiryMaterialSupplierDTO> inquiryMaterialSupplierDTOS = inquiryMaterialSupplierLogic.quoteList(query);
        return ResponseEntity.ok(inquiryMaterialSupplierDTOS);
    }

    /**
     * 物料供应商列表
     * @param query 参数
     */
    @RequestMapping("/material/supplier/list/page")
    @AuditLogInter(module = "比价报表",value = "导出按钮")
    public PageView materialSupplierListPage(InquiryQuoteQuery query) {
        return inquiryMaterialSupplierLogic.quoteListPage(query);
    }

    /**
     * 物料供应商列表导出
     * @param exportFiled 导出的列信息
     * @param queryStr 查询条件
     */
    @PostMapping("/material/supplier/export")
    public void export(HttpServletResponse response, String exportFiled, String queryStr) throws IOException {
        // 查询数据列表，直接调用列表的查询，无需特殊改动
        final List<InquiryMaterialSupplierDTO> exportData = inquiryMaterialSupplierLogic.quoteList(JSON.parseObject(queryStr, InquiryQuoteQuery.class));
        //动态导出工具类，只需要修改导出excel名称
        EasyExcelUtils.trendsModelWrite(response,"物料供应商记录-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN),"sheet", exportData, exportFiled);
    }

    /**
     * 物料供应商数据补充导出
     * @param exportFiled 导出的列信息
     * @param queryStr 查询条件
     */
    @PostMapping("/material/supplier/data/export")
    public void dataExport(HttpServletResponse response, String exportFiled, String queryStr) throws IOException {
        List<ExportDataDTO> exportDataDTOS = new ArrayList<>();
        //先加载固定字段
        exportDataDTOS.add(ExportDataDTO.builder().title("").field("id").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("").field("inquiryMaterialId").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("物料编码").field("materialCode").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("物料名称").field("materialName").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("有效期起始日").field("quoteFromDate").exportDateFormatter("date").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("有效期结束日").field("quoteEndDate").exportDateFormatter("date").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("货期（天）").field("confirmDeliveryDate").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("最小包装量").field("mpq").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("最小订货量").field("moq").build());
        // 查询数据列表，直接调用列表的查询，无需特殊改动
        List<InquiryMaterialSupplierDTO> exportData = inquiryMaterialSupplierLogic.quoteList(JSON.parseObject(queryStr, InquiryQuoteQuery.class));
//        final List<InquiryMaterialDTO> exportData = inquiryMaterialLogic.listAll(JSON.parseObject(queryStr, InquiryMaterialQuery.class));
        //动态导出工具类，只需要修改导出excel名称
        EasyExcelUtils.trendsModelWrite(response,"数据补充导出-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN),"sheet", exportData, JSON.toJSONString(exportDataDTOS));
    }

    /**
     * 定价导出
     * @param exportFiled 导出的列信息
     * @param queryStr 查询条件
     */
    @PostMapping("/material/supplier/fix/export")
    public void fixExport(HttpServletResponse response, String exportFiled, String queryStr) throws IOException {
        List<ExportDataDTO> exportDataDTOS = new ArrayList<>();
        //先加载固定字段
        exportDataDTOS.add(ExportDataDTO.builder().title("").field("id").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("").field("inquiryMaterialId").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("物料编码").field("materialCode").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("物料名称").field("materialName").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("详细规格参数").field("materialSpec").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("供应商编码").field("supplierShortName").build());
        List<DictDTO> dictDTOS = dictClient.getDicByType(DictCode.CURRENCY.getCode());
        List<ExportEnumDataDTO> currencyEnum = new ArrayList<>();
        dictDTOS.forEach(dictDTO -> {
            ExportEnumDataDTO exportEnumDataDTO = new ExportEnumDataDTO();
            exportEnumDataDTO.setCode(dictDTO.getCode());
            exportEnumDataDTO.setCodeWithDesc(dictDTO.getCodeWithDesc());
            currencyEnum.add(exportEnumDataDTO);
        });
        exportDataDTOS.add(ExportDataDTO.builder().title("币别").field("currencyCode").exportEnum(currencyEnum).build());
        exportDataDTOS.add(ExportDataDTO.builder().title("原中标价格(含税)").field("lastBidPrice").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("原中标价格(含税)").field("lastBidPrice").build());
        List<DictDTO> paymentMethodDTOS = dictClient.getDicByType(DictCode.PAYMENT_TERMS.getCode());
        List<ExportEnumDataDTO> paymentMethodEnum = new ArrayList<>();
        paymentMethodDTOS.forEach(dictDTO -> {
            ExportEnumDataDTO exportEnumDataDTO = new ExportEnumDataDTO();
            exportEnumDataDTO.setCode(dictDTO.getCode());
            exportEnumDataDTO.setCodeWithDesc(dictDTO.getCodeWithDesc());
            paymentMethodEnum.add(exportEnumDataDTO);
        });
        exportDataDTOS.add(ExportDataDTO.builder().title("付款条件").field("paymentMethod").exportEnum(paymentMethodEnum).build());
        List<ExportEnumDataDTO> flagEnum = new ArrayList<>();
        ExportEnumDataDTO exportEnumDataDTO = new ExportEnumDataDTO();
        exportEnumDataDTO.setCode("0");
        exportEnumDataDTO.setCodeWithDesc("否");
        flagEnum.add(exportEnumDataDTO);
        ExportEnumDataDTO exportEnumDataDTO1 = new ExportEnumDataDTO();
        exportEnumDataDTO1.setCode("1");
        exportEnumDataDTO1.setCodeWithDesc("是");
        flagEnum.add(exportEnumDataDTO1);
        exportDataDTOS.add(ExportDataDTO.builder().title("定价").field("bidFlag").exportEnum(flagEnum).selectList(ListUtil.toList("是","否")).color(IndexedColors.YELLOW.getIndex()).build());
        exportDataDTOS.add(ExportDataDTO.builder().title("是否最低价").field("minPriceFlag").exportEnum(flagEnum).build());
        exportDataDTOS.add(ExportDataDTO.builder().title("最终含税单价").field("taxPrice").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("最初含税单价").field("firstTaxPrice").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("配额%").field("confirmQuota").color(IndexedColors.YELLOW.getIndex()).build());
        exportDataDTOS.add(ExportDataDTO.builder().title("期望价格(含税)").field("desirePrice").color(IndexedColors.YELLOW.getIndex()).build());
        exportDataDTOS.add(ExportDataDTO.builder().title("议价意见").field("priceOpinion").color(IndexedColors.YELLOW.getIndex()).build());
        // 查询数据列表，直接调用列表的查询，无需特殊改动
        List<InquiryMaterialSupplierDTO> exportData = inquiryMaterialSupplierLogic.quoteList(JSON.parseObject(queryStr, InquiryQuoteQuery.class));
        //动态导出工具类，只需要修改导出excel名称
        EasyExcelUtils.trendsModelWrite(response,"定价议价导出-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN),"sheet", exportData, JSON.toJSONString(exportDataDTOS));
    }

    /**
     * 物料供应商数据补充导入
     * @param file 文件
     */
    @RequestMapping("/material/supplier/data/import")
    @AuditLogInter(module = "比价定价",value = "详情面-物料供应商数据补充导入")
    public ResponseEntity dataImport(@RequestPart("file") MultipartFile file){
        inquiryMaterialSupplierLogic.dataImport(file);
        return ResponseEntity.ok(true);
    }

    /**
     * 物料供应商数据补充导入
     * @param file 文件
     */
    @RequestMapping("/material/supplier/fix/import")
    @AuditLogInter(module = "比价定价",value = "详情面-导入供应商议价列表")
    public ResponseEntity fixImport(@RequestPart("file") MultipartFile file){
        List<Map<String,String>> dataList = inquiryMaterialSupplierLogic.fixImport(file);
        return ResponseEntity.ok(dataList);
    }

    /**
     * 定价报表导出
     * @param exportFiled 导出的列信息
     * @param queryStr 查询条件
     */
    @PostMapping("/material/supplier/report/export")
    @AuditLogInter(module = "比价定价",value = "详情面-导出供应商定价列表")
    public void reportExport(HttpServletResponse response, String exportFiled, String queryStr) throws IOException {
        // 查询数据列表，直接调用列表的查询，无需特殊改动
        final List<InquiryMaterialSupplierDTO> exportData = inquiryMaterialSupplierLogic.quoteList(JSON.parseObject(queryStr, InquiryQuoteQuery.class));
        //动态导出工具类，只需要修改导出excel名称
        EasyExcelUtils.trendsModelWrite(response,"比价报表-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN),"sheet", exportData, exportFiled);
    }

    /**
     * 供应商附件列表
     * @param inquiryId 询价id
     */
    @RequestMapping("/supplier/file/list")
    @AuditLogInter(module = "比价定价",value = "详情面-供应商附件列表")
    public ResponseEntity<List<InquirySupplierDTO>> supplierFileList(Long inquiryId) {
        List<InquirySupplierDTO> inquirySupplierDTOS = inquirySupplierLogic.listByInquiryId(inquiryId);
        return ResponseEntity.ok(inquirySupplierDTOS);
    }

    /**
     * 更新询价物料和供应商数据
     */
    @PostMapping("/updateMaterialAndSupplierData")
    public ResponseEntity updateMaterialAndSupplierData(Long inquiryMaterialId, Long inquiryMaterialSupplierId, String materialCode, String quoteFromDate, String quoteEndDate,Integer confirmDeliveryDate,Long mpq,Long moq,String supplierCode) {
        inquiryLogic.updateMaterialAndSupplierData(inquiryMaterialId,inquiryMaterialSupplierId,materialCode,quoteFromDate,quoteEndDate,confirmDeliveryDate,mpq,moq,supplierCode);
        return ResponseEntity.ok(true);
    }

    /**
     * 议价
     *
     * @param param 参数
     */
    @PostMapping("/bargain")
    @AuditLogInter(module = "比价定价",value = "详情页-议价按钮")
    public ResponseEntity bargain(@RequestBody InquirySupplierBargainParamDTO param) {
        inquiryMaterialSupplierLogic.bargain(param);
        return ResponseEntity.ok(true);
    }

    /**
     * 议价截止
     *
     * @param param 参数
     */
    @PostMapping("/bargain/end")
    @AuditLogInter(module = "比价定价",value = "详情面-议价截止按钮")
    public ResponseEntity bargainEnd(@RequestBody InquirySupplierBargainParamDTO param) {
        inquiryMaterialSupplierLogic.bargainEnd(param);
        return ResponseEntity.ok(true);
    }

    /**
     * 定价
     *
     * @param param 参数
     */
    @PostMapping("/fixPrice")
    @AuditLogInter(module = "比价定价",value = "详情-定价按钮")
    public ResponseEntity fixPrice(@RequestBody InquirySupplierBargainParamDTO param) {
        //校验待淘汰供应商是否存在历史订单
        inquiryMaterialSupplierLogic.checkEliminateFlag(param);
        //定价
        inquiryMaterialSupplierLogic.fixPrice(param);
        return ResponseEntity.ok(true);
    }

    /**
     * 计算配额
     *
     * @param param 参数
     */
    @PostMapping("/calculateQuota")
    @AuditLogInter(module = "比价定价",value = "详情面-计算配额按钮")
    public ResponseEntity calculateQuota(@RequestBody InquirySupplierCalculateQuotaParamDTO param) {
        inquiryMaterialSupplierLogic.calculateQuota(param);
        return ResponseEntity.ok(true);
    }

    /**
     * 定价确认
     *
     * @param param 参数
     */
    @PostMapping("/fixConfirm")
    @AuditLogInter(module = "比价定价",value = "详情面-定价确认按钮")
    public ResponseEntity fixConfirm(@RequestBody InquirySupplierBargainConfirmParamDTO param) {
        inquiryMaterialSupplierLogic.fixConfirm(param);
        return ResponseEntity.ok(true);
    }

    /**
     * 主管确认
     *
     * @param param 参数
     */
    @PostMapping("/chargeConfirm")
    @AuditLogInter(module = "比价定价",value = "详情面-主管确认按钮")
    public ResponseEntity chargeConfirm(@RequestBody InquirySupplierBargainConfirmParamDTO param) {
        inquiryMaterialSupplierLogic.chargeConfirm(param);
        return ResponseEntity.ok(true);
    }
}
