package org.dromara.zhishu.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import org.dromara.zhishu.util.HttpUtils;
import org.dromara.zhishu.util.JsonObjUtil;
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.redis.utils.RedisUtils;
import org.springframework.stereotype.Service;
import org.dromara.zhishu.domain.bo.SpecBo;
import org.dromara.zhishu.domain.vo.SpecVo;
import org.dromara.zhishu.domain.Spec;
import org.dromara.zhishu.mapper.SpecMapper;
import org.dromara.zhishu.service.ISpecService;

import java.util.*;

/**
 * 自定义规格设置Service业务层处理
 *
 * @author yxy
 * @date 2025-03-27
 */
@RequiredArgsConstructor
@Service
public class SpecServiceImpl implements ISpecService {

    private final SpecMapper baseMapper;

    /**
     * 查询自定义规格设置
     *
     * @param id 主键
     * @return 自定义规格设置
     */
    @Override
    public SpecVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    @Override
    public SpecVo selectVoByShopId(Long shopId) {
        return baseMapper.selectVoByShopId(shopId);
    }

    /**
     * 分页查询自定义规格设置列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 自定义规格设置分页列表
     */
    @Override
    public TableDataInfo<SpecVo> queryPageList(SpecBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Spec> lqw = buildQueryWrapper(bo);
        Page<SpecVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的自定义规格设置列表
     *
     * @param bo 查询条件
     * @return 自定义规格设置列表
     */
    @Override
    public List<SpecVo> queryList(SpecBo bo) {
        LambdaQueryWrapper<Spec> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Spec> buildQueryWrapper(SpecBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Spec> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(Spec::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getSpecTypeId()), Spec::getSpecTypeId, bo.getSpecTypeId());
        lqw.like(StringUtils.isNotBlank(bo.getSpecTypeName()), Spec::getSpecTypeName, bo.getSpecTypeName());
        lqw.eq(StringUtils.isNotBlank(bo.getSpecCompose()), Spec::getSpecCompose, bo.getSpecCompose());
        lqw.like(StringUtils.isNotBlank(bo.getSpecName()), Spec::getSpecName, bo.getSpecName());
        lqw.eq(StringUtils.isNotBlank(bo.getSpecPrefix()), Spec::getSpecPrefix, bo.getSpecPrefix());
        lqw.eq(StringUtils.isNotBlank(bo.getSpecSuffix()), Spec::getSpecSuffix, bo.getSpecSuffix());
        lqw.eq(StringUtils.isNotBlank(bo.getSpecCodeCompose()), Spec::getSpecCodeCompose, bo.getSpecCodeCompose());
        lqw.eq(StringUtils.isNotBlank(bo.getSpecCodePrefix()), Spec::getSpecCodePrefix, bo.getSpecCodePrefix());
        lqw.eq(StringUtils.isNotBlank(bo.getSpecCodeSuffix()), Spec::getSpecCodeSuffix, bo.getSpecCodeSuffix());
        lqw.eq(StringUtils.isNotBlank(bo.getSpecSyUrl()), Spec::getSpecSyUrl, bo.getSpecSyUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), Spec::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增自定义规格设置
     *
     * @param bo 自定义规格设置
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SpecBo bo) {
        Spec add = MapstructUtils.convert(bo, Spec.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            // 新增成功后添加到Redis

            //更新Redis
//            String specUrl = "http://localhost:30200/api/updateSourceTable";
            String specUrl = "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(specUrl, headers, jsonBody);
                System.out.println("调用updateShopHandler接口成功，响应: " + requestBody);
            } catch (Exception e) {
                System.err.println("调用updateShopHandler接口失败: " + e.getMessage());
                e.printStackTrace();
            }
//            insertSpecIntoRedis(bo);
        }
        return flag;
    }

    /**
     * 修改自定义规格设置
     *
     * @param bo 自定义规格设置
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SpecBo bo) {
        Spec update = MapstructUtils.convert(bo, Spec.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            // 更新成功后更新Redis中的spec数据


            //更新Redis
//            String specUrl = "http://localhost:30200/api/updateSourceTable";
            String specUrl = "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(specUrl, headers, jsonBody);
                System.out.println("调用updateShopHandler接口成功，响应: " + requestBody);
            } catch (Exception e) {
                System.err.println("调用updateShopHandler接口失败: " + e.getMessage());
                e.printStackTrace();
            }
//            insertSpecIntoRedis(bo);
        }
        return flag;
    }

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

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

    /**
     * 向redis，db7中添加t_spec数据
     * @param bo
     */
//    public void insertSpecIntoRedis(SpecBo bo){
//        if (ObjectUtil.isEmpty(bo) || bo.getShopId() == null) {
//            return;
//        }
//
//        try {
//            String redisKey = bo.getShopId().toString();
//            // 构建t_specd数据结构
//            Map<String, Object> specData = new LinkedHashMap<>();
//            specData.put("source_table", "t_spec");
//            specData.put("data", bo);
//            String specJson = JsonObjUtil.objectToJsonWithSnakeKeys(specData);
//
//            // 获取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_spec".equals(itemMap.get("source_table"))) {
//                    redisList.set(i, specJson);
//                    updated = true;
//                    break;
//                }
//            }
//
//            // 如果没有找到对应数据，则添加新元素
//            if (!updated) {
//                redisList.add(specJson);
//            }
//
//        } catch (Exception e) {
//            System.out.println(e.getMessage());
//        }
//    }
}
