package com.slodon.b2b2c.model.goods;

import cn.hutool.json.JSONObject;
import com.slodon.b2b2c.config.ProductConfig;
import com.slodon.b2b2c.core.constant.GoodsConst;
import com.slodon.b2b2c.core.exception.MallException;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.core.util.AssertUtil;
import com.slodon.b2b2c.core.util.FileUrlUtil;
import com.slodon.b2b2c.core.util.HttpClientUtil;
import com.slodon.b2b2c.core.util.StringUtil;
import com.slodon.b2b2c.dao.read.goods.ProductReadMapper;
import com.slodon.b2b2c.dao.write.goods.ProductWriteMapper;
import com.slodon.b2b2c.enums.WebSiteConstant;
import com.slodon.b2b2c.goods.example.GoodsPictureExample;
import com.slodon.b2b2c.goods.example.ProductExample;
import com.slodon.b2b2c.goods.pojo.Goods;
import com.slodon.b2b2c.goods.pojo.GoodsPicture;
import com.slodon.b2b2c.goods.pojo.Product;
import com.slodon.b2b2c.investment.constant.InvestmentConst;
import com.slodon.b2b2c.model.seller.StoreModel;
import com.slodon.b2b2c.model.seller.VendorModel;
import com.slodon.b2b2c.seller.pojo.Vendor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Component
@Slf4j
public class ProductModel {

    @Resource
    private ProductReadMapper productReadMapper;
    @Resource
    private ProductWriteMapper productWriteMapper;

    @Resource
    private VendorModel vendorModel;

    @Resource
    private StoreModel storeModel;

    @Resource
    private GoodsPictureModel goodsPictureModel;

    @Resource
    private ProductConfig productConfig;


    /**
     * 新增商品表（SKU），指定特定规格
     *
     * @param product
     * @return
     */
    public Integer saveProduct(Product product) {
        int count = productWriteMapper.insert(product);
        if (count == 0) {
            throw new MallException("添加商品表（SKU），指定特定规格失败，请重试");
        }
        return count;
    }

    /**
     * 查询符合条件的记录数
     *
     * @param example
     * @return
     */
    public Integer countByExample(ProductExample example) {
        return productReadMapper.countByExample(example);
    }

    /**
     * 根据productId删除商品表（SKU），指定特定规格
     *
     * @param productId productId
     * @return
     */
    public Integer deleteProduct(Long productId) {
        if (StringUtils.isEmpty(productId)) {
            throw new MallException("请选择要删除的数据");
        }
        int count = productWriteMapper.deleteByPrimaryKey(productId);
        if (count == 0) {
            log.error("根据productId：" + productId + "删除商品表（SKU），指定特定规格失败");
            throw new MallException("删除商品表（SKU），指定特定规格失败,请重试");
        }
        return count;
    }

    /**
     * 根据productId更新商品表（SKU），指定特定规格
     *
     * @param product
     * @return
     */
    public Integer updateProduct(Product product) {
        if (StringUtils.isEmpty(product.getProductId())) {
            throw new MallException("请选择要修改的数据");
        }
        int count = productWriteMapper.updateByPrimaryKeySelective(product);
        if (count == 0) {
            log.error("根据productId：" + product.getProductId() + "更新商品表（SKU），指定特定规格失败");
            throw new MallException("更新商品表（SKU），指定特定规格失败,请重试");
        }
        return count;
    }

    /**
     * 根据条件更新商品表（SKU）
     *
     * @param product
     * @param example
     * @return
     */
    public Integer updateProductByExample(Product product, ProductExample example) {
        return productWriteMapper.updateByExampleSelective(product, example);
    }

    /**
     * 根据productId获取商品表（SKU），指定特定规格详情
     *
     * @param productId productId
     * @return
     */
    public Product getProductByProductId(Long productId) {
        return productReadMapper.getByPrimaryKey(productId);
    }

    /**
     * 根据条件获取商品表（SKU），指定特定规格列表
     *
     * @param example 查询条件信息
     * @param pager   分页信息
     * @return
     */
    public List<Product> getProductList(ProductExample example, PagerInfo pager) {
        List<Product> productList;
        if (pager != null) {
            pager.setRowsCount(productReadMapper.countByExample(example));
            productList = productReadMapper.listPageByExample(example, pager.getStart(), pager.getPageSize());
        } else {
            productList = productReadMapper.listByExample(example);
        }
        return productList;
    }

    /**
     * 系统定时检查库存
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public List<Product> jobSystemCheckProductStock() {
        List<Product> productList = new ArrayList<>();
        //获取所有还未通知过的货品
        ProductExample example = new ProductExample();
        example.setStateNotIn(GoodsConst.PRODUCT_STATE_0 + "," + GoodsConst.PRODUCT_STATE_2);
        example.setProductStockWarningState(GoodsConst.PRODUCT_STOCK_WARNING_STATE_1);
        List<Product> list = productReadMapper.listByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            return productList;
        }
        //拼接货品id
        StringBuilder productIds = new StringBuilder();
        for (Product product : list) {
            if (null == product.getProductStock() || null == product.getProductStockWarning()) {
                continue;
            }
            if (product.getProductStock() <= product.getProductStockWarning()) {
                productIds.append(",").append(product.getProductId());

                productList.add(product);
            }
        }
        //更新通知状态
        if (!StringUtil.isEmpty(productIds.toString())) {
            ProductExample productExample = new ProductExample();
            productExample.setProductIdIn(productIds.toString().substring(1));
            Product updateProduct = new Product();
            updateProduct.setProductStockWarningState(GoodsConst.PRODUCT_STOCK_WARNING_STATE_2);
            int count = productWriteMapper.updateByExampleSelective(updateProduct, productExample);
            AssertUtil.isTrue(count == 0, "更新货品信息失败，请确认");
        }
        return productList;
    }


    @Transactional(rollbackFor = Exception.class)
    public void upsertProduct(Goods goods, Vendor vendor) {
        if (!WebSiteConstant.MEMBER_OVERSEA.equals(goods.getWebSite())) {
            return;
        }
        //查询商户获取token
        vendor = vendorModel.getVendorByVendorId(vendor.getVendorId());

        //查询货品
        ProductExample productExample = new ProductExample();
        productExample.setGoodsId(goods.getGoodsId());
        List<Product> products = productReadMapper.listByExample(productExample);
        AssertUtil.isTrue(CollectionUtils.isEmpty(products), "商品不存在");

        //查询货品图片
        GoodsPictureExample goodsPictureExample = new GoodsPictureExample();
        goodsPictureExample.setGoodsId(goods.getGoodsId());
        goodsPictureExample.setOrderBy("picture_id asc");
        List<GoodsPicture> goodsPictureList = goodsPictureModel.getGoodsPictureList(goodsPictureExample, null);

        String regex = ".*token=([^&]*).*";
        HashMap<String, String> headers = new HashMap<>();
        headers.put(InvestmentConst.CONTENT_TYPE, InvestmentConst.APPLICATION_JSON);
        if (!StringUtil.isBlank(vendor.getStoreUrlBy9710())) {
            headers.put(InvestmentConst.AUTHORIZATION, "Token " + vendor.getStoreUrlBy9710().replaceFirst(regex, "$1"));
        } else {
            JSONObject jsonObject = storeModel.getStoreUrlsObject(vendor.getStoreId(), vendor.getVendorName());
            headers.put(InvestmentConst.AUTHORIZATION, "Token " + jsonObject.getStr("9710").replaceFirst(regex, "$1"));
        }

        JSONObject param = new JSONObject();

        //目前只有单规格
        param.set("productId", products.get(0).getProductId().toString());
        param.set("authName", vendor.getVendorName()+"_"+vendor.getStoreId());
        param.set("name", goods.getGoodsName());
        param.set("cn_name", goods.getGoodsNameCn());
        param.set("sku", goods.getGoodsId().toString());
        param.set("active", GoodsConst.GOODS_STATE_UPPER == goods.getState());
        List<String> image_urls = new ArrayList<>();
        if (!CollectionUtils.isEmpty(goodsPictureList)) {
            goodsPictureList.forEach(goodsPicture -> {
                image_urls.add(FileUrlUtil.getFileUrl(goodsPicture.getImagePath(), null));
            });
        }
        param.set("image_urls", image_urls);
        try {
            log.error("调用第三方接口创建/更新商品 -请求接口: {}, 请求参数: {},请求头: {}", productConfig.getUrl(), param.toString(), com.alibaba.fastjson.JSONObject.toJSONString(headers));
            HttpClientUtil.httpPost201(productConfig.getUrl(), param.toString(), headers);
        } catch (Exception e) {
            log.error("调用第三方接口创建/更新商品失败 -请求接口: {}, 请求参数: {},请求头: {}, 错误信息: {}", productConfig.getUrl(), param.toString(), com.alibaba.fastjson.JSONObject.toJSONString(headers), e.getMessage(), e);
            throw new MallException("创建/更新商品失败，请重试");
        }
    }
}