package com.gree.mall.manager.logic.goods;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.goods.GoodsLibraryBean;
import com.gree.mall.manager.bean.goods.GoodsMaterialVO;
import com.gree.mall.manager.bean.goods.outside.GoodsBean;
import com.gree.mall.manager.bean.goods.outside.GoodsSpec;
import com.gree.mall.manager.bean.listvo.goods.GoodsLibraryVO;
import com.gree.mall.manager.commonmapper.CommonMapper;
import com.gree.mall.manager.enums.StatusEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.helper.ResponseHelper;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.CommonFile;
import com.gree.mall.manager.plus.entity.GoodsLibrary;
import com.gree.mall.manager.plus.entity.GoodsLibrarySpec;
import com.gree.mall.manager.plus.service.GoodsLibraryService;
import com.gree.mall.manager.plus.service.GoodsLibrarySpecService;
import com.gree.mall.manager.utils.HttpUtils;
import com.gree.mall.manager.utils.StringUtil;
import com.gree.mall.manager.utils.oss.OSSUtil;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 商品库
 * @author ：lijh
 * @description：TODO
 * @date ：2024/4/30 14:06
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GoodsLibraryLogic {

    @Value("${gjmall.goods.url}")
    private String gjmallGoodsUrl;

    private final CommonLogic commonLogic;
    private final OSSUtil ossUtil;
    
    private final GoodsLibraryService goodsLibraryService;
    private final GoodsLibrarySpecService goodsLibrarySpecService;
    private final CommonMapper commonMapper;


    /**
     * 商品库列表
     * @param zfireParamBean
     * @return
     */
    public IPage<GoodsLibraryVO> list(ZfireParamBean zfireParamBean){
        FieldUtils.supplyParam(zfireParamBean, GoodsLibraryVO.class);
        IPage<GoodsLibraryVO> page = commonMapper.goodsLibraryList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
        return page;
    }


    /**
     * 保存商品
     * @param goodsLibraryBean
     */
    @Transactional
    public void save(GoodsLibraryBean goodsLibraryBean){
        goodsLibraryBean.insertOrUpdate();

        List<GoodsLibrarySpec> goodsLibrarySpecList = goodsLibraryBean.getGoodsLibrarySpecList();
        goodsLibrarySpecList.forEach(v -> v.setGoodsLibraryId(goodsLibraryBean.getGoodsLibraryId())
                .setGoodsName(goodsLibraryBean.getGoodsName())
                .setBrandName(goodsLibraryBean.getBrandName())
                .setCategory1(goodsLibraryBean.getCategory1())
                .setCategory2(goodsLibraryBean.getCategory2())
                .setDescribeText(goodsLibraryBean.getDescribeText())
                .setVedio(goodsLibraryBean.getVedio())
                .setContent(goodsLibraryBean.getContent())
                .setStatus(goodsLibraryBean.getStatus())
        );
        goodsLibrarySpecService.lambdaUpdate().eq(GoodsLibrarySpec::getGoodsLibraryId,goodsLibraryBean.getGoodsLibraryId()).remove();
        goodsLibrarySpecService.saveOrUpdateBatch(goodsLibrarySpecList);
    }


    /**
     * 详情
     */
    public GoodsLibraryBean detail(String goodsLibraryId){
        GoodsLibrary goodsLibrary = goodsLibraryService.getById(goodsLibraryId);
        GoodsLibraryBean goodsLibraryBean = BeanUtil.copyProperties(goodsLibrary, GoodsLibraryBean.class);
        //规格
        List<GoodsLibrarySpec> list = goodsLibrarySpecService.lambdaQuery().eq(GoodsLibrarySpec::getGoodsLibraryId, goodsLibraryBean.getGoodsLibraryId()).list();
        goodsLibraryBean.setGoodsLibrarySpecList(list);
        return goodsLibraryBean;
    }

    /**
     * 删除
     * @param goodsLibraryId
     */
    public void delete(String goodsLibraryId){
        goodsLibraryService.lambdaUpdate().eq(GoodsLibrary::getGoodsLibraryId,goodsLibraryId).remove();
        goodsLibrarySpecService.lambdaUpdate().eq(GoodsLibrarySpec::getGoodsLibraryId,goodsLibraryId).remove();
    }


    /**
     * 批量开启，批量关闭
     * @param goodsLibraryIds
     * @param statusEnum
     */
    public void batchStatus(List<String> goodsLibraryIds, Boolean statusEnum){
        goodsLibraryService.lambdaUpdate().set(GoodsLibrary::getStatus,statusEnum).in(GoodsLibrary::getGoodsLibraryId,goodsLibraryIds).update();
    }


    /**
     * 同步商品
     */
    @Transactional
    public void sync() throws MalformedURLException {
        Map<String,String> param = new HashMap<>();
        //查询修改时间在这个之后的时间
        param.put("time",null);
        param.put("sign","asfo&ndEdl1dfx(dk123xxckk@fx1kas#xdfA21");
        log.info("同步商品开始："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        String s = HttpUtils.requestPostForm(gjmallGoodsUrl, param, null);
        ResponseHelper<List<GoodsBean>> result = JSONUtil.toBean(s, new TypeReference<ResponseHelper<List<GoodsBean>>>() {
        }, false);
        List<GoodsBean> goodsBeans = checkData(result);
        log.info("同步商品response：{}",JSONObject.toJSONString(goodsBeans));
        if(CollectionUtils.isEmpty(goodsBeans)){
            return;
        }
        //当前所有商品库的旧商品
        List<GoodsLibrary> list = goodsLibraryService.lambdaQuery().select(GoodsLibrary::getGoodsLibraryId,GoodsLibrary::getUpdateTime).list();
        Map<String, Date> oldMap = list.stream().collect(Collectors.toMap(v -> v.getGoodsLibraryId(), v -> v.getUpdateTime()));

        List<GoodsLibrary> goodsLibraryList = new ArrayList<>();
        List<GoodsLibrarySpec> goodsLibrarySpecList = new ArrayList<>();
        for(GoodsBean goodsBean : goodsBeans){
            Date date = oldMap.get(goodsBean.getGoodsId());
            //旧商品的修改时间大于新同步的商品的时间则不需要同步
            if(date != null && goodsBean.getUpdateTime() != null && date.getTime() > goodsBean.getUpdateTime().getTime()){
                continue;
            }
            //主图
            String filePath = "";

            if(StringUtils.isNotBlank(goodsBean.getImgUrl())) {
                InputStream inputStream = commonLogic.getFileInputStreamByUrl(goodsBean.getImgUrl());
                String suffix = goodsBean.getImgUrl().substring(goodsBean.getImgUrl().lastIndexOf("."));
                filePath = ossUtil.uploadFile(inputStream, suffix);
            }
            //轮播图
            String imgs = "";
            List<CommonFile> images = goodsBean.getImages();
            if(!CollectionUtils.isEmpty(images)){
                for(CommonFile commonFile : images){
                    String url = commonFile.getUrl();
                    InputStream inputStream = commonLogic.getFileInputStreamByUrl(url);
                    String suffix = goodsBean.getImgUrl().substring(url.lastIndexOf("."));
                    imgs += ossUtil.uploadFile(inputStream, suffix)+",";
                }
            }
            if(StringUtils.isNotBlank(imgs)){
                imgs = imgs.substring(0,imgs.length() - 1);
            }
            GoodsLibrary goodsLibrary = new GoodsLibrary();
            goodsLibrary.setGoodsLibraryId(goodsBean.getGoodsId());
            goodsLibrary.setGoodsName(goodsBean.getGoodsName());
            goodsLibrary.setBrandName("格力");
            goodsLibrary.setCategory1(goodsBean.getCategory1());
            goodsLibrary.setCategory2(goodsBean.getCategory2());
            goodsLibrary.setDescribeText(goodsBean.getDescribeText());
            goodsLibrary.setImgUrl(filePath);
            goodsLibrary.setVedio(goodsBean.getVedio());
            goodsLibrary.setContent(converContent(goodsBean.getContent()));
            goodsLibrary.setSortNum(goodsBean.getSortNum());
            goodsLibrary.setStatus(goodsBean.getStatus());
            goodsLibrary.setIsVr(goodsBean.getIsVr());
            goodsLibrary.setImgs(imgs);
            goodsLibrary.setIsOutside(true);
            goodsLibraryList.add(goodsLibrary);

            //规格
            for(GoodsSpec goodsSpec : goodsBean.getGoodsSpecs()) {
                GoodsLibrarySpec goodsLibrarySpec = new GoodsLibrarySpec();
                BeanUtil.copyProperties(goodsLibrary,goodsLibrarySpec);
                goodsLibrarySpec.setId(goodsSpec.getGoodsSpecId());
                goodsLibrarySpec.setMainName(goodsBean.getMainName());
                goodsLibrarySpec.setSmallName(goodsBean.getSmallName());
                goodsLibrarySpec.setSpecValue(goodsSpec.getSpecValue());
                goodsLibrarySpec.setOrgPrice(goodsSpec.getOrgPrice());
                goodsLibrarySpec.setCostPrice(goodsSpec.getCostPrice());
                goodsLibrarySpec.setPrice(goodsSpec.getPrice());
                goodsLibrarySpec.setShareAmount(goodsSpec.getShareAmount());
                goodsLibrarySpec.setInnerShareAmount(goodsSpec.getInnerShareAmount());
                if(goodsSpec.getSharePercent() != null) {
                    goodsLibrarySpec.setSharePercent(BigDecimal.valueOf(goodsSpec.getSharePercent()));
                }
                if(goodsSpec.getInnerSharePercent() != null) {
                    goodsLibrarySpec.setInnerSharePercent(BigDecimal.valueOf(goodsSpec.getInnerSharePercent()));
                }
                goodsLibrarySpecList.add(goodsLibrarySpec);
            }
        }
        if(CollectionUtils.isEmpty(goodsLibraryList)){
            return;
        }
        goodsLibraryService.saveOrUpdateBatch(goodsLibraryList);
        goodsLibrarySpecService.saveOrUpdateBatch(goodsLibrarySpecList);
    }

//    public static void main(String[] args){
//        String htmlText = "<img src=\"https://gj.oss.com/sdfsd.png\">asdfasdfsdf<img src=\"https://gj.oss.com/sdfsd.png\">23dvfa";
//        converContent(htmlText);
//    }


    /**
     * 富文本框里找到img src的图片，并上传至新oss
     * @param content
     * @return
     */
    public  String converContent(String content){
        Pattern pattern = Pattern.compile("<img\\s+src=\"(.*?)\"");
        Matcher matcher = pattern.matcher(content);
        while(matcher.find()){
            String imgUrl = matcher.group().replace("<img src=","").replaceAll("\"","");
            InputStream inputStream = commonLogic.getFileInputStreamByUrl(imgUrl);
            String suffix = imgUrl.substring(imgUrl.lastIndexOf("."));
            String filePath = ossUtil.uploadFile(inputStream, suffix);
            log.info("商品库商品详情富文本图片，替换前{},替换后{}",imgUrl,filePath);
            content = content.replaceAll(imgUrl,filePath);
        }
        return content;
    }



    public <T> T checkData(ResponseHelper<T> result){
        if(result.getCode() != ResponseHelper.ResponseCode_Success){
            String errMsg = result.getMessage().replace("温馨提示：", "");
            throw new RemoteServiceException(result.getCode(),errMsg);
        }
        return result.getData();
    }

}
