package com.storlead.sales.controller.sku;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.util.DateUtil;
import com.storlead.framework.common.util.WordUtils;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.auth.vo.LoginUser;
import com.storlead.framework.common.result.Result;
import com.storlead.sales.pojo.dto.sku.QuotationAddDTO;
import com.storlead.sales.pojo.dto.sku.QuotationListDTO;
import com.storlead.sales.pojo.dto.sku.QuotationPriceDTO;
import com.storlead.sales.pojo.dto.sku.QuotationSearchDTO;
import com.storlead.sales.pojo.entity.sku.QuotationEntity;
import com.storlead.sales.pojo.vo.sku.*;
import com.storlead.sales.service.sku.QuotationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

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

/**
 * <p>
 * 报价单表 前端控制器
 * </p>
 *
 * @author YPZ
 * @since 2024-08-09
 */
@RestController
@RequestMapping("/quotation")
@Api(tags = "销售: 报价单相关接口")
@Log4j2
public class QuotationController {

    @Resource
    private QuotationService quotationService;

    @Resource
    private Environment environment;

    @GetMapping(value = "/get-by-id")
    @ApiOperation(value = "报价单管理查询-通过id查看详情", notes = "报价单管理查询-通过id查看详情")
    public Result<QuotationDetailVO> getById(@RequestParam(name="id",required=false) Long id) {

        QuotationDetailVO quotationDetailVO = quotationService.getQuotationDetailVOById(id);
        return Result.result(quotationDetailVO);
    }

    @GetMapping(value = "/get-amt")
    @ApiOperation(value = "报价单管理查询-通过商机/订单id查看订单总金额", notes = "报价单管理查询-通过商机/订单id查看订单总金额")
    public Result<QuotationAmtVO> getAmtById(QuotationSearchDTO quotationSearchDTO) {
        LambdaQueryWrapper<QuotationEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuotationEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        wrapper.eq(!ObjectUtils.isEmpty(quotationSearchDTO.getId()),QuotationEntity::getId,quotationSearchDTO.getId());
        wrapper.eq(!ObjectUtils.isEmpty(quotationSearchDTO.getBusinessId()),QuotationEntity::getBusinessId,quotationSearchDTO.getBusinessId());
        wrapper.eq(!ObjectUtils.isEmpty(quotationSearchDTO.getOrderFormId()),QuotationEntity::getOrderFormId,quotationSearchDTO.getOrderFormId());
        wrapper.last("limit 1");
        QuotationEntity quotation = quotationService.getOne(wrapper);
        QuotationAmtVO quotationDetailVO = new QuotationAmtVO();
        BeanUtils.copyProperties(quotation,quotationDetailVO);
        return Result.result(quotationDetailVO);
    }

    @GetMapping(value = "/get-detail")
    @ApiOperation(value = "报价单管理查询-通过商机/订单id查看详情", notes = "报价单管理查询-通过商机/订单id查看详情")
    public Result<QuotationDetailVO> geDetail(QuotationSearchDTO quotationSearchDTO) {

        QuotationDetailVO quotationDetailVO = quotationService.getQuotationDetailVO(quotationSearchDTO);
        return Result.result(quotationDetailVO);
    }

    @GetMapping(value = "/list")
    @ApiOperation(value = "报价单管理查询-通过客户id查看列表", notes = "报价单管理查询-通过客户id查看列表")
    public Result<IPage<QuotationListVO>> list(QuotationListDTO quotationListDTO) {

        return quotationService.selectListVO(quotationListDTO);
    }

    @PostMapping(value = "/add")
    @ApiOperation(value = "报价管理-新增确认报价", notes = "报价管理-新增确认报价")
    @Transactional(rollbackFor = Throwable.class)
    public Result<?> add(@RequestBody QuotationAddDTO quotationAddDTO) {
        return quotationService.addQuotation(quotationAddDTO);
    }

    @PostMapping(value = "/edit")
    @ApiOperation(value = "报价管理-编辑确认报价", notes = "报价管理-编辑确认报价")
    @Transactional(rollbackFor = Throwable.class)
    public Result<?> edit(@RequestBody QuotationAddDTO quotationAddDTO) {
        return quotationService.editQuotation(quotationAddDTO);
    }

    @PostMapping(value = "/getPriceCNY")
    @ApiOperation(value = "报价管理-根据单价获取所有报价", notes = "报价管理-根据单价获取所有报价")
    public Result<?> getPrice(@RequestBody QuotationPriceDTO quotationPriceDTO) {
        return quotationService.getPrice(quotationPriceDTO);
    }
    @PostMapping(value = "/getPriceUSD")
    @ApiOperation(value = "报价管理-根据单价获取海外报价", notes = "报价管理-根据单价获取海外报价")
    public Result<?> getPriceUSD(@RequestBody QuotationPriceDTO quotationPriceDTO) {
        return quotationService.getPriceUSD(quotationPriceDTO);
    }

    @PostMapping(value = "/getLastQuotation")
    @ApiOperation(value = "报价管理-查询用户最后一次保存的和商机、订单不关联的报价单", notes = "报价管理-查询用户最后一次保存的和商机、订单不关联的报价单")
    public Result<?> getLastQuotation(@RequestBody QuotationSearchDTO quotationSearchDTO) {
        return quotationService.getLastQuotation(quotationSearchDTO);
    }

    @PostMapping("/dow-quotation-file")
    @ApiOperation(value = "产品管理-通过商机/订单id下载报价单", notes = "产品管理-通过商机/订单id下载报价单")
    public ResponseEntity<FileSystemResource> downloadQuotationFile(@RequestBody QuotationSearchDTO quotationSearchDTO) {

//        List<MakeQuotationSkuDetailCNENVO> querySkuDetailParamList = makeQuotationListDTO.getSsdSkuDetailVOList();
        QuotationDetailVO quotationDetailVO = quotationService.getQuotationDetailVO(quotationSearchDTO);
        if (ObjectUtils.isEmpty(quotationDetailVO)) {
            return ResponseEntity.status(500).build();
        }
        LoginUser loginUser = LoginUserUtil.getLoginUser();
//        Map<String, Object> dataMap = Maps.newConcurrentMap();
        Map<String, Object> dataMap = new HashMap<>();
        // 下载报价单
        String fileName = "quotation" + DateUtil.getStringByFormat(new Date(), "yyyyMMddHHmmss");
//        BigDecimal totalOrderAmt = BigDecimal.ZERO;
//        BigDecimal totalEarnestAmt = BigDecimal.ZERO;
//        int totalProductCount = 0;
        String ftl = "templates/sku/ssdSkuQuotationCn.ftl";
        if (!ObjectUtils.isEmpty(quotationSearchDTO.getLanguageType()) && quotationSearchDTO.getLanguageType() == 2){
            ftl = "templates/sku/ssdSkuQuotationEn.ftl";
        }
        try {

            List<GenSsdOrderContractDataVO> ssdList = new ArrayList<>();
            for (int i = 0; i < quotationDetailVO.getSsdSkuDetailVOList().size(); i++) {
//                Result result = ssdSkuService.downloadQuotationFile(querySkuDetailParamList.get(i));
                quotationDetailVO.getSsdSkuDetailVOList().get(i).setSkuCode(quotationDetailVO.getSsdSkuDetailVOList().get(i).getSsdSkuCode());
                GenSsdOrderContractDataVO contractData = JSONObject.parseObject(JSONObject.toJSONString(quotationDetailVO.getSsdSkuDetailVOList().get(i)), GenSsdOrderContractDataVO.class);
                contractData.setNum(i+1);
//                totalProductCount = totalProductCount + Integer.parseInt(contractData.getProductCount());
//                totalOrderAmt = totalOrderAmt.add(new BigDecimal(contractData.getOrderAmt()));
//                if (!ObjectUtils.isEmpty(contractData.getEarnestAmt())) {
//                    totalEarnestAmt = totalEarnestAmt.add(new BigDecimal(contractData.getEarnestAmt()));
//                }



                String openPLAR = "";
                String openPLAREn = "";
                //物理销毁
                if (quotationDetailVO.getSsdSkuDetailVOList().get(i).getForceOpenPhysicalDestroy()) {
                    contractData.setOpenP("开通");
                    openPLAR = openPLAR + "物理销毁,";
                    openPLAREn = openPLAREn + "Physical Destruction,";
                } else {
                    contractData.setOpenP("不开通");
                }
                //逻辑销毁
                if (quotationDetailVO.getSsdSkuDetailVOList().get(i).getForceOpenLogicDestroy()) {
                    contractData.setOpenL("开通");
                    openPLAR = openPLAR + "逻辑销毁,";
                    openPLAREn = openPLAREn + "Logical Destruction,";
                } else {
                    contractData.setOpenL("不开通");
                }
                //AES加密
                if (quotationDetailVO.getSsdSkuDetailVOList().get(i).getForceOpenAesEncrypt()) {
                    contractData.setOpenA("开通");
                    openPLAR = openPLAR + "AES加密,";
                    openPLAREn = openPLAREn + "AES Encryption,";
                } else {
                    contractData.setOpenA("不开通");
                }
                //R备份
                if (quotationDetailVO.getSsdSkuDetailVOList().get(i).getForceOpenRapidBackup()) {
                    contractData.setOpenR("开通");
                    openPLAR = openPLAR + "R备份,";
                    openPLAREn = openPLAREn + "rBackup,";
                } else {
                    contractData.setOpenR("不开通");
                }
                if (!ObjectUtils.isEmpty(openPLAR)){
                    openPLAR =  openPLAR.substring(0,openPLAR.length()-1);
                }
                if (!ObjectUtils.isEmpty(openPLAREn)){
                    openPLAREn =  openPLAREn.substring(0,openPLAREn.length()-1);
                }
                contractData.setOpenPLAR(openPLAR);
                contractData.setOpenPLAREn(openPLAREn);
//                if (quotationSearchDTO.getLanguageType() == 2) {
//                    contractData.setOrderAmt(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceUSD()));
//                    // 总价 USD
//                    contractData.setEarnestAmt(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceUSD()));
//                    //单价 USD
//                    contractData.setUnitPrice(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getUnitPriceUSD()));
//                }else {
//                    contractData.setOrderAmt(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceCNY()));
//                    // 总价 CNY
//                    contractData.setEarnestAmt(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceCNY()));
//                    //单价 CNY
//                    contractData.setUnitPrice(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getUnitPriceCNY()));
//                }
                if (quotationSearchDTO.getLanguageType() == 2) {
                    contractData.setOrderAmt(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceUSDActual()));
                    // 总价 USD
                    contractData.setEarnestAmt(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceUSDActual()));
                    //单价 USD
                    contractData.setUnitPrice(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getUnitPriceUSDActual()));
                    if (quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuCode().equals("外部产品")){
                        contractData.setSkuCode("External Products");
                    }
                    if (quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuCode().equals("其他费用") || quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuCode().equals("额外费用")){
                        contractData.setSkuCode("Other Expenses");
                    }
                }else {
                    if (ObjectUtils.isEmpty(quotationDetailVO.getQuotationType()) || quotationDetailVO.getQuotationType() == 2) {
                        contractData.setOrderAmt(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceCNYWithNoRateActual()));
                    }else {
                        contractData.setOrderAmt(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceCNYActual()));
                    }
                    // 总价 CNY
                    contractData.setEarnestAmt(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceCNYActual()));
                    //单价 CNY
                    contractData.setUnitPrice(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getUnitPriceCNYActual()));
                }
                if (!ObjectUtils.isEmpty(quotationSearchDTO.getSkuDetailId())){
                    dataMap.put("totalProductCount", contractData.getProductCount());
                    if (ObjectUtils.isEmpty(quotationDetailVO.getQuotationType()) || quotationDetailVO.getQuotationType() == 2) {
                        dataMap.put("totalOrderAmt", quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceCNYWithNoRateActual());
                    }else {
                        dataMap.put("totalOrderAmt", quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceCNYActual());
                    }

                    dataMap.put("totalEarnestAmt", contractData.getEarnestAmt());
                }

                String specificationType;
                //判断是否是外部产品
                if (contractData.getSsdSkuCode().equals("外部产品") || contractData.getSsdSkuCode().equals("其他费用")){
                    contractData.setConnectorType("");
                    contractData.setProductSize("");
                    contractData.setConnectorProtocol("");
                    contractData.setCoreChipType("");
                    contractData.setProductLevel("");
                    contractData.setFlashChipType("");
                    contractData.setCapacity("");
                    contractData.setOpenPLAR(contractData.getSpecificationRemarks()+","+contractData.getFunctionRemarks());
                    contractData.setOpenPLAREn(contractData.getSpecificationRemarks()+","+contractData.getFunctionRemarks());
                    specificationType = contractData.getSpecificationRemarks();
                    if (ObjectUtils.isEmpty(specificationType) || specificationType.equals("null")){
                        specificationType = " ";
                    }
                    contractData.setSpecificationType(specificationType);
                }else {
                    if (quotationSearchDTO.getLanguageType() == 1){
                        specificationType = contractData.getConnectorType() + "," + contractData.getProductSize() + "," + contractData.getConnectorProtocol() + "," +contractData.getCoreChipType() + "," + contractData.getProductLevel() + "," + contractData.getFlashChipType() + "," + contractData.getCapacity() + "," + contractData.getOpenPLAR();
                    }else {
                        specificationType = contractData.getConnectorType() + "," + contractData.getProductSize() + "," + contractData.getConnectorProtocol() + "," +contractData.getCoreChipType() + ","  + contractData.getProductLevel() + "," + contractData.getFlashChipType() + "," + contractData.getCapacity() + "," + contractData.getOpenPLAREn();
                    }

                    contractData.setSpecificationType(specificationType);

                }

                if(ObjectUtils.isEmpty(contractData.getSpecificationType())){
                    contractData.setSpecificationType("");
                }


//                if (!ObjectUtils.isEmpty(contractData.getZhCNTaxPriceRate())){
//                    dataMap.put("zhCNTaxPriceRate", contractData.getZhCNTaxPriceRate());
//
//                }

                //如果是海外报价
                if (ObjectUtils.isEmpty(quotationDetailVO.getQuotationType()) || quotationDetailVO.getQuotationType() == 2) {
                    dataMap.put("zhCNTaxPriceRate","（不含增值税）");
                    if (quotationSearchDTO.getLanguageType() == 1) {
                        contractData.setUnitPrice(contractData.getUnitPriceCNYWithNoRateActual());
                        contractData.setOrderAmt(contractData.getSkuPriceCNYWithNoRateActual());
                    }
                }else {
                    dataMap.put("zhCNTaxPriceRate", "（含" + contractData.getZhCNTaxPriceRate() + "增值税）");

                }
                ssdList.add(contractData);

            }

            Calendar calendar = Calendar.getInstance();
            dataMap.put("name", loginUser.getRealName());
            dataMap.put("year", String.valueOf(calendar.get(Calendar.YEAR)));
            dataMap.put("month", (calendar.get(Calendar.MONTH)  + 1));
            dataMap.put("day", calendar.get(Calendar.DAY_OF_MONTH));
            dataMap.put("mobile", loginUser.getMobile());
            dataMap.put("ssdList", ssdList);
            if (ObjectUtils.isEmpty(quotationSearchDTO.getSkuDetailId())){
                dataMap.put("totalProductCount", quotationDetailVO.getTotalNumber());

                dataMap.put("totalOrderAmt", quotationDetailVO.getTotalOrderAmt());

                dataMap.put("totalEarnestAmt", quotationDetailVO.getTotalEarnestAmt());
            }

           return  WordUtils.getInstance().repExportDocFile(ftl, fileName, dataMap);

//            List<String> fileList = new ArrayList<>();
//            fileList.add(fileName);
//            WordUtilsTest.exportWord(dataMap, fileName, ftl, response);

        } catch (Exception e) {
//            log.error("导出word失败", e);
//            dowFileError(response, "文件下载失败");
            return ResponseEntity.status(500).build();
        }
    }


    @PostMapping("/dow-quotation-url")
    @ApiOperation(value = "产品管理-通过商机/订单id下载报价单", notes = "产品管理-通过商机/订单id下载报价单")
    public Result downloadQuotationUrl(@RequestBody QuotationSearchDTO quotationSearchDTO) {

//        List<MakeQuotationSkuDetailCNENVO> querySkuDetailParamList = makeQuotationListDTO.getSsdSkuDetailVOList();
        QuotationDetailVO quotationDetailVO = quotationService.getQuotationDetailVO(quotationSearchDTO);
        if (ObjectUtils.isEmpty(quotationDetailVO)) {
            return Result.error("下载异常");
        }
        LoginUser loginUser = LoginUserUtil.getLoginUser();
//        Map<String, Object> dataMap = Maps.newConcurrentMap();
        Map<String, Object> dataMap = new HashMap<>();
        // 下载报价单
        String fileName = "quotation" + DateUtil.getStringByFormat(new Date(), "yyyyMMddHHmmss");
//        BigDecimal totalOrderAmt = BigDecimal.ZERO;
//        BigDecimal totalEarnestAmt = BigDecimal.ZERO;
//        int totalProductCount = 0;
        String ftl = "templates/sku/ssdSkuQuotationCn.ftl";
        if (!ObjectUtils.isEmpty(quotationSearchDTO.getLanguageType()) && quotationSearchDTO.getLanguageType() == 2){
            ftl = "templates/sku/ssdSkuQuotationEn.ftl";
        }
        String url = "";
        try {

            List<GenSsdOrderContractDataVO> ssdList = new ArrayList<>();
            for (int i = 0; i < quotationDetailVO.getSsdSkuDetailVOList().size(); i++) {
//                Result result = ssdSkuService.downloadQuotationFile(querySkuDetailParamList.get(i));
                quotationDetailVO.getSsdSkuDetailVOList().get(i).setSkuCode(quotationDetailVO.getSsdSkuDetailVOList().get(i).getSsdSkuCode());
                GenSsdOrderContractDataVO contractData = JSONObject.parseObject(JSONObject.toJSONString(quotationDetailVO.getSsdSkuDetailVOList().get(i)), GenSsdOrderContractDataVO.class);
                contractData.setNum(i+1);
//                totalProductCount = totalProductCount + Integer.parseInt(contractData.getProductCount());
//                totalOrderAmt = totalOrderAmt.add(new BigDecimal(contractData.getOrderAmt()));
//                if (!ObjectUtils.isEmpty(contractData.getEarnestAmt())) {
//                    totalEarnestAmt = totalEarnestAmt.add(new BigDecimal(contractData.getEarnestAmt()));
//                }



                String openPLAR = "";
                String openPLAREn = "";
                //物理销毁
                if (quotationDetailVO.getSsdSkuDetailVOList().get(i).getForceOpenPhysicalDestroy()) {
                    contractData.setOpenP("开通");
                    openPLAR = openPLAR + "物理销毁,";
                    openPLAREn = openPLAREn + "Physical Destruction,";
                } else {
                    contractData.setOpenP("不开通");
                }
                //逻辑销毁
                if (quotationDetailVO.getSsdSkuDetailVOList().get(i).getForceOpenLogicDestroy()) {
                    contractData.setOpenL("开通");
                    openPLAR = openPLAR + "逻辑销毁,";
                    openPLAREn = openPLAREn + "Logical Destruction,";
                } else {
                    contractData.setOpenL("不开通");
                }
                //AES加密
                if (quotationDetailVO.getSsdSkuDetailVOList().get(i).getForceOpenAesEncrypt()) {
                    contractData.setOpenA("开通");
                    openPLAR = openPLAR + "AES加密,";
                    openPLAREn = openPLAREn + "AES Encryption,";
                } else {
                    contractData.setOpenA("不开通");
                }
                //R备份
                if (quotationDetailVO.getSsdSkuDetailVOList().get(i).getForceOpenRapidBackup()) {
                    contractData.setOpenR("开通");
                    openPLAR = openPLAR + "R备份,";
                    openPLAREn = openPLAREn + "rBackup,";
                } else {
                    contractData.setOpenR("不开通");
                }
                if (!ObjectUtils.isEmpty(openPLAR)){
                    openPLAR =  openPLAR.substring(0,openPLAR.length()-1);
                }
                if (!ObjectUtils.isEmpty(openPLAREn)){
                    openPLAREn =  openPLAREn.substring(0,openPLAREn.length()-1);
                }
                contractData.setOpenPLAR(openPLAR);
                contractData.setOpenPLAREn(openPLAREn);
//                if (quotationSearchDTO.getLanguageType() == 2) {
//                    contractData.setOrderAmt(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceUSD()));
//                    // 总价 USD
//                    contractData.setEarnestAmt(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceUSD()));
//                    //单价 USD
//                    contractData.setUnitPrice(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getUnitPriceUSD()));
//                }else {
//                    contractData.setOrderAmt(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceCNY()));
//                    // 总价 CNY
//                    contractData.setEarnestAmt(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceCNY()));
//                    //单价 CNY
//                    contractData.setUnitPrice(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getUnitPriceCNY()));
//                }
                if (quotationSearchDTO.getLanguageType() == 2) {
                    contractData.setOrderAmt(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceUSDActual()));
                    // 总价 USD
                    contractData.setEarnestAmt(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceUSDActual()));
                    //单价 USD
                    contractData.setUnitPrice(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getUnitPriceUSDActual()));
                    if (quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuCode().equals("外部产品")){
                        contractData.setSkuCode("External Products");
                    }
                    if (quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuCode().equals("其他费用") || quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuCode().equals("额外费用")){
                        contractData.setSkuCode("Other Expenses");
                    }
                }else {
                    if (ObjectUtils.isEmpty(quotationDetailVO.getQuotationType()) || quotationDetailVO.getQuotationType() == 2) {
                        contractData.setOrderAmt(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceCNYWithNoRateActual()));
                    }else {
                        contractData.setOrderAmt(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceCNYActual()));
                    }
                    // 总价 CNY
                    contractData.setEarnestAmt(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceCNYActual()));
                    //单价 CNY
                    contractData.setUnitPrice(String.valueOf(quotationDetailVO.getSsdSkuDetailVOList().get(i).getUnitPriceCNYActual()));
                }
                if (!ObjectUtils.isEmpty(quotationSearchDTO.getSkuDetailId())){
                    dataMap.put("totalProductCount", contractData.getProductCount());
                    if (ObjectUtils.isEmpty(quotationDetailVO.getQuotationType()) || quotationDetailVO.getQuotationType() == 2) {
                        dataMap.put("totalOrderAmt", quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceCNYWithNoRateActual());
                    }else {
                        dataMap.put("totalOrderAmt", quotationDetailVO.getSsdSkuDetailVOList().get(i).getSkuPriceCNYActual());
                    }

                    dataMap.put("totalEarnestAmt", contractData.getEarnestAmt());
                }

                String specificationType;
                //判断是否是外部产品
                if (contractData.getSsdSkuCode().equals("外部产品") || contractData.getSsdSkuCode().equals("其他费用")){
                    contractData.setConnectorType("");
                    contractData.setProductSize("");
                    contractData.setConnectorProtocol("");
                    contractData.setCoreChipType("");
                    contractData.setProductLevel("");
                    contractData.setFlashChipType("");
                    contractData.setCapacity("");
                    contractData.setOpenPLAR(contractData.getSpecificationRemarks()+","+contractData.getFunctionRemarks());
                    contractData.setOpenPLAREn(contractData.getSpecificationRemarks()+","+contractData.getFunctionRemarks());
                    specificationType = contractData.getSpecificationRemarks();
                    if (ObjectUtils.isEmpty(specificationType) || specificationType.equals("null")){
                        specificationType = " ";
                    }
                    contractData.setSpecificationType(specificationType);
                }else {
                    if (quotationSearchDTO.getLanguageType() == 1){
                        specificationType = contractData.getConnectorType() + "," + contractData.getProductSize() + "," + contractData.getConnectorProtocol() + "," +contractData.getCoreChipType() + "," + contractData.getProductLevel() + "," + contractData.getFlashChipType() + "," + contractData.getCapacity() + "," + contractData.getOpenPLAR();
                    }else {
                        specificationType = contractData.getConnectorType() + "," + contractData.getProductSize() + "," + contractData.getConnectorProtocol() + "," +contractData.getCoreChipType() + ","  + contractData.getProductLevel() + "," + contractData.getFlashChipType() + "," + contractData.getCapacity() + "," + contractData.getOpenPLAREn();
                    }

                    contractData.setSpecificationType(specificationType);

                }

                if(ObjectUtils.isEmpty(contractData.getSpecificationType())){
                    contractData.setSpecificationType("");
                }


//                if (!ObjectUtils.isEmpty(contractData.getZhCNTaxPriceRate())){
//                    dataMap.put("zhCNTaxPriceRate", contractData.getZhCNTaxPriceRate());
//
//                }

                //如果是海外报价
                if (ObjectUtils.isEmpty(quotationDetailVO.getQuotationType()) || quotationDetailVO.getQuotationType() == 2) {
                    dataMap.put("zhCNTaxPriceRate","（不含增值税）");
                    if (quotationSearchDTO.getLanguageType() == 1) {
                        contractData.setUnitPrice(contractData.getUnitPriceCNYWithNoRateActual());
                        contractData.setOrderAmt(contractData.getSkuPriceCNYWithNoRateActual());
                    }
                }else {
                    dataMap.put("zhCNTaxPriceRate", "（含" + contractData.getZhCNTaxPriceRate() + "增值税）");

                }
                ssdList.add(contractData);

            }

            Calendar calendar = Calendar.getInstance();
            dataMap.put("name", loginUser.getRealName());
            dataMap.put("year", String.valueOf(calendar.get(Calendar.YEAR)));
            dataMap.put("month", (calendar.get(Calendar.MONTH)  + 1));
            dataMap.put("day", calendar.get(Calendar.DAY_OF_MONTH));
            dataMap.put("mobile", loginUser.getMobile());
            dataMap.put("ssdList", ssdList);
            if (ObjectUtils.isEmpty(quotationSearchDTO.getSkuDetailId())){
                dataMap.put("totalProductCount", quotationDetailVO.getTotalNumber());

                dataMap.put("totalOrderAmt", quotationDetailVO.getTotalOrderAmt());

                dataMap.put("totalEarnestAmt", quotationDetailVO.getTotalEarnestAmt());
            }

            url = WordUtils.getInstance().exportDocToUrl(ftl, fileName, dataMap);
            if (url == null) {
                return Result.error("下载异常");
            }
            String active = environment.getProperty("spring.profiles.active");
            String port =  environment.getProperty("server.port");
            String domainUrl = "";
            if(active.equals("prod")) {
                domainUrl = "https://sales.storlead.com"+url;
            } else if (active.equals("test")){
                domainUrl = "https://sales.test.storlead.com"+url;
            } else if (active.equals("dev")){
                domainUrl = "http://localhost:"+port+url;
            }

//            domainUrl = "https://sp-sales-test.oss-cn-shenzhen.aliyuncs.com/20250826/quotation202508261659161700413628.doc";
            return Result.result(domainUrl);

        } catch (Exception e) {
//            log.error("导出word失败", e);
//            dowFileError(response, "文件下载失败");
            return Result.error("下载异常");
        }
    }


    public void dowFileError(HttpServletResponse response, String errorMsg) {
        try {
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            response.getWriter().write("<script language=javascript>alert('" + errorMsg + "');</script>");
        } catch (Exception e) {
            e.getMessage();
        }
    }

    @ApiOperation(value = "报价管理-删除", notes = "报价管理-删除")
    @PostMapping("deleteById")
    public Result delete(Long id) {
        if (ObjectUtils.isEmpty( id)){
            return Result.error("参数错误");
        }
        QuotationEntity quotationEntity = quotationService.getById(id);
        if (ObjectUtils.isEmpty(quotationEntity)){
            return Result.error("数据不存在");
        }
        if (!ObjectUtils.isEmpty(quotationEntity.getOrderFormId()) && !quotationEntity.getOrderFormId().equals(0L)){
            return Result.error("该报价单已关联订单，无法删除");
        }
        if (!ObjectUtils.isEmpty(quotationEntity.getBusinessId()) && !quotationEntity.getBusinessId().equals(0L)){
            return Result.error("该报价单已关联商机，无法删除");
        }
        quotationEntity.setIsDelete(CommonConstant.DEL_FLAG_1);
        boolean result = quotationService.updateById(quotationEntity);
        return result ? Result.result("删除成功") : Result.error("删除失败");
    }
}
