package com.ruoyi.jarvis.service.impl;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.jarvis.mapper.ErpProductMapper;
import com.ruoyi.jarvis.domain.ErpProduct;
import com.ruoyi.jarvis.service.IErpProductService;
import com.ruoyi.erp.request.IERPAccount;
import com.ruoyi.jarvis.service.erp.ErpAccountResolver;
import com.ruoyi.erp.request.ProductListQueryRequest;
import com.ruoyi.erp.request.ProductDeleteRequest;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import java.util.HashSet;
import java.util.stream.Collectors;

/**
 * 闲鱼商品Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@Service
public class ErpProductServiceImpl implements IErpProductService 
{
    private static final Logger log = LoggerFactory.getLogger(ErpProductServiceImpl.class);

    @Autowired
    private ErpProductMapper erpProductMapper;

    @Autowired
    private ErpAccountResolver erpAccountResolver;

    /**
     * 查询闲鱼商品
     * 
     * @param id 闲鱼商品主键
     * @return 闲鱼商品
     */
    @Override
    public ErpProduct selectErpProductById(Long id)
    {
        return erpProductMapper.selectErpProductById(id);
    }

    /**
     * 查询闲鱼商品列表
     * 
     * @param erpProduct 闲鱼商品
     * @return 闲鱼商品
     */
    @Override
    public List<ErpProduct> selectErpProductList(ErpProduct erpProduct)
    {
        return erpProductMapper.selectErpProductList(erpProduct);
    }

    /**
     * 新增闲鱼商品
     * 
     * @param erpProduct 闲鱼商品
     * @return 结果
     */
    @Override
    public int insertErpProduct(ErpProduct erpProduct)
    {
        // 检查是否已存在
        ErpProduct existing = erpProductMapper.selectErpProductByProductIdAndAppid(
            erpProduct.getProductId(), erpProduct.getAppid());
        if (existing != null) {
            // 更新已存在的商品
            erpProduct.setId(existing.getId());
            return erpProductMapper.updateErpProduct(erpProduct);
        }
        return erpProductMapper.insertErpProduct(erpProduct);
    }

    /**
     * 修改闲鱼商品
     * 
     * @param erpProduct 闲鱼商品
     * @return 结果
     */
    @Override
    public int updateErpProduct(ErpProduct erpProduct)
    {
        return erpProductMapper.updateErpProduct(erpProduct);
    }

    /**
     * 批量删除闲鱼商品
     * 
     * @param ids 需要删除的闲鱼商品主键
     * @return 结果
     */
    @Override
    public int deleteErpProductByIds(Long[] ids)
    {
        return erpProductMapper.deleteErpProductByIds(ids);
    }

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

    /**
     * 从闲鱼ERP拉取商品列表并保存
     * 
     * @param appid ERP应用ID
     * @param pageNo 页码
     * @param pageSize 每页大小
     * @param productStatus 商品状态
     * @return 拉取并保存的商品数量
     */
    @Override
    public int pullAndSaveProductList(String appid, Integer pageNo, Integer pageSize, Integer productStatus)
    {
        try {
            // 解析ERP账号
            IERPAccount account = erpAccountResolver.resolve(appid);
            
            // 创建查询请求
            ProductListQueryRequest request = new ProductListQueryRequest(account);
            if (pageNo != null) {
                request.setPageNo(pageNo);
            }
            if (pageSize != null) {
                request.setPageSize(pageSize);
            }
            if (productStatus != null) {
                // API要求的状态值：-1(全部), 10(上架), 21(下架), 22(草稿), 23(审核中), 31(已售), 33(已删除), 36(违规)
                // 前端传入的简化状态值：1(上架), 2(下架), 3(已售)
                Integer apiStatus = convertProductStatus(productStatus);
                if (apiStatus != null) {
                    request.setProductStatus(apiStatus);
                }
            }
            
            // 调用接口获取商品列表
            String responseBody = request.getResponseBody();
            JSONObject response = JSONObject.parseObject(responseBody);
            
            if (response == null || response.getInteger("code") == null || response.getInteger("code") != 0) {
                String errorMsg = response != null ? response.getString("msg") : "未知错误";
                log.error("拉取商品列表失败: code={}, msg={}, response={}", 
                    response != null ? response.getInteger("code") : null, errorMsg, responseBody);
                throw new RuntimeException("拉取商品列表失败: " + errorMsg);
            }
            
            // 解析商品列表
            JSONObject data = response.getJSONObject("data");
            if (data == null) {
                log.warn("拉取商品列表返回数据为空");
                return 0;
            }
            
            JSONArray productList = data.getJSONArray("list");
            Integer totalCount = data.getInteger("count");
            
            if (productList == null || productList.isEmpty()) {
                String statusMsg = productStatus != null ? "（状态：" + productStatus + "）" : "";
                if (totalCount != null && totalCount > 0) {
                    log.info("拉取商品列表为空，但总数显示为 {}，可能是分页问题", totalCount);
                } else {
                    log.info("拉取商品列表为空{}，该账号下没有符合条件的商品", statusMsg);
                }
                return 0;
            }
            
            log.info("拉取到 {} 个商品，开始保存", productList.size());
            
            // 转换为实体对象并保存
            List<ErpProduct> erpProducts = new ArrayList<>();
            for (int i = 0; i < productList.size(); i++) {
                JSONObject productJson = productList.getJSONObject(i);
                ErpProduct erpProduct = parseProductJson(productJson, appid);
                if (erpProduct != null) {
                    erpProducts.add(erpProduct);
                }
            }
            
            // 批量保存或更新
            if (!erpProducts.isEmpty()) {
                // 逐个保存（兼容更新）
                int savedCount = 0;
                for (ErpProduct product : erpProducts) {
                    ErpProduct existing = erpProductMapper.selectErpProductByProductIdAndAppid(
                        product.getProductId(), product.getAppid());
                    if (existing != null) {
                        product.setId(existing.getId());
                        erpProductMapper.updateErpProduct(product);
                    } else {
                        erpProductMapper.insertErpProduct(product);
                    }
                    savedCount++;
                }
                log.info("成功拉取并保存 {} 个商品", savedCount);
                return savedCount;
            }
            
            return 0;
        } catch (Exception e) {
            log.error("拉取商品列表异常", e);
            throw new RuntimeException("拉取商品列表失败: " + e.getMessage(), e);
        }
    }

    /**
     * 解析商品JSON数据
     */
    private ErpProduct parseProductJson(JSONObject productJson, String appid) {
        try {
            ErpProduct product = new ErpProduct();
            
            // 管家商品ID
            Long productId = productJson.getLong("product_id");
            if (productId == null) {
                log.warn("商品ID为空，跳过: {}", productJson);
                return null;
            }
            product.setProductId(productId);
            
            // 商品标题
            product.setTitle(productJson.getString("title"));
            
            // 商品图片（取第一张）
            JSONArray images = productJson.getJSONArray("images");
            if (images != null && !images.isEmpty()) {
                product.setMainImage(images.getString(0));
            }
            
            // 价格（分）
            Long price = productJson.getLong("price");
            if (price == null) {
                // 尝试从price字段解析
                Object priceObj = productJson.get("price");
                if (priceObj instanceof Number) {
                    price = ((Number) priceObj).longValue();
                }
            }
            product.setPrice(price);
            
            // 库存
            Integer stock = productJson.getInteger("stock");
            product.setStock(stock);
            
            // 商品状态
            Integer productStatus = productJson.getInteger("product_status");
            product.setProductStatus(productStatus);
            
            // 销售状态
            Integer saleStatus = productJson.getInteger("sale_status");
            product.setSaleStatus(saleStatus);
            
            // 闲鱼会员名
            product.setUserName(productJson.getString("user_name"));
            
            // 时间字段（时间戳，秒）
            product.setOnlineTime(productJson.getLong("online_time"));
            product.setOfflineTime(productJson.getLong("offline_time"));
            product.setSoldTime(productJson.getLong("sold_time"));
            product.setCreateTimeXy(productJson.getLong("create_time"));
            product.setUpdateTimeXy(productJson.getLong("update_time"));
            
            // ERP应用ID
            product.setAppid(appid);
            
            // 商品链接
            product.setProductUrl(productJson.getString("product_url"));
            
            return product;
        } catch (Exception e) {
            log.error("解析商品JSON失败: {}", productJson, e);
            return null;
        }
    }

    /**
     * 转换商品状态值：将前端状态值转换为API需要的状态值
     * 实际状态值：-1(删除), 21(待发布), 22(销售中), 23(已售罄), 31(手动下架), 33(售出下架), 36(自动下架)
     * API支持的状态值：-1, 10, 21, 22, 23, 31, 33, 36
     * 前端传入的状态值直接使用，不做转换
     */
    private Integer convertProductStatus(Integer frontendStatus) {
        if (frontendStatus == null) {
            return null;
        }
        // 直接使用前端传入的状态值（-1, 21, 22, 23, 31, 33, 36）
        // API支持的状态值列表
        if (frontendStatus == -1 || frontendStatus == 10 || frontendStatus == 21 || 
            frontendStatus == 22 || frontendStatus == 23 || frontendStatus == 31 || 
            frontendStatus == 33 || frontendStatus == 36) {
            return frontendStatus;
        }
        log.warn("未知的商品状态值: {}, 将不设置状态筛选", frontendStatus);
        return null;
    }

    /**
     * 全量同步商品列表（自动遍历所有页码，同步更新和删除）
     */
    @Override
    public IErpProductService.SyncResult syncAllProducts(String appid, Integer productStatus) {
        IErpProductService.SyncResult result = new IErpProductService.SyncResult();
        Set<Long> remoteProductIds = new HashSet<>(); // 远程商品ID集合
        int pageNo = 1;
        int pageSize = 50; // 每页50条，尽量少请求次数
        int totalPulled = 0;
        int added = 0;
        int updated = 0;
        
        try {
            IERPAccount account = erpAccountResolver.resolve(appid);
            
            // 第一步：遍历所有页码，拉取并保存所有商品
            log.info("开始全量同步商品，账号：{}", appid);
            while (true) {
                ProductListQueryRequest request = new ProductListQueryRequest(account);
                request.setPage(pageNo, pageSize);
                
                if (productStatus != null) {
                    Integer apiStatus = convertProductStatus(productStatus);
                    if (apiStatus != null) {
                        request.setProductStatus(apiStatus);
                    }
                }
                
                String responseBody = request.getResponseBody();
                JSONObject response = JSONObject.parseObject(responseBody);
                
                if (response == null || response.getInteger("code") == null || response.getInteger("code") != 0) {
                    String errorMsg = response != null ? response.getString("msg") : "未知错误";
                    log.error("拉取商品列表失败（页码：{}）: {}", pageNo, errorMsg);
                    result.setFailed(result.getFailed() + 1);
                    break;
                }
                
                JSONObject data = response.getJSONObject("data");
                if (data == null) {
                    log.warn("拉取商品列表返回数据为空（页码：{}）", pageNo);
                    break;
                }
                
                JSONArray productList = data.getJSONArray("list");
                
                if (productList == null || productList.isEmpty()) {
                    log.info("第 {} 页数据为空，同步完成", pageNo);
                    break;
                }
                
                // 处理当前页商品
                for (int i = 0; i < productList.size(); i++) {
                    JSONObject productJson = productList.getJSONObject(i);
                    ErpProduct erpProduct = parseProductJson(productJson, appid);
                    if (erpProduct != null && erpProduct.getProductId() != null) {
                        remoteProductIds.add(erpProduct.getProductId());
                        
                        // 保存或更新商品
                        ErpProduct existing = erpProductMapper.selectErpProductByProductIdAndAppid(
                            erpProduct.getProductId(), erpProduct.getAppid());
                        if (existing != null) {
                            erpProduct.setId(existing.getId());
                            erpProductMapper.updateErpProduct(erpProduct);
                            updated++;
                        } else {
                            erpProductMapper.insertErpProduct(erpProduct);
                            added++;
                        }
                        totalPulled++;
                    }
                }
                
                log.info("已同步第 {} 页，共 {} 条商品", pageNo, productList.size());
                
                // 判断是否还有下一页
                if (productList.size() < pageSize) {
                    log.info("已拉取完所有页码，共 {} 页", pageNo);
                    break;
                }
                
                pageNo++;
            }
            
            result.setTotalPulled(totalPulled);
            result.setAdded(added);
            result.setUpdated(updated);
            
            // 第二步：对比本地和远程，删除本地有但远程没有的商品
            log.info("开始同步删除，远程商品数：{}", remoteProductIds.size());
            
            // 查询本地该账号下的所有商品
            ErpProduct queryParam = new ErpProduct();
            queryParam.setAppid(appid);
            List<ErpProduct> localProducts = erpProductMapper.selectErpProductList(queryParam);
            
            // 找出需要删除的商品（本地有但远程没有的）
            List<ErpProduct> toDelete = localProducts.stream()
                .filter(p -> !remoteProductIds.contains(p.getProductId()))
                .collect(Collectors.toList());
            
            if (!toDelete.isEmpty()) {
                log.info("发现 {} 个本地商品在远程已不存在，开始删除", toDelete.size());
                
                for (ErpProduct product : toDelete) {
                    try {
                        // 先调用远程删除接口
                        ProductDeleteRequest deleteRequest = new ProductDeleteRequest(account);
                        deleteRequest.setProductId(product.getProductId());
                        String deleteResponse = deleteRequest.getResponseBody();
                        JSONObject deleteResult = JSONObject.parseObject(deleteResponse);
                        
                        if (deleteResult != null && deleteResult.getInteger("code") != null && 
                            deleteResult.getInteger("code") == 0) {
                            // 远程删除成功，删除本地记录
                            erpProductMapper.deleteErpProductById(product.getId());
                            result.setDeleted(result.getDeleted() + 1);
                            log.debug("成功删除商品：{}", product.getProductId());
                        } else {
                            // 远程删除失败，记录日志但不删除本地（可能是远程已经删除了）
                            String errorMsg = deleteResult != null ? deleteResult.getString("msg") : "未知错误";
                            log.warn("远程删除商品失败（可能已不存在）：{}，错误：{}", product.getProductId(), errorMsg);
                            // 如果远程返回商品不存在的错误，也删除本地记录
                            if (errorMsg != null && (errorMsg.contains("不存在") || errorMsg.contains("not found"))) {
                                erpProductMapper.deleteErpProductById(product.getId());
                                result.setDeleted(result.getDeleted() + 1);
                            } else {
                                result.setFailed(result.getFailed() + 1);
                            }
                        }
                    } catch (Exception e) {
                        log.error("删除商品异常：{}", product.getProductId(), e);
                        result.setFailed(result.getFailed() + 1);
                    }
                }
            }
            
            // 构建结果消息
            StringBuilder msg = new StringBuilder();
            msg.append(String.format("同步完成！拉取：%d个，新增：%d个，更新：%d个，删除：%d个", 
                totalPulled, added, updated, result.getDeleted()));
            if (result.getFailed() > 0) {
                msg.append(String.format("，失败：%d个", result.getFailed()));
            }
            result.setMessage(msg.toString());
            
            log.info(result.getMessage());
            return result;
            
        } catch (Exception e) {
            log.error("全量同步商品异常", e);
            result.setMessage("同步失败: " + e.getMessage());
            result.setFailed(result.getFailed() + 1);
            throw new RuntimeException("全量同步商品失败: " + e.getMessage(), e);
        }
    }

}

