package com.bawei.mall.product.service.impl;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.exception.ServiceException;
import com.bawei.common.core.utils.DateUtils;
import com.bawei.common.core.utils.bean.BeanUtils;
import com.bawei.common.rabbit.domain.Message;
import com.bawei.common.rabbit.enums.QueueEnum;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.es.remote.EsDocRemoteService;
import com.bawei.es.remote.EsIndexRemoteService;
import com.bawei.mall.product.cache.ProductInfoCache;
import com.bawei.mall.product.domain.MallProductRuleInfo;
import com.bawei.mall.product.domain.MallProductSkuInfo;
import com.bawei.mall.product.domain.model.ProductModel;
import com.bawei.mall.product.domain.model.SkuModel;
import com.bawei.mall.product.domain.reponse.ProductDetailsResponse;
import com.bawei.mall.product.domain.reponse.ProductInfoResponse;
import com.bawei.mall.product.domain.request.ProductInfoRequest;
import com.bawei.mall.product.service.IMallProductRuleInfoService;
import com.bawei.mall.product.service.IMallProductSkuInfoService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Builder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bawei.mall.product.mapper.MallProductInfoMapper;
import com.bawei.mall.product.domain.MallProductInfo;
import com.bawei.mall.product.service.IMallProductInfoService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品信息Service业务层处理
 *
 * @author DongZeLiang
 * @date 2022-09-19
 */
@Service
@Builder
public class MallProductInfoServiceImpl implements IMallProductInfoService
{
    @Autowired
    private MallProductInfoMapper mallProductInfoMapper;

    @Autowired
    private IMallProductSkuInfoService skuInfoService;

    @Autowired
    private IMallProductRuleInfoService ruleInfoService;


    @Autowired
    private ProductInfoCache productInfoCache;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private EsDocRemoteService  esDocRemoteService;

    @Autowired
    private EsIndexRemoteService esIndexRemoteService;

    /**
     * 查询商品信息
     *
     * @param id 商品信息主键
     * @return 商品信息
     */
    @Override
    public ProductInfoResponse selectMallProductInfoById(Long id)
    {
        MallProductInfo mallProductInfo = mallProductInfoMapper.selectMallProductInfoById(id);
        ProductInfoResponse productInfoResponse = new ProductInfoResponse();
        BeanUtils.copyBeanProp(productInfoResponse, mallProductInfo);
        productInfoResponse.setSkuInfoList(
                skuInfoService.selectMallProductSkuInfoList(new MallProductSkuInfo(){{
                    setProductId(id);
                }})
        );
        return productInfoResponse;
    }

    @Override
    public ProductDetailsResponse selectProductDetailsById (Long productId) {
        if (productId == null || productId == 0){
            throw new ServiceException("查询商品信息，依据不合法！");
        }
        ProductDetailsResponse productDetailsResponse = new ProductDetailsResponse();
        ProductModel productModel = mallProductInfoMapper.selectProductModelById(productId);
        if (productModel == null){
            throw new ServiceException("查询商品信息，商品数据为空");
        }
        productDetailsResponse.setProduct(productModel);
        List<MallProductSkuInfo> mallProductSkuInfos = skuInfoService.selectMallProductSkuInfoList(productId);
        if (mallProductSkuInfos == null || mallProductSkuInfos.size() == 0){
            throw new ServiceException("查询商品信息，SKU数据为空");
        }
        productDetailsResponse.setSkuList(mallProductSkuInfos);
        MallProductRuleInfo ruleInfo = ruleInfoService.selectMallProductRuleInfoById(productModel.getRuleId());
        if (ruleInfo == null){
            throw new ServiceException("查询商品信息，规格数据为空");
        }
        productDetailsResponse.setProductRule(ruleInfo);
        return productDetailsResponse;
    }

    /**
     * 查询商品信息列表
     *
     * @param mallProductInfo 商品信息
     * @return 商品信息
     */
    @Override
    public List<MallProductInfo> selectMallProductInfoList(MallProductInfo mallProductInfo)
    {
        return mallProductInfoMapper.selectMallProductInfoList(mallProductInfo);
    }

    /**
     * 新增商品信息
     *
     * @param productInfoRequest 商品信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertMallProductInfo(ProductInfoRequest productInfoRequest)
    {
        productInfoRequest.setCreateBy(java.lang.String.valueOf(SecurityUtils.getUserId()));
        productInfoRequest.setCreateTime(DateUtils.getNowDate());
        int i = mallProductInfoMapper.insertMallProductInfo(productInfoRequest);
        if (i == 0){
            return i;
        }

        skuInfoService.batchInsertProductSku(
                SkuModel.builderSkuModel(productInfoRequest.getId(), productInfoRequest.getSkuInfoList())
        );

        // 给搜索系统发送消息需要进行搜索更新
        rabbitTemplate.convertAndSend(QueueEnum.PRODUCT_ADD.queueName(),
                Message.builderMsg(productInfoRequest.getId()));

        return i;
    }

    /**
     * 修改商品信息
     *
     * @param productInfoRequest 商品信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateMallProductInfo(ProductInfoRequest productInfoRequest)
    {
        productInfoRequest.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
        productInfoRequest.setUpdateTime(DateUtils.getNowDate());
        int i = mallProductInfoMapper.updateMallProductInfo(productInfoRequest);
        if (i == 0){
            return i;
        }
        skuInfoService.deleteMallProductSkuInfoByProductId(productInfoRequest.getId());
        skuInfoService.batchInsertProductSku(
                SkuModel.builderSkuModel(productInfoRequest.getId(), productInfoRequest.getSkuInfoList())
        );
        return i;
    }

    /**
     * 批量删除商品信息
     *
     * @param ids 需要删除的商品信息主键
     * @return 结果
     */
    @Override
    public int deleteMallProductInfoByIds(Long[] ids)
    {
        skuInfoService.deleteMallProductSkuInfoByProductIds(ids);
        for (Long id : ids) {
            // 延迟执行
            productInfoCache.delayRemove(id);
        }
        return mallProductInfoMapper.deleteMallProductInfoByIds(ids);
    }

    /**
     * 删除商品信息信息
     *
     * @param id 商品信息主键
     * @return 结果
     */
    @Override
    public int deleteMallProductInfoById(Long id)
    {
        return mallProductInfoMapper.deleteMallProductInfoById(id);
    }

    /**
     * 商品总条数
     * @param mallProductInfo 商品查询
     * @return
     */
    @Override
    public Long selectMallProductInfoCount (MallProductInfo mallProductInfo) {
        return mallProductInfoMapper.selectMallProductInfoCount(mallProductInfo);
    }


    @Override
    public void queryJson() {
        Path pathJson = Paths.get(".");
        try {
            List<Path> collect = Files.walk(pathJson)
                    .filter(Files::isRegularFile)
                    .filter(path -> path.toString().endsWith(".json"))
                    .collect(Collectors.toList());
            //根据文件路径查找文件
            collect.forEach(path -> {
                try {
                    String json = new String(Files.readAllBytes(path));
                    JSONObject jsonObject = JSONObject.parseObject(json);
                    Object javaObject = JSONObject.toJavaObject(jsonObject, Object.class);
                    System.out.println(javaObject);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public void unmout(Long id, java.lang.String status) {
        if(id==null && id==0){
            throw new RuntimeException("id不能为空");
        }
        if (status==null || status.equals("")){
            throw new RuntimeException("商品状态不能为空");
        }
            MallProductInfo mallProductInfo =  mallProductInfoMapper.selectMallProductInfoById(id);
        if (mallProductInfo==null){
            throw new RuntimeException("商品不存在");
        }
        //判断修改的状态和数据库里的状态是否冲突
        if (mallProductInfo.getStatus().equals("0") && status.equals("0")){
            throw new RuntimeException("商品已上架");
        }else if (mallProductInfo.getStatus().equals("1") && status.equals("1")){
            throw new RuntimeException("商品已下架");
        }
        R shop = esIndexRemoteService.findIndex("shop");
        if (shop.isSuccess()){
            R r = esIndexRemoteService.deleteIndex("shop");
            if (r.isSuccess()){
                //删除该索引后,进行修改数据
                mallProductInfo.setStatus(status);
                mallProductInfoMapper.updateMallProductInfo(mallProductInfo);

            }else {
                throw new RuntimeException("删除索引失败");
            }
        }

    }

    @Override
    public R esList() {
        //添加es列表查询
        if (esIndexRemoteService.findIndex("shop").isSuccess()){
            //查询es列表
            R shop = esDocRemoteService.queryList("shop", null);
            return R.ok(shop.getData());
        }
        return null;
    }

}
