package com.yami.shop.service.hb.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.dto.hb.HBBaseReq;
import com.yami.shop.bean.model.FrontCategory;
import com.yami.shop.common.util.hb.HBR;
import com.yami.shop.dao.FrontCategoryMapper;
import com.yami.shop.service.hb.IHBFrontCategoryService;
import com.yami.shop.utils.HBSignUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static com.yami.shop.common.util.HttpUtil.post;


/**
 * 前台类目管理服务实现
 *
 * @author fubojin
 * @version 1.0.0
 * @since 2025-09-1
 */
@Slf4j
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class HBFrontCategoryService implements IHBFrontCategoryService {
    private final FrontCategoryMapper frontCategoryMapper;
    private final HBSignUtil hbSignUtil;


    @Override
    @Transactional
    public HBR addHBFrontCategory(JSONObject hbRequest) {
        try {
            String bodyStr = hbRequest.getString("body");
            log.info("开始前台分类，body：{}", bodyStr);
            JSONObject bodyJson = JSON.parseObject(bodyStr); // 使用Fastjson的解析方法
            JSONArray codeList = bodyJson.getJSONArray("codeList");
            List<String> resultList = IntStream.range(0, codeList.size())
                    .mapToObj(codeList::getString)
                    .collect(Collectors.toList());

            String info = selectHBFrontCategory(resultList);
            JSONObject jsonObject = JSON.parseObject(info);
            JSONObject jsonObjectHB = jsonObject.getJSONObject("result");
            JSONObject result = jsonObjectHB.getJSONObject("result");
            JSONArray resultArray = result.getJSONArray("categoryInfos");
            for (Object o : resultArray) {
                JSONObject jsonObjectInfo = JSON.parseObject(o.toString());
                // 2. 构建实体
                FrontCategory frontCategory = new FrontCategory();
                frontCategory.setCode(jsonObjectInfo.getString("code"));
                frontCategory.setParentCode(jsonObjectInfo.getString("parentCode"));
                frontCategory.setName(jsonObjectInfo.getString("name"));
                frontCategory.setParentName(jsonObjectInfo.getString("parentName"));
                frontCategory.setNum(jsonObjectInfo.getInteger("num"));
                frontCategory.setLevel(jsonObjectInfo.getInteger("level"));
                frontCategory.setOperateUser(jsonObjectInfo.getString("operateUser"));
                frontCategory.setIsLeaves(jsonObjectInfo.getInteger("isLeaves"));
                frontCategory.setIcon(jsonObjectInfo.getString("https://zswl-shop.oss-cn-chengdu.aliyuncs.com/2025/09/fe56414a161b498b8f263d3e6afdab92.png"));
                frontCategory.setPic(jsonObjectInfo.getString("https://zswl-shop.oss-cn-chengdu.aliyuncs.com/2025/09/fe56414a161b498b8f263d3e6afdab92.png"));
                log.info("添加前台类目信息{}",frontCategory);

//                if (ObjectUtils.isNotEmpty(jsonObjectInfo.getString("parentCode")) && !jsonObjectInfo.getString("parentCode").equals("0")) {
//                    frontCategoryMapper.selectOne(new LambdaQueryWrapper<FrontCategory>().
//                            eq(FrontCategory::getParentCode, frontCategory.getParentCode())
//                            .eq(FrontCategory::getIsDelete, 0));
//                    if (frontCategory.getParentCode() == null) {
//                        FrontCategory frontCategory1 = new FrontCategory();
//                        frontCategory1.setCode(jsonObjectInfo.getString("parentCode"));
//                        frontCategory1.setName(jsonObjectInfo.getString("parentName"));
//                        frontCategory1.setIsDelete(0);
//                        frontCategoryMapper.insert(frontCategory1);
//                    }
//                }
                FrontCategory frontCategory1 = frontCategoryMapper.selectOne(new LambdaQueryWrapper<FrontCategory>().
                        eq(FrontCategory::getCode, frontCategory.getCode())
                        .eq(FrontCategory::getIsDelete, 0));
                if (frontCategory1 == null) {
                    frontCategoryMapper.insert(frontCategory);
                } else {
                    frontCategory.setId(frontCategory1.getId());
                    frontCategoryMapper.updateById(frontCategory);
                }
                // 3. 保存门店信息
//                frontCategoryMapper.insert(frontCategory);
            }
            log.info("前台分类成功");
            // 4. 构建响应
            return HBR.success();
        } catch (Exception e) {
            log.error("前台分类失败：{}", e.getMessage(), e);
            return HBR.error("未知异常");
        }
    }

    public String selectHBFrontCategory(List<String> resultList) {
        HBBaseReq<Object> build = HBBaseReq.create();
        build.setAppId(hbSignUtil.getAppId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("flag", 1);
        jsonObject.put("codeList", resultList);
        build.setBody(JSON.toJSONString(jsonObject));
        build.setSign(hbSignUtil.signMd5(build));
        String post = post(hbSignUtil.getHBHost() + "/api/product/frontCategory/getCategory", build);
        log.info("post 请求参数：{}", JSON.toJSONString(build));
        log.info("post 结果：{}", post);
        return post;
    }

    @Override
    public void deleteFrontCategory(JSONObject hbRequest) {
        String bodyStr = hbRequest.getString("body");
        JSONObject jsonObject = JSON.parseObject("bodyStr");
        log.info("前台类目删除，body：{}", bodyStr);
        List<FrontCategory> frontCategorys = frontCategoryMapper.selectList(new LambdaQueryWrapper<FrontCategory>().eq(FrontCategory::getCode,jsonObject.getLong("code")));
        for (FrontCategory frontCategory : frontCategorys) {
            frontCategory.setIsDelete(1);
            frontCategoryMapper.updateById(frontCategory);
        }
    }
}
