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.bean.model.ShopCategory;
import com.yami.shop.common.util.hb.HBR;
import com.yami.shop.dao.FrontCategoryMapper;
import com.yami.shop.dao.ShopCategoryMapper;
import com.yami.shop.service.hb.IHBFrontCategoryService;
import com.yami.shop.utils.HBSignUtil;
import com.yami.shop.utils.SmqjhUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
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
public class HBFrontCategoryService implements IHBFrontCategoryService {
    private final FrontCategoryMapper frontCategoryMapper;
    private final ShopCategoryMapper shopCategoryMapper;
    private final HBSignUtil hbSignUtil;

    private final SmqjhUtil smqjhUtil;


    @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");
            if (ObjectUtils.isEmpty(codeList)) {
                return HBR.success();
            }
            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);

                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);
                    List<ShopCategory> shopCategory = shopCategoryMapper.selectList(new LambdaQueryWrapper<ShopCategory>()
                            .eq(ShopCategory::getCode, frontCategory.getCode())
                            .eq(ShopCategory::getIsDelete, 0));
                    for (ShopCategory shopCategory1 : shopCategory) {
                        shopCategory1.setName(frontCategory.getName());
                        shopCategory1.setNum(frontCategory.getNum());
                        shopCategoryMapper.updateById(shopCategory1);
                        try {
                            String syncUrl = smqjhUtil.getSmqjhPmsUrl()  + "/syncShopCategoryData";
                            // 将frontCategory对象作为JSON放入请求体
                            String response = com.yami.shop.common.util.HttpUtil.post(syncUrl, shopCategory1);
                            log.info("推送frontCategory到同步服务器结果: {}", response);
                        } catch (Exception e) {
                            log.error("推送frontCategory到同步服务器失败: {}", e.getMessage(), e);
                        }

                    }
                }

            }
            log.info("前台分类成功");
            // 4. 构建响应
            return HBR.success();
        } catch (Exception e) {
            log.error("前台分类失败：{}", e.getMessage(), e);
            return HBR.error("未知异常");
        }
    }

    /**
     * 添加门店分类
     *
     * @param frontCategory 前台分类
     * @param shopId        门店id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addShopCategory(FrontCategory frontCategory, Long shopId, Long hbShopId) {
        ShopCategory shopCategoryByCode = shopCategoryMapper.selectOne(new LambdaQueryWrapper<ShopCategory>()
                .eq(ShopCategory::getCode, frontCategory.getCode())
                .eq(ShopCategory::getShopId, shopId)
                .eq(ShopCategory::getIsDelete, 0));

        if (shopCategoryByCode != null) {
            return;
        }
        ShopCategory shopCategory = new ShopCategory();
        shopCategory.setCode(frontCategory.getCode());
        shopCategory.setName(frontCategory.getName());
        if (frontCategory.getParentCode() == null || frontCategory.getParentCode().equals("0")) {
            shopCategory.setPid(0L);
            shopCategory.setParentCode("0");
        } else {
            ShopCategory shopCategoryByCode1 = shopCategoryMapper.selectOne(new LambdaQueryWrapper<ShopCategory>()
                    .eq(ShopCategory::getCode, frontCategory.getParentCode())
                    .eq(ShopCategory::getShopId, shopId)
                    .eq(ShopCategory::getIsDelete, 0));
            if (shopCategoryByCode1 == null) {
                //不存在门店分类父类目添加
                FrontCategory frontCategoryParent = frontCategoryMapper.selectOne(new LambdaQueryWrapper<FrontCategory>()
                        .eq(FrontCategory::getCode, frontCategory.getParentCode())
                        .eq(FrontCategory::getIsDelete, 0));
                addShopCategory(frontCategoryParent, shopId, hbShopId);
            }
            shopCategory.setPid(shopCategoryByCode1.getId());
            shopCategory.setParentCode(shopCategoryByCode1.getCode());
        }

        shopCategory.setShopId(shopId);
        shopCategory.setHbShopId(String.valueOf(hbShopId));
        shopCategory.setLabel(frontCategory.getLabel());
        shopCategory.setIcon(frontCategory.getIcon());
        shopCategory.setPic(frontCategory.getPic());
        shopCategory.setLevel(frontCategory.getLevel());
        shopCategory.setIsDelete(0);
        shopCategory.setOperateUser("admin");
        shopCategory.setNum(frontCategory.getNum());
        shopCategory.setIsLeaves(frontCategory.getIsLeaves());

        shopCategoryMapper.insert(shopCategory);
        try {
            String syncUrl = smqjhUtil.getSmqjhPmsUrl() + "/syncShopCategoryData";
            String response = com.yami.shop.common.util.HttpUtil.post(syncUrl, shopCategory);
            log.info("推送门店分类到同步服务器结果: {}", response);
        } catch (Exception e) {
            log.error("推送门店分类到同步服务器失败: {}", e.getMessage(), e);
        }

    }

    @Override
    public void sync(Long shopId, Long hbShopId) {
        List<FrontCategory> frontCategoryList = frontCategoryMapper.selectList(new LambdaQueryWrapper<FrontCategory>()
                .eq(FrontCategory::getIsDelete, 0));

        for (FrontCategory frontCategory : frontCategoryList) {
            addShopCategory(frontCategory, shopId, hbShopId);
        }
    }

    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) {
        JSONObject body = hbRequest.getJSONObject("body");
        JSONArray codeList = body.getJSONArray("codeList");
        for (Object codeObject : codeList) {    
            String code = codeObject.toString();
            log.info("前台类目删除，body：{}", code);
            FrontCategory frontCategory = frontCategoryMapper.selectOne(new LambdaQueryWrapper<FrontCategory>()
                    .eq(FrontCategory::getIsDelete, 0)
                    .eq(FrontCategory::getCode, Long.valueOf(code)));
            if (frontCategory == null) {
                return;
            }
            frontCategory.setIsDelete(1);
            frontCategoryMapper.updateById(frontCategory);
            shopCategoryMapper.deleteByCode(code);

            try {
                List<ShopCategory> shopCategories = shopCategoryMapper.selectList(new LambdaQueryWrapper<ShopCategory>().eq(ShopCategory::getCode, code));
                for (ShopCategory shopCategory : shopCategories) {
                    String syncUrl = smqjhUtil.getSmqjhPmsUrl() + "/syncShopCategoryData";
                    String response = com.yami.shop.common.util.HttpUtil.post(syncUrl, shopCategory);
                    log.info("推送门店分类到同步服务器结果: {}", response);
                }
            } catch (Exception e) {
                log.error("推送门店分类到同步服务器失败: {}", e.getMessage(), e);
            }

        }
    }

}
