package org.dromara.zhishu.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import org.dromara.zhishu.domain.ShopWarehouseAuto;
import org.dromara.zhishu.service.IShopWarehouseAutoService;
import org.dromara.zhishu.util.HttpUtils;
import org.dromara.zhishu.util.JsonObjUtil;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.oss.core.OssClient;
import org.dromara.common.oss.entity.UploadResult;
import org.dromara.common.oss.factory.OssFactory;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.zhishu.domain.bo.ShopContextBo;
import org.dromara.zhishu.domain.bo.ShopWarehouseBo;
import org.dromara.zhishu.domain.vo.ShopContextVo;
import org.dromara.zhishu.domain.vo.ShopWarehouseVo;
import org.dromara.zhishu.mapper.ShopContextMapper;
import org.dromara.zhishu.mapper.ShopMapper;
import org.dromara.zhishu.service.IShopContextService;
import org.dromara.zhishu.service.IShopWarehouseService;
import org.springframework.stereotype.Service;
import org.dromara.zhishu.domain.bo.ShopDetailBo;
import org.dromara.zhishu.domain.vo.ShopDetailVo;
import org.dromara.zhishu.domain.ShopDetail;
import org.dromara.zhishu.mapper.ShopDetailMapper;
import org.dromara.zhishu.service.IShopDetailService;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.Collection;
import java.util.stream.Collectors;
import java.util.HashMap;

/**
 * 商品详情Service业务层处理
 *
 * @author yxy
 * @date 2025-03-13
 */
@RequiredArgsConstructor
@Service
public class ShopDetailServiceImpl implements IShopDetailService {

    private final ShopDetailMapper baseMapper;

    private final IShopContextService shopContextService;

    private final IShopWarehouseService shopWarehouseService;

    private final IShopWarehouseAutoService shopWarehouseAutoService;

    /**
     * 查询商品详情
     *
     * @param id 主键
     * @return 商品详情
     */
    @Override
    public ShopDetailVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    @Override
    public ShopDetailVo queryByShopId(Long shopId) {
        ShopDetailVo shopDetailVo = baseMapper.selectVoByShopId(shopId);

        shopDetailVo.setWarehouseList(
                shopWarehouseService.queryListByShopId(shopId)
                        .stream()
                        .map(ShopWarehouseVo::getUserId)
                        .collect(Collectors.toList())
        );
        shopDetailVo.setMappingList(
                shopWarehouseAutoService.queryListByShopId(shopId)
                        .stream()
                        .map(item -> item.getUserId()+"-"+item.getWarehouseId())
                        .collect(Collectors.toList())
        );

        ShopContextVo shopContextVo = shopContextService.selectByShopId(shopId);
        if(shopContextVo != null){
            shopDetailVo.setContext(shopContextVo.getContext());
        }
        return shopDetailVo;
    }

    /**
     * 分页查询商品详情列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 商品详情分页列表
     */
    @Override
    public TableDataInfo<ShopDetailVo> queryPageList(ShopDetailBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ShopDetail> lqw = buildQueryWrapper(bo);
        Page<ShopDetailVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的商品详情列表
     *
     * @param bo 查询条件
     * @return 商品详情列表
     */
    @Override
    public List<ShopDetailVo> queryList(ShopDetailBo bo) {
        LambdaQueryWrapper<ShopDetail> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ShopDetail> buildQueryWrapper(ShopDetailBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ShopDetail> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(ShopDetail::getId);
        lqw.eq(bo.getShopId() != null, ShopDetail::getShopId, bo.getShopId());
        lqw.eq(bo.getTemplateId() != null, ShopDetail::getTemplateId, bo.getTemplateId());
        lqw.eq(bo.getHighPrice() != null, ShopDetail::getHighPrice, bo.getHighPrice());
        lqw.eq(bo.getLowPrice() != null, ShopDetail::getLowPrice, bo.getLowPrice());
        lqw.eq(bo.getSaleTemplateId() != null, ShopDetail::getSaleTemplateId, bo.getSaleTemplateId());
        lqw.eq(StringUtils.isNotBlank(bo.getSevenDays()), ShopDetail::getSevenDays, bo.getSevenDays());
        lqw.eq(StringUtils.isNotBlank(bo.getIsSecondHand()), ShopDetail::getIsSecondHand, bo.getIsSecondHand());
        lqw.eq(StringUtils.isNotBlank(bo.getCarouselNum()), ShopDetail::getCarouselNum, bo.getCarouselNum());
        lqw.eq(StringUtils.isNotBlank(bo.getIsDetailsImg()), ShopDetail::getIsDetailsImg, bo.getIsDetailsImg());
        lqw.eq(StringUtils.isNotBlank(bo.getIsCatalogueDetails()), ShopDetail::getIsCatalogueDetails, bo.getIsCatalogueDetails());
        lqw.eq(StringUtils.isNotBlank(bo.getIsInformationImg()), ShopDetail::getIsInformationImg, bo.getIsInformationImg());
        lqw.eq(StringUtils.isNotBlank(bo.getTitlePrefix()), ShopDetail::getTitlePrefix, bo.getTitlePrefix());
        lqw.eq(StringUtils.isNotBlank(bo.getTitleSuffix()), ShopDetail::getTitleSuffix, bo.getTitleSuffix());
        lqw.eq(StringUtils.isNotBlank(bo.getTitleFilter()), ShopDetail::getTitleFilter, bo.getTitleFilter());
        lqw.eq(StringUtils.isNotBlank(bo.getItemNumberPrefix()), ShopDetail::getItemNumberPrefix, bo.getItemNumberPrefix());
        lqw.eq(StringUtils.isNotBlank(bo.getTitleConsistOf()), ShopDetail::getTitleConsistOf, bo.getTitleConsistOf());
        lqw.eq(StringUtils.isNotBlank(bo.getSpaceCharacter()), ShopDetail::getSpaceCharacter, bo.getSpaceCharacter());
        lqw.eq(StringUtils.isNotBlank(bo.getAutoTruncation()), ShopDetail::getAutoTruncation, bo.getAutoTruncation());
        lqw.eq(StringUtils.isNotBlank(bo.getMySetUp()), ShopDetail::getMySetUp, bo.getMySetUp());
        lqw.eq(StringUtils.isNotBlank(bo.getSystemSetUp()), ShopDetail::getSystemSetUp, bo.getSystemSetUp());
        lqw.eq(StringUtils.isNotBlank(bo.getFilterSuit()), ShopDetail::getFilterSuit, bo.getFilterSuit());
        lqw.eq(StringUtils.isNotBlank(bo.getIsDelProtect()), ShopDetail::getIsDelProtect, bo.getIsDelProtect());
        lqw.eq(StringUtils.isNotBlank(bo.getIsRemoveProtect()), ShopDetail::getIsRemoveProtect, bo.getIsRemoveProtect());
        lqw.eq(StringUtils.isNotBlank(bo.getBootPrice()), ShopDetail::getBootPrice, bo.getBootPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getOwnPictures()), ShopDetail::getOwnPictures, bo.getOwnPictures());
        return lqw;
    }

    /**
     * 新增商品详情
     *
     * @param bo 商品详情
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ShopDetailBo bo) {
        ShopDetail add = MapstructUtils.convert(bo, ShopDetail.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {


//            String url = "http://localhost:30200/api/updateSourceTable";
            String url = "http://localhost:9099/api/updateSourceTable";

            // 创建请求体，包含ID参数
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("ShopID", bo.getShopId().toString());

            // 设置请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");

            try {
                // 将请求对象转换为JSON字符串
                String jsonBody = HttpUtils.convertObjectToJson(requestBody);

                // 发送POST请求
                String response = HttpUtils.sendPost(url, headers, jsonBody);
                System.out.println("调用updateShopDetail接口成功，响应: " + response);
            } catch (Exception e) {
                System.err.println("调用updateShopDetail接口失败: " + e.getMessage());
                e.printStackTrace();
            }

//            insertShopDetialIntoRedis(bo);
        }
        return flag;
    }

    /**
     * 向redis，db7中添加数据
     * @param bo
     */
//    public void insertShopDetialIntoRedis(ShopDetailBo bo){
//        if (ObjectUtil.isEmpty(bo) || bo.getShopId() == null) {
//            return;
//        }
//
//        try {
//            String redisKey = bo.getShopId().toString();
//            // 构建shop_detail数据结构
//            Map<String, Object> shopDetailData = new LinkedHashMap<>();
//            shopDetailData.put("source_table", "t_shop_detail");
//            shopDetailData.put("data", bo);
//            String shopDetailJson = JsonObjUtil.objectToJsonWithSnakeKeys(shopDetailData);
//
//            // 获取Redis中的List
//            org.redisson.api.RList<String> redisList = RedisUtils.getThirdClient().getList(redisKey);
//            boolean updated = false;
//
//            // 遍历List，更新对应source_table的数据
//            for (int i = 0; i < redisList.size(); i++) {
//                String item = redisList.get(i);
//                Map<String, Object> itemMap = JSONUtil.toBean(item, Map.class);
//                if ("t_shop_detail".equals(itemMap.get("source_table"))) {
//                    redisList.set(i, shopDetailJson);
//                    updated = true;
//                    break;
//                }
//            }
//
//            // 如果没有找到对应数据，则添加新元素
//            if (!updated) {
//                redisList.add(shopDetailJson);
//            }
//
//        } catch (Exception e) {
//            System.out.println(e.getMessage());
//        }
//    }


    /**
     * 修改商品详情
     *
     * @param bo 商品详情
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ShopDetailBo bo) {
        ShopDetail update = MapstructUtils.convert(bo, ShopDetail.class);
        validEntityBeforeSave(update);

        // 修改关联的仓库id
        shopWarehouseService.deleteByShopId(bo.getShopId());
        for(Long warehouseId : bo.getWarehouseList()){
            ShopWarehouseBo shopWarehouseBo = new ShopWarehouseBo();
            shopWarehouseBo.setUserId(warehouseId);
            shopWarehouseBo.setShopId(bo.getShopId());
            shopWarehouseService.insertByBo(shopWarehouseBo);
        }

        // 修改关联的进销存仓库
        shopWarehouseAutoService.deleteByShopId(bo.getShopId());
        for (String data : bo.getMappingList()){
            String[] ids = data.split("-");
            String userId = ids[0];
            String warehouseId = ids[1];
            ShopWarehouseAuto shopWarehouseAuto = new ShopWarehouseAuto();
            shopWarehouseAuto.setShopId(bo.getShopId());
            shopWarehouseAuto.setUserId(Long.parseLong(userId));
            shopWarehouseAuto.setWarehouseId(Long.parseLong(warehouseId));
            shopWarehouseAutoService.insertByBo(shopWarehouseAuto);
        }

        ShopContextVo shopContextVo = shopContextService.selectByShopId(bo.getShopId());
        if(shopContextVo != null){
            //修改
            ShopContextBo shopContextBo = new ShopContextBo();
            shopContextBo.setId(shopContextVo.getId());
            shopContextBo.setContext(bo.getContext());
            shopContextService.updateByBo(shopContextBo);
        }else{
            ShopContextBo shopContextBo = new ShopContextBo();
            shopContextBo.setShopId(bo.getShopId());
            shopContextBo.setContext(bo.getContext());
            shopContextService.insertByBo(shopContextBo);
        }
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            // 修改成功后更新shopDetail的redis数据

//            String url = "http://localhost:30200/api/updateSourceTable";
            String url = "http://localhost:9099/api/updateSourceTable";

            // 创建请求体，包含ID参数
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("ShopID", bo.getShopId().toString());

            // 设置请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");

            try {
                // 将请求对象转换为JSON字符串
                String jsonBody = HttpUtils.convertObjectToJson(requestBody);

                // 发送POST请求
                String response = HttpUtils.sendPost(url, headers, jsonBody);
                System.out.println("调用updateShopDetail接口成功，响应: " + response);
            } catch (Exception e) {
                System.err.println("调用updateShopDetail接口失败: " + e.getMessage());
                e.printStackTrace();
            }
//            insertShopDetialIntoRedis(bo);
        }
        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ShopDetail entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除商品详情信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public UploadResult upload(MultipartFile file) {
        String originalfileName = file.getOriginalFilename();
        String suffix = StringUtils.substring(originalfileName, originalfileName.lastIndexOf("."), originalfileName.length());
        OssClient storage = OssFactory.instance();
        UploadResult uploadResult;
        try {
            uploadResult = storage.uploadSuffix(file.getBytes(), suffix, file.getContentType());
        } catch (IOException e) {
            throw new ServiceException(e.getMessage());
        }

        return uploadResult;
    }

    @Override
    public String selectSaleTemplateIdByShopId(Long shopId) {
        return baseMapper.selectSaleTemplateIdByShopId(shopId);
    }

}
