package org.dromara.zhishu.service.impl;

import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.service.ISysConfigService;
import org.dromara.zhishu.domain.ZhishuShopGoods;
import org.dromara.zhishu.domain.ZhishuShopImages;
import org.dromara.zhishu.domain.vo.*;
import org.dromara.zhishu.service.*;
import org.dromara.zhishu.util.CnumberUtils;
import org.dromara.zhishu.util.ImageUtils;
import org.dromara.zhishu.util.InterfaceUtils;
import org.dromara.zhishu.util.UploadUtil;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Path;
import java.util.*;

/**
 * 店铺主表Service业务层处理
 *
 * @author yxy
 * @date 2025-05-8
 */
@RequiredArgsConstructor
@Service
public class KongfzServiceImpl implements IKongFzService {

    private final IShopService shopService;
    private final ISysConfigService configService;
    private final IBookBaseInfoService bookBaseInfoService;
    private final IZhishuShopImagesService zhishuShopImagesService;
    private final IPriceTemplateService priceTemplateService;
    private final IShopImgService shopImgService;

//    @Override
//    public void goodAdd(String shopId, ZhishuShopGoods zhishuShopGoods, ShopDetailVo shopDetailVo) {
//        //店铺数据
//        ShopVo shopVo = shopService.queryById(Long.parseLong(shopId));
//        //获取中心书库的数据
//        BookBaseInfoVo bookBaseInfoVo = bookBaseInfoService.queryByIsbn(zhishuShopGoods.getIsbn());
//        //获取实拍图
//        List<ZhishuShopImagesVo> zhishuShopImagesVoList = zhishuShopImagesService.selectShopImagesByShopId(zhishuShopGoods.getId());
//
//
//
//        Map map = new HashMap();
//        map.put("shopId",shopId);
//        map.put("goodId", zhishuShopGoods.getId());
//        map.put("userId", zhishuShopGoods.getUserId());
//        map.put("token",shopVo.getToken());
//        map.put("tpl",shopDetailVo.getBookTemplate());
//        map.put("catId","");
//        map.put("myCatId","");
//        /**
//         * 获取书名和中央书库不匹配
//         */
//        if (!zhishuShopGoods.getGoodsName().equals(bookBaseInfoVo.getBookName())){
//            map.put("otherName",zhishuShopGoods.getGoodsName());
//        }
//        /**
//         * 商品标题
//         */
//        map.put("itemName",getGoodTitle(shopDetailVo,zhishuShopGoods,bookBaseInfoVo));
//        map.put("importantDesc",shopDetailVo.getRecommend());
//        /**
//         * 价格
//         */
//        map.put("price",getPrice(shopDetailVo,zhishuShopGoods));
//        map.put("number",zhishuShopGoods.getInventory());
//        if(StringUtils.isNotEmpty(zhishuShopGoods.getConditionCode())){
//            String qualityNum = CnumberUtils.getQualityNum(zhishuShopGoods.getConditionCode());
//            if(!qualityNum.equals("UNDEFINED")){
//                map.put("quality",qualityNum);
//            }else{
//                map.put("quality",shopDetailVo.getConditionDef());
//            }
//        }else{
//            map.put("quality",shopDetailVo.getConditionDef());
//        }
//
//        map.put("qualityDesc",shopDetailVo.getConditionDes());
//        map.put("itemSn",zhishuShopGoods.getArtNo());
//        /**
//         * 获取水印图片
//         */
//        /**
//         * 封面水印  specSyImageUrl
//         */
//        String specSyImageUrl = "";
//        List<ShopImgVo> shopImgList = shopImgService.selectVoByShopId(shopId);
//        for (ShopImgVo shopImgMap : shopImgList){
//            specSyImageUrl = shopImgMap.getAbsolutePath();
//        }
//
//        //无水印图片记录
//        String noSyImage = "";
//        String images = "";
//        if(zhishuShopImagesVoList.size() == 0){
//            //没有实拍图则获取中心书库的图片
//            String image = UploadUtil.getFiles(bookBaseInfoVo.getBookName(), bookBaseInfoVo.getBookPic(),"bookInfoImages","");
//
//            //如果图片访问不到
//            Boolean bool = ImageUtils.isImageExists(image);
//            if(!bool){
//                //白底图
//                image = getWhiteImage(zhishuShopGoods);
//                noSyImage = image;
//            }else{
//                noSyImage = image;
//                //图片增加水印，若报错则返回白底图
//                if(specSyImageUrl != ""){
//                    image = getImageSy(specSyImageUrl,image,zhishuShopGoods);
//                }
//            }
//            System.out.println("中央书库上传首图-------------"+image+"；书名:"+bookBaseInfoVo.getBookName());
//            map.put("imgUrl", image);
//            //实拍图
//            images = image;
//        }else{
//            //第一张图作为首图,第一张肯定有水印
//            String imageFirst = UploadUtil.getFiles("", "","",zhishuShopImagesVoList.get(0).getPath());
//
//
//            noSyImage = imageFirst;
//            if(specSyImageUrl != ""){
//                imageFirst = getImageSy(specSyImageUrl,imageFirst,zhishuShopGoods);
//            }
//            System.out.println("用户上传首图-------------"+imageFirst+"；书名:"+zhishuShopGoods.getGoodsName());
//            map.put("imgUrl", imageFirst);
//            // WatermarkPosition 水印位置 0 全部  1第一张
//            if(shopDetailVo.getWatermarkPosition().equals("0")){
//                //为0是全部增加水印
//                for(ZhishuShopImagesVo vo : zhishuShopImagesVoList){
//                    //图片路径
//                    String image = UploadUtil.getFiles("","","",vo.getPath());
//                    //水印不为空则增加水印
//                    if(specSyImageUrl != ""){
//                        image = getImageSy(specSyImageUrl,image,zhishuShopGoods);
//                    }
//                    System.out.println("用户上传后续-------------"+image+"；书名:"+zhishuShopGoods.getGoodsName());
//                    //记录图片
//                    if(images == ""){
//                        images = image;
//                    }else{
//                        images = images + ";" + image;
//                    }
//                }
//            }else{
//                //实拍图 为1时，正常不加水印图片
//                for(ZhishuShopImagesVo vo : zhishuShopImagesVoList){
//                    String image = UploadUtil.getFiles("","","",vo.getPath());
//                    System.out.println("实拍图 为1时，正常不加水印图片：用户上传后续-------------"+image+"；书名:"+zhishuShopGoods.getGoodsName());
//                    if(images == ""){
//                        images = image;
//                    }else{
//                        images = images + ";" + image;
//                    }
//                }
//            }
//        }
//        //只有1张图片，并且只在第一张图片上加水印
//        if(images.split(";").length == 1 && shopDetailVo.getWatermarkPosition().equals("1")){
//            images = images +";"+ noSyImage;
//        }
//        int index = images.indexOf(";") + 1;
//        if(index != -1){
//            images = images.substring(index);
//        }
//
//
//        map.put("images",images);
//
//        map.put("itemDesc",bookBaseInfoVo.getContent());
//        if(shopDetailVo.getIsParcel().equals("0")){
//            //不包邮
//            map.put("bearShipping","buyer");
//        }else{
//            //包邮
//            map.put("bearShipping","seller");
//        }
//        map.put("mouldld", shopDetailVo.getTemplateId());
//        map.put("weight",shopDetailVo.getBookWeight());
//        map.put("weightPiece",shopDetailVo.getStandardNumber());
//
//        map.put("isbn",zhishuShopGoods.getIsbn());
//        map.put("author",bookBaseInfoVo.getAuthor());
//        map.put("press",bookBaseInfoVo.getPublisher());
//        map.put("pubDate",bookBaseInfoVo.getPublicationTime());
//        map.put("binding",bookBaseInfoVo.getBindingLayout());
//        map.put("oriPrice",bookBaseInfoVo.getFixPrice());
//
//        InterfaceUtils.getInterfacePost(configService.selectConfigByKey("kongfz.ip"), "/api/kfz/goodAddOne", map);
//
//    }

    /**
     * 获取商品标题
     * @return
     */
    public String getGoodTitle(ShopDetailVo shopDetailVo,ZhishuShopGoods zhishuShopGoods,BookBaseInfoVo bookBaseInfoVo){
        //获取标题组成的内容
        String titleStr = shopDetailVo.getTitleConsistOf();
        String[] titleOfArr = titleStr.split(",");
        titleStr = "";
        for(int i=0;i<titleOfArr.length;i++){
            String[] titleMark = titleOfArr[i].split(":");
            if(titleMark[1].equals("true")){
                titleStr += "," + titleMark[0];
            }
        }

        String prefix =  StringUtils.isNotEmpty(shopDetailVo.getTitlePrefix()) ? shopDetailVo.getTitlePrefix() : "";
        String suffix =  StringUtils.isNotEmpty(shopDetailVo.getTitleSuffix()) ? shopDetailVo.getTitleSuffix() : "";
        String jianGeFu = "";
        String biaoTi = prefix;
        if(shopDetailVo.getSpaceCharacter().equals("1")){
            jianGeFu = " ";
        }

        String[] titleArr = titleStr.split(",");
        for(String title : titleArr){
            switch (title){
                case "0" :biaoTi = biaoTi + jianGeFu + (StringUtils.isEmpty(zhishuShopGoods.getIsbn())  ? "" : zhishuShopGoods.getIsbn());break;
                case "1" :
                    biaoTi = biaoTi + jianGeFu + (StringUtils.isEmpty(zhishuShopGoods.getGoodsName()) ? "" : zhishuShopGoods.getGoodsName());
                    break;
                case "2" :biaoTi = biaoTi + jianGeFu + (StringUtils.isEmpty(bookBaseInfoVo.getAuthor()) ? "" : bookBaseInfoVo.getAuthor());break;
                case "3" :biaoTi = biaoTi + jianGeFu + (StringUtils.isEmpty(bookBaseInfoVo.getPublisher()) ? "" : bookBaseInfoVo.getPublisher());break;
                case "4" :biaoTi = biaoTi + jianGeFu + (StringUtils.isEmpty(bookBaseInfoVo.getPublicationTime()) ? "" : bookBaseInfoVo.getPublicationTime());break;
                case "5" :biaoTi = biaoTi + jianGeFu + (StringUtils.isEmpty(bookBaseInfoVo.getBindingLayout()) ? "" : bookBaseInfoVo.getPublicationTime());break;
                case "6" :biaoTi = biaoTi + jianGeFu + (StringUtils.isEmpty(bookBaseInfoVo.getFormat()) ? "" : bookBaseInfoVo.getFormat());break;
            }
        }
        //后缀
        biaoTi = biaoTi + jianGeFu + suffix;
        // 裁剪字符串，保留200个字符
        biaoTi = StringUtils.truncateString(biaoTi, 199);
        return biaoTi;
    }

    /**
     * 获取价格
     */
    public String getPrice(ShopDetailVo shopDetailVo,ZhishuShopGoods zhishuShopGoods){
        //校验价格区间，低于最小价格则改为最低价
        BigDecimal priceL = null;
        BigDecimal priceOld = new BigDecimal(zhishuShopGoods.getPrice().toString()).divide(new BigDecimal(100));
        BigDecimal highPrice = new BigDecimal(String.valueOf(shopDetailVo.getHighPrice())).divide(new BigDecimal(100));
        BigDecimal lowPrice = new BigDecimal(String.valueOf(shopDetailVo.getLowerPrice())).divide(new BigDecimal(100));

        if(priceOld.compareTo(lowPrice) < 0){
            //小于最低价
            priceL = lowPrice;
        }else if(priceOld.compareTo(highPrice) > 0){
            //大于最高价
            priceL = highPrice;
        }else{
            priceL = priceOld;
        }

        //获取价格模板
        PriceTemplateVo priceTemplateVo = priceTemplateService.queryById(shopDetailVo.getSaleTemplateId());

        //根据价格模板换算后的价格
        BigDecimal price = new BigDecimal(String.valueOf(priceTemplateVo.getProportion()))
                .divide(new BigDecimal(100))
                .multiply(priceL)
                .add(priceL)
                .add(new BigDecimal(priceTemplateVo.getAddAmount().toString()))
                .multiply(new BigDecimal(100))
                .setScale(0, RoundingMode.DOWN);

        return price.toString();
    }

    /**
     * 获取白底图
     */
    public String getWhiteImage(ZhishuShopGoods zhishuShopGoods){
        String uuid = UUID.randomUUID().toString();
        String fileUrl = ImageUtils.generateImage(zhishuShopGoods.getGoodsName(), 800, 800,uuid+".jpg");
        MultipartFile multipartFile = UploadUtil.getMultipartFileFromPath(fileUrl);
        //上传文件
        UploadUtil.upload(multipartFile,"userShopGoodsImages");
        //获取上传文件网络地址
        return UploadUtil.getFiles("","","","other/"+ LoginHelper.getUserId()+"/userShopGoodsImages/"+uuid+".jpg");
    }

    /**
     * 处理水印图片
     * specSyImageUrl 水印图片
     */
    public String getImageSy(String specSyImageUrl,String iamge,ZhishuShopGoods zhishuShopGoods){

        try {
            String uuid = UUID.randomUUID().toString();
            //本地缓存路径
            String filePath = UploadUtil.mergeImages(iamge,specSyImageUrl);
            MultipartFile multipartFile = UploadUtil.getMultipartFileFromPath(filePath);
            //上传图片空间
            UploadUtil.upload(multipartFile,"userShopGoodsImages");
            //获取图片空间路径
            return UploadUtil.getFiles("","","","other/"+ LoginHelper.getUserId()+"/userShopGoodsImages/"+multipartFile.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
            return getWhiteImage(zhishuShopGoods);
        }
    }

    /**
     * 调用kongfz服务接口修改商品库存
     * @param map
     */
    public void goodUpdateStock(String token,String itemId,String number){
        Map map = new HashMap();
        map.put("token",token);
        map.put("itemId",itemId);
        map.put("number",number);
        InterfaceUtils.getInterfacePost(configService.selectConfigByKey("kongfz.ip"), "/api/kfz/itemNumberUpdate", map);
    }
}
