package com.haha.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haha.common.constant.CommonConstants;
import com.haha.common.constant.SyncConstants;
import com.haha.common.exception.BusinessException;
import com.haha.common.utils.EntityLabelUtils;
import com.haha.entity.Product;
import com.haha.mapper.ProductMapper;
import com.haha.sdk.HahaClient;
import com.haha.sdk.exception.HahaException;
import com.haha.service.ProductService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    private final HahaClient hahaClient;

    @Override
    public IPage<Product> getPage(int page, int pageSize, String name, String barcode, 
                                   String category, Integer syncStatus) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        
        wrapper.like(name != null && !name.isEmpty(), Product::getName, name)
               .like(barcode != null && !barcode.isEmpty(), Product::getBarcode, barcode)
               .eq(category != null && !category.isEmpty(), Product::getType, category)
               .eq(syncStatus != null, Product::getSyncStatus, syncStatus)
               .eq(Product::getIsDeleted, CommonConstants.NOT_DELETED)
               .orderByDesc(Product::getCreateTime);

        IPage<Product> productPage = this.page(new Page<>(page, pageSize), wrapper);

        // 填充额外字段
        productPage.getRecords().forEach(this::fillProductLabels);
        
        return productPage;
    }

    @Override
    public Product getDetailById(Long id) {
        Product product = this.getById(id);
        if (product == null) {
            return null;
        }
        fillProductLabels(product);
        return product;
    }

    @Override
    public Map<String, Object> getStatistics() {
        Map<String, Object> statistics = new HashMap<>();

        // 总商品数（未删除）
        long totalProducts = this.lambdaQuery()
                .eq(Product::getIsDeleted, CommonConstants.NOT_DELETED)
                .count();
        statistics.put("totalProducts", totalProducts);

        // 已同步商品数
        long syncedProducts = this.lambdaQuery()
                .eq(Product::getIsDeleted, CommonConstants.NOT_DELETED)
                .eq(Product::getSyncStatus, SyncConstants.STATUS_SYNCED)
                .count();
        statistics.put("syncedProducts", syncedProducts);

        return statistics;
    }

    @Override
    public Product add(Product product) {
        product.setIsDeleted(CommonConstants.NOT_DELETED);
        product.setSyncStatus(SyncConstants.STATUS_NOT_SYNCED);
        product.setCreateTime(LocalDateTime.now());
        product.setUpdateTime(LocalDateTime.now());
        
        this.save(product);
        return product;
    }

    @Override
    public Product edit(Long id, Product product) {
        Product existing = this.getById(id);
        if (existing == null) {
            throw new BusinessException(404, "商品不存在");
        }
        
        product.setId(id);
        product.setUpdateTime(LocalDateTime.now());
        
        this.updateById(product);
        return product;
    }

    @Override
    public boolean softDelete(Long id) {
        Product product = this.getById(id);
        if (product == null) {
            throw new BusinessException(404, "商品不存在");
        }
        
        product.setIsDeleted(CommonConstants.DELETED);
        product.setUpdateTime(LocalDateTime.now());
        
        return this.updateById(product);
    }

    @Override
    public boolean syncToHaha(Long id) {
        Product product = this.getById(id);
        if (product == null) {
            throw new BusinessException(404, "商品不存在");
        }
        
        log.info("同步商品到哈哈平台: productId={}, name={}", id, product.getName());

        // TODO: 调用SDK同步商品到哈哈平台

        // 更新同步状态
        return this.updateSyncStatus(id, SyncConstants.STATUS_SYNCED);
    }

    @Override
    public List<Product> getProductListBydeviceId(String deviceId) {
        try {
            Map<String, Object> result = hahaClient.getGoodsApi().getDeviceGoodsList(deviceId, null);
            if (result != null && result.containsKey("dataInfo")) {
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> dataInfoList = (List<Map<String, Object>>) result.get("dataInfo");
                return dataInfoList.stream()
                    .flatMap(category -> {
                        @SuppressWarnings("unchecked")
                        List<Map<String, Object>> goodsList = (List<Map<String, Object>>) category.get("goods");
                        if (goodsList == null) return java.util.stream.Stream.empty();
                        return goodsList.stream().map(item -> {
                            Product product = new Product();
                            product.setCode((String) item.get("code"));
                            product.setName((String) item.get("name"));
                            product.setPic((String) item.get("pic"));
                            if (item.get("c_price") != null) {
                                try {
                                    product.setPrice(Double.parseDouble(item.get("c_price").toString()));
                                } catch (NumberFormatException e) {
                                    log.debug("价格解析失败: {}", item.get("c_price"));
                                }
                            }
                            return product;
                        });
                    })
                    .collect(Collectors.toList());
            }
        } catch (Exception e) {
            log.error("获取设备商品列表失败 - deviceId: {}, error: {}", deviceId, e.getMessage());
        }
        return list();
    }

    @Override
    public List<Product> getProductListByCategory(Integer categoryId) {
        // 这里需要实现根据分类ID获取商品列表的逻辑，暂时返回所有商品
        return list();
    }

    @Override
    public Product getProductByBarcode(String barcode) {
        return lambdaQuery().eq(Product::getBarcode, barcode).one();
    }

    @Override
    public Product getProductByCode(String code) {
        return lambdaQuery().eq(Product::getCode, code).one();
    }

    @Override
    public List<Product> listByCodes(java.util.Collection<String> codes) {
        if (codes == null || codes.isEmpty()) {
            return List.of();
        }
        return lambdaQuery().in(Product::getCode, codes).list();
    }

    @Override
    public boolean updateSyncStatus(Long productId, Integer syncStatus) {
        return lambdaUpdate()
                .eq(Product::getId, productId)
                .set(Product::getSyncStatus, syncStatus)
                .set(Product::getSyncTime, LocalDateTime.now())
                .update();
    }

    @Override
    public Map<String, Object> getMasterProductList(int page, int pageSize, String barcode,
                                                     String code, String productName, String deviceAdapt) {
        try {
            Map<String, Object> result = hahaClient.getGoodsApi()
                    .getTotalList(page, pageSize, barcode, code, productName, deviceAdapt);

            Map<String, Object> response = new HashMap<>();
            if (result != null) {
                response.put("list", result.getOrDefault("data", List.of()));
                response.put("total", result.getOrDefault("total", 0L));
                response.put("pageSize", pageSize);
                response.put("currentPage", page);
            } else {
                response.put("list", List.of());
                response.put("total", 0L);
                response.put("pageSize", pageSize);
                response.put("currentPage", page);
            }
            return response;
        } catch (HahaException e) {
            log.error("查询商品总库失败: {}", e.getMessage());
            throw new BusinessException(500, "查询商品总库失败: " + e.getMessage());
        }
    }

    @Override
    public boolean addToMerchant(String codeList) {
        try {
            return hahaClient.getGoodsApi().addToMerchant(codeList);
        } catch (HahaException e) {
            log.error("添加商品到商家商品库失败: {}", e.getMessage());
            throw new BusinessException(500, "添加到商家商品库失败: " + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> setProductShelfStatus(String deviceId, String goodsCode, String salesType, String callType) {
        try {
            Map<String, Object> result = hahaClient.getGoodsApi().setStatus(deviceId, goodsCode, salesType, callType);
            log.info("商品上下架操作成功 - deviceId: {}, goodsCode: {}, salesType: {}", deviceId, goodsCode, salesType);
            return result;
        } catch (HahaException e) {
            log.error("商品上下架操作失败: {}", e.getMessage());
            throw new BusinessException(500, "商品上下架操作失败: " + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getIdMapping(String codeList) {
        try {
            return hahaClient.getGoodsApi().getIdMapping(codeList);
        } catch (HahaException e) {
            log.error("查询商品ID对应关系失败: {}", e.getMessage());
            throw new BusinessException(500, "查询商品ID对应关系失败: " + e.getMessage());
        }
    }

    /**
     * 填充商品标签字段
     */
    private void fillProductLabels(Product product) {
        // 同步状态标签
        if (product.getSyncStatus() != null) {
            var statusLabel = EntityLabelUtils.getStatusLabel("sync", product.getSyncStatus());
            product.setSyncStatusLabel(statusLabel.getLabel());
            product.setSyncStatusColor(statusLabel.getColor());
        }

        // 图片 URL
        if (product.getImageUrl() == null && product.getPic() != null) {
            product.setImageUrl(product.getPic());
        }

        // 分类字段
        if (product.getCategory() == null) {
            product.setCategory(product.getType());
        }
        
        // 价格字段（转换为分）
        if (product.getPrice() == null && product.getRetailPrice() != null) {
            product.setPrice(product.getRetailPrice() * 100);
        }
        if (product.getCost() == null && product.getCostPrice() != null) {
            product.setCost(product.getCostPrice() * 100);
        }
        
        // 最后同步时间
        if (product.getLastSyncTime() == null && product.getSyncTime() != null) {
            product.setLastSyncTime(product.getSyncTime());
        }
    }
}
