package com.storlead.sales.controller.sku;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
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.MakeQuotationListDTO;
import com.storlead.sales.pojo.entity.sku.SsdProductType;
import com.storlead.sales.pojo.vo.sku.*;
import com.storlead.sales.service.sku.SsdProductService;
import com.storlead.sales.service.sku.SsdProductTypeService;
import com.storlead.sales.service.sku.SsdSkuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.env.Environment;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

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

/**
 * <p>
 * 产品管理 前端控制器
 * </p>
 *
 * @author YPZ
 * @since 2024-04-12
 */
@RestController
@RequestMapping("/sku")
@Api(tags = "销售: 产品管理相关接口")
public class SsdskuController {

    @Resource
    private SsdProductTypeService ssdProductTypeService;
    @Resource
    private SsdSkuService ssdSkuService;
    @Resource
    private SsdProductService ssdProductService;
    @Resource
    private Environment environment;

    /**
     * 查询所有产品类型 不分页
     *
     * @Author: timo
     * @Date: 2018/7/28 16:41
     * @Description: 产品类别查询
     */
    @PostMapping("/get_product_type_list")
    @ApiOperation(value = "产品管理-查询所有产品类型", notes = "产品管理-查询所有产品类型")
    public Result getProductTypeList(SsdProductType ssdProductType) {
        return ssdProductTypeService.queryProductTypeList(ssdProductType);
    }

    /**
     * @Author: timo
     * @Date: 2018/7/28 16:45
     * @Description: 获取产品类型详情
     */
    @GetMapping("/get_product_type")
    @ApiOperation(value = "产品管理-获取产品类型详情", notes = "产品管理-获取产品类型详情")
    public Result getProductType(@RequestParam(value = "productTypeId", defaultValue = "") Integer productTypeId) {

        return ssdProductTypeService.getProductType(productTypeId);
//    return Result.ok();
    }

    /**
     * ssd sku 列表
     *
     * @param ssdSku 请求参数
     * @return com.storlead.common.util.Result
     * @author blank
     * @since 2018-11-13 上午 9:34
     */
    @PostMapping("list")
    @ApiOperation(value = "产品管理-sku 列表", notes = "产品管理-sku 列表")
    public Result list(@RequestBody SsdSkuVO ssdSku) {
        return ssdSkuService.list(ssdSku);
    }

    /**
     * SSD产品分页列表
     *
     * @param ssdProductVO 请求参数
     * @return com.storlead.common.util.Result
     * @author blank
     * @since 2018-11-19 下午 6:53
     */
    @PostMapping("/get_product_list")
    @ApiOperation(value = "产品管理-SSD产品分页列表", notes = "产品管理-SSD产品分页列表")
    public Result getProductList(@RequestBody SsdProductVO ssdProductVO) {
        return ssdProductService.queryProductList(ssdProductVO);
    }

    @GetMapping("detail")
    @ApiOperation(value = "产品管理-sku详情", notes = "产品管理-sku详情")
    public Result detail(SsdSkuVO ssdSkuVO){
        return ssdSkuService.detail(ssdSkuVO);
    }

    @GetMapping("get-rate")
    @ApiOperation(value = "产品管理-汇率查询", notes = "产品管理-汇率查询")
    public Result getRate(){
        BigDecimal uSDToCNYRate = ssdSkuService.getRate();
        return Result.result(uSDToCNYRate);
    }

    /**
     * 管理后台 SKU 实时计算 价格和生产周期
     * 根据选择的参数类型去查询 该sku制造需要的天数 以及价格
     *
     * 返回对应的SKU天数 价格
     * 参见 com.storelead.storage.SsdOrderController.getSkuDetail 此方法
     *
     * @return com.storlead.common.util.Result
     * @author YPZ
     * @since 2024-8-2 下午 4:50
     */
    @PostMapping("/ssd_step_1_get_sku")
    @ApiOperation(value = "产品管理-实时计算 价格和生产周期", notes = "产品管理-实时计算 价格和生产周期")
    public Result getSkuDetail(@RequestBody MakeQuotationSkuDetailCNENVO querySkuDetailParam, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            return Result.error(bindingResult.getFieldError().getDefaultMessage());
        }

        return  ssdSkuService.ssdStepOneGetSkuDetail( querySkuDetailParam);
    }

    @PostMapping("/ssd_step_1_get_sku_list")
    @ApiOperation(value = "产品管理-实时批量计算 价格和生产周期", notes = "产品管理-实时批量计算 价格和生产周期")
    public Result getSkuDetailList(@RequestBody MakeQuotationListDTO makeQuotationListDTO, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            return Result.error(bindingResult.getFieldError().getDefaultMessage());
        }
        if (CollectionUtils.isEmpty(makeQuotationListDTO.getSsdSkuDetailVOList())){
            return Result.error("数据不能为空！");
        }

        List<Object> objList =  new ArrayList<>();
        for (MakeQuotationSkuDetailCNENVO querySkuDetailParam : makeQuotationListDTO.getSsdSkuDetailVOList()){
            Result result = ssdSkuService.ssdStepOneGetSkuDetail( querySkuDetailParam);
            if (result.getCode() != 200){
                return result;
            }
            objList.add(result.getResult());
        }
        return Result.result(objList);
    }

    @GetMapping("ssd_config")
    @ApiOperation(value = "产品管理-ssd sku 可选配置json列表", notes = "产品管理-ssd sku 可选配置json列表")
    public Result configSsdSkuJson(){
        return ssdSkuService.configSsdSkuJson();
    }

    /**
     * 下载报价单
     *
     * @param response            响应
     * @param makeQuotationListDTO 请求参数
     * @author YPZ
     * @since 2024-08-05 下午 17:20
     */
    @PostMapping("/dow-quotation-file")
    @ApiOperation(value = "产品管理-下载报价单", notes = "产品管理-下载报价单")
    public void downloadQuotationFile(HttpServletResponse response, @RequestBody MakeQuotationListDTO makeQuotationListDTO, BindingResult bindingResult) {

        List<MakeQuotationSkuDetailCNENVO> querySkuDetailParamList = makeQuotationListDTO.getSsdSkuDetailVOList();

        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";
        try {
            List<GenSsdOrderContractDataVO> ssdList = new ArrayList<>();
            for (int i = 0; i < querySkuDetailParamList.size(); i++) {
                Result result = ssdSkuService.downloadQuotationFile(querySkuDetailParamList.get(i));
                GenSsdOrderContractDataVO contractData = JSONObject.parseObject(JSONObject.toJSONString(result.getResult()), GenSsdOrderContractDataVO.class);
                contractData.setNum(i+1);
                if (!result.isSuccess()) {
                    dowFileError(response, result.getMessage());
                }
                if (!contractData.getSsdSkuCode().equals("其他费用")) {
                    totalProductCount = totalProductCount + Integer.parseInt(contractData.getProductCount());
                }
                if ((querySkuDetailParamList.get(i).getLanguageType() == 1) && (ObjectUtils.isEmpty(makeQuotationListDTO.getQuotationType()) || makeQuotationListDTO.getQuotationType() == 2)) {
                    totalOrderAmt = totalOrderAmt.add(new BigDecimal(contractData.getSkuPriceCNYWithNoRateActual()));
                }else {
                    totalOrderAmt = totalOrderAmt.add(new BigDecimal(contractData.getOrderAmt()));
                }
                if (!ObjectUtils.isEmpty(contractData.getEarnestAmt())) {
                    totalEarnestAmt = totalEarnestAmt.add(new BigDecimal(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 (querySkuDetailParamList.get(i).getLanguageType().equals(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 (querySkuDetailParamList.get(i).getLanguageType() == 1) {
                    if (ObjectUtils.isEmpty(makeQuotationListDTO.getQuotationType()) || makeQuotationListDTO.getQuotationType() == 2) {
                        contractData.setUnitPrice(contractData.getUnitPriceCNYWithNoRateActual());
                        contractData.setOrderAmt(contractData.getSkuPriceCNYWithNoRateActual());
                    }
                }

                ssdList.add(contractData);
                if (i==0){

                    if (querySkuDetailParamList.get(i).getLanguageType() == 2){
                        ftl = "templates/sku/ssdSkuQuotationEn.ftl";
                    }else {
//                        (含${zhCNTaxPriceRate}增值税)
                        //如果是海外报价
                        if (ObjectUtils.isEmpty(makeQuotationListDTO.getQuotationType()) || makeQuotationListDTO.getQuotationType() == 2) {
                            dataMap.put("zhCNTaxPriceRate","（不含增值税）");
                        }else {
                            dataMap.put("zhCNTaxPriceRate", "（含" + contractData.getZhCNTaxPriceRate() + "增值税）");
                        }
                    }
                }

            }

            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);
            dataMap.put("totalProductCount", totalProductCount);
            dataMap.put("totalOrderAmt", totalOrderAmt);
            dataMap.put("totalEarnestAmt", totalEarnestAmt);

            WordUtils.getInstance().exportDocFile(ftl, fileName, dataMap, response);

        } catch (Exception e) {
            dowFileError(response, "文件下载失败");
        }
    }

    /**
     * 下载报价单
     *
     * @param response            响应
     * @param makeQuotationListDTO 请求参数
     * @author YPZ
     * @since 2024-08-05 下午 17:20
     */
    @PostMapping("/dow-quotation-url")
    @ApiOperation(value = "产品管理-下载报价单", notes = "产品管理-下载报价单")
    public Result downloadQuotationUrl(HttpServletResponse response, @RequestBody MakeQuotationListDTO makeQuotationListDTO, BindingResult bindingResult) {

        List<MakeQuotationSkuDetailCNENVO> querySkuDetailParamList = makeQuotationListDTO.getSsdSkuDetailVOList();

        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";
        try {
            List<GenSsdOrderContractDataVO> ssdList = new ArrayList<>();
            for (int i = 0; i < querySkuDetailParamList.size(); i++) {
                Result result = ssdSkuService.downloadQuotationFile(querySkuDetailParamList.get(i));
                GenSsdOrderContractDataVO contractData = JSONObject.parseObject(JSONObject.toJSONString(result.getResult()), GenSsdOrderContractDataVO.class);
                contractData.setNum(i+1);
                if (!result.isSuccess()) {
                    dowFileError(response, result.getMessage());
                }
                if (!contractData.getSsdSkuCode().equals("其他费用")) {
                    totalProductCount = totalProductCount + Integer.parseInt(contractData.getProductCount());
                }
                if ((querySkuDetailParamList.get(i).getLanguageType() == 1) && (ObjectUtils.isEmpty(makeQuotationListDTO.getQuotationType()) || makeQuotationListDTO.getQuotationType() == 2)) {
                    totalOrderAmt = totalOrderAmt.add(new BigDecimal(contractData.getSkuPriceCNYWithNoRateActual()));
                }else {
                    totalOrderAmt = totalOrderAmt.add(new BigDecimal(contractData.getOrderAmt()));
                }
                if (!ObjectUtils.isEmpty(contractData.getEarnestAmt())) {
                    totalEarnestAmt = totalEarnestAmt.add(new BigDecimal(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 (querySkuDetailParamList.get(i).getLanguageType().equals(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 (querySkuDetailParamList.get(i).getLanguageType() == 1) {
                    if (ObjectUtils.isEmpty(makeQuotationListDTO.getQuotationType()) || makeQuotationListDTO.getQuotationType() == 2) {
                        contractData.setUnitPrice(contractData.getUnitPriceCNYWithNoRateActual());
                        contractData.setOrderAmt(contractData.getSkuPriceCNYWithNoRateActual());
                    }
                }

                ssdList.add(contractData);
                if (i==0){

                    if (querySkuDetailParamList.get(i).getLanguageType() == 2){
                        ftl = "templates/sku/ssdSkuQuotationEn.ftl";
                    }else {
//                        (含${zhCNTaxPriceRate}增值税)
                        //如果是海外报价
                        if (ObjectUtils.isEmpty(makeQuotationListDTO.getQuotationType()) || makeQuotationListDTO.getQuotationType() == 2) {
                            dataMap.put("zhCNTaxPriceRate","（不含增值税）");
                        }else {
                            dataMap.put("zhCNTaxPriceRate", "（含" + contractData.getZhCNTaxPriceRate() + "增值税）");
                        }
                    }
                }

            }

            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);
            dataMap.put("totalProductCount", totalProductCount);
            dataMap.put("totalOrderAmt", totalOrderAmt);
            dataMap.put("totalEarnestAmt", totalEarnestAmt);

//            WordUtils.getInstance().exportDocToUrl(ftl, fileName, dataMap);
            String 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) {
//            dowFileError(response, "文件下载失败");
            return Result.error("下载异常");
        }
    }

    @PostMapping("/export_word")
    @ApiOperation(value = "产品管理-下载报价单测试2", notes = "产品管理-下载报价单测试2")
    public void exportWord(HttpServletResponse response) {
        Map<String, Object> dataMap = Maps.newConcurrentMap();
        dataMap.put("title", "这是标题这是标题");
        List<GenSsdOrderContractDataVO> ssdList = new ArrayList<>();
        for (int i = 0; i < 5; i++){
            GenSsdOrderContractDataVO ssdOrderContractDataVO = new GenSsdOrderContractDataVO();
            ssdOrderContractDataVO.setSkuCode("skuuu"+i);
            ssdOrderContractDataVO.setProductCount("count"+i);
            ssdOrderContractDataVO.setUnitPrice("unitp"+i);
            ssdOrderContractDataVO.setOrderAmt("orderA哈哈"+i);
            ssdList.add(ssdOrderContractDataVO);
        }
        dataMap.put("ssdList", ssdList);

        dataMap.put("name", "你的名字2");
        dataMap.put("mobile", "你的电话2");
        dataMap.put("skuCode", "你的产品型号2");
        dataMap.put("zhCNTaxPriceRate", "10000");
        dataMap.put("zhCNTaxPriceRate", "20000");

        String ftl = "templates/sku/test.ftl";
        WordUtils.getInstance().exportDocFile(ftl, "Word导出测试", dataMap, response);
    }


    /***
      * @Description: 判断折扣是否在0-1之间
      * @Param:
      * @return:
      * @Author: YPZ
      * @Date: 2024/8/5 15:28
      */
    public boolean isDiscountValid(BigDecimal discount) {
        BigDecimal zero = BigDecimal.ZERO;
        BigDecimal one = new BigDecimal("1");

        // 检查discount是否在0（包括）和1（不包括）之间
        return discount.compareTo(zero)  >= 0 && discount.compareTo(one)  < 0;
    }

    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();
        }

    }



}
