package com.ruoyi.web.controller.publicapi;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.RateLimiter;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.enums.LimitType;
import com.ruoyi.jarvis.domain.GoodsInfo;
import com.ruoyi.jarvis.domain.OrderRows;
import com.ruoyi.jarvis.domain.dto.PromoterOrderInfoVO;
import com.ruoyi.jarvis.enums.ValidCodeConverter;
import com.ruoyi.jarvis.service.IGoodsInfoService;
import com.ruoyi.jarvis.service.IOrderRowsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 京东开放接口（免登录，路径统一 /open/jd/）
 */
@Anonymous
@RestController
@RequestMapping("/open/jd")
public class PublicPromoterOrderController {

    private static final String DEFAULT_SHOP_LOGO = "https://www.jd.com/favicon.ico";
    private static final SimpleDateFormat DATE_FMT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private IOrderRowsService orderRowsService;

    @Autowired
    private IGoodsInfoService goodsInfoService;

    /**
     * 跟团订单查询（兼容 jiadiantemai 接口格式）
     */
    @GetMapping("/queryTkOrder")
    @RateLimiter(key = CacheConstants.RATE_LIMIT_KEY, time = 60, count = 30, limitType = LimitType.IP)
    public Map<String, Object> queryTkOrder(
            @RequestParam String orderId,
            @RequestParam(required = false) String t) {
        Map<String, Object> result = new HashMap<>();
        String trimmedOrderId = orderId != null ? orderId.trim() : "";
        if (trimmedOrderId.isEmpty()) {
            result.put("code", 200);
            result.put("count", 0);
            result.put("msg", "请输入订单编号");
            return result;
        }

        List<OrderRows> rows = orderRowsService.selectOrderRowsByOrderNo(trimmedOrderId);
        if (rows == null || rows.isEmpty()) {
            result.put("code", 200);
            result.put("count", 0);
            result.put("msg", "未查找到对应订单信息~");
            return result;
        }

        Set<Long> goodsInfoIds = new HashSet<>();
        for (OrderRows row : rows) {
            if (row.getGoodsInfoId() != null) {
                goodsInfoIds.add(row.getGoodsInfoId());
            }
        }
        Map<Long, GoodsInfo> goodsInfoMap = goodsInfoService.selectGoodsInfoMapByIds(goodsInfoIds);

        List<PromoterOrderInfoVO> orderInfoList = new ArrayList<>();
        ValidCodeConverter validCodeConverter = new ValidCodeConverter();
        for (OrderRows row : rows) {
            GoodsInfo goodsInfo = row.getGoodsInfoId() != null
                    ? goodsInfoMap.get(row.getGoodsInfoId()) : null;
            orderInfoList.add(toPromoterOrderInfo(row, goodsInfo, validCodeConverter));
        }

        if (orderInfoList.isEmpty()) {
            result.put("code", 200);
            result.put("count", 0);
            result.put("msg", "未查找到对应订单信息~");
            return result;
        }

        result.put("code", 200);
        result.put("orderInfoList", orderInfoList);
        result.put("msg", "查询成功");
        return result;
    }

    private PromoterOrderInfoVO toPromoterOrderInfo(OrderRows row, GoodsInfo goodsInfo,
                                                    ValidCodeConverter validCodeConverter) {
        PromoterOrderInfoVO vo = new PromoterOrderInfoVO();
        String shopName = goodsInfo != null && goodsInfo.getShopName() != null && !goodsInfo.getShopName().isEmpty()
                ? goodsInfo.getShopName() : "京东商城";
        vo.setShopName(shopName);
        vo.setShopLogo(DEFAULT_SHOP_LOGO);
        vo.setOrderSource("京东");
        vo.setTraceTypeStr(row.getTraceType() != null && row.getTraceType() == 2 ? "同店" : "跨店");
        if (row.getParentId() != null && row.getParentId() > 0) {
            vo.setParentId(String.valueOf(row.getParentId()));
        }
        if (row.getOrderId() != null) {
            vo.setOrderId(String.valueOf(row.getOrderId()));
        }
        vo.setValidCodeMsg(validCodeConverter.getCodeDescription(row.getValidCode()));
        if (goodsInfo != null && goodsInfo.getImageUrl() != null && !goodsInfo.getImageUrl().isEmpty()) {
            vo.setSkuImageUrl(goodsInfo.getImageUrl());
        } else if (row.getSkuId() != null) {
            vo.setSkuImageUrl("https://img14.360buyimg.com/n5/s450x450_" + row.getSkuId() + ".jpg");
        }
        vo.setSkuName(row.getSkuName());
        if (row.getSkuId() != null) {
            vo.setSkuId(String.valueOf(row.getSkuId()));
        }
        vo.setItemId(row.getItemId());
        vo.setSkuNum(row.getSkuNum() != null ? row.getSkuNum() : 1);
        vo.setCosPrice(formatPrice(row));
        vo.setOrderTime(formatDate(row.getOrderTime()));
        vo.setFinishTime(formatDate(row.getFinishTime()));
        Double proPrice = row.getProPriceAmount();
        if (proPrice != null && proPrice > 0) {
            vo.setProPriceAmount(String.format("%.2f", proPrice));
        } else {
            vo.setProPriceAmount("0.00");
        }
        return vo;
    }

    private String formatPrice(OrderRows row) {
        Double price = row.getActualCosPrice();
        if (price == null || price <= 0) {
            price = row.getEstimateCosPrice();
        }
        if (price == null) {
            return "0.00";
        }
        return String.format("%.2f", price);
    }

    private String formatDate(java.util.Date date) {
        if (date == null) {
            return "";
        }
        synchronized (DATE_FMT) {
            return DATE_FMT.format(date);
        }
    }
}
