package com.ruoyi.web.controller.erp;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.erp.domain.*;
import com.ruoyi.jarvis.service.IOuterIdGeneratorService;
import org.springframework.beans.factory.annotation.Autowired;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.erp.request.ERPAccount;
import com.ruoyi.erp.request.IERPAccount;
import com.ruoyi.jarvis.domain.ErpOpenConfig;
import com.ruoyi.jarvis.service.IErpOpenConfigService;
import com.ruoyi.jarvis.service.erp.ErpAccountResolver;
import com.ruoyi.erp.request.ProductCreateRequest;
import com.ruoyi.erp.request.ProductCategoryListQueryRequest;
import com.ruoyi.erp.request.ProductPropertyListQueryRequest;
import com.ruoyi.erp.request.AuthorizeListQueryRequest;
import com.ruoyi.erp.request.ProductPublishRequest;
import com.ruoyi.erp.request.ProductDownShelfRequest;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * ERP 商品接口
 * 基于“生成的文案与图片”快速创建商品
 */
@RestController
@RequestMapping("/erp/product")
@Validated
public class ProductController extends BaseController {

    @Autowired
    private IOuterIdGeneratorService outerIdGeneratorService;

    @Resource
    private ErpAccountResolver erpAccountResolver;

    @Resource
    private IErpOpenConfigService erpOpenConfigService;
    
    private static final Logger log = LoggerFactory.getLogger(ProductController.class);

    @PostMapping("/createByPromotion")
    public R<?> createByPromotion(@RequestBody @Validated CreateProductFromPromotionRequest req) {
        try {
            IERPAccount account = resolveAccount(req.getAppid());
            // 1) 组装 ERPShop
            ERPShop erpShop = new ERPShop();
            erpShop.setChannelCatid(req.getChannelCatId());
            erpShop.setItemBizType(req.getItemBizType());
            erpShop.setSpBizType(req.getSpBizType());
            erpShop.setPrice(req.getPrice());
            erpShop.setExpressFee(req.getExpressFee());
            erpShop.setStock(req.getStock());
            
            // 处理商家编码：如果为空则自动生成
            String outerId = req.getOuterId();
            if (StringUtils.isEmpty(outerId) && StringUtils.isNotEmpty(req.getSkuid())) {
                outerId = outerIdGeneratorService.generateOuterId(req.getSkuid());
                if (StringUtils.isNotEmpty(outerId)) {
                    log.info("自动生成商家编码: skuid={}, outerId={}", req.getSkuid(), outerId);
                }
            }
            erpShop.setOuterid(outerId);
            erpShop.setStuffStatus(req.getStuffStatus());

            // 发布店铺（必填）
            PublishShop shop = new PublishShop();
            shop.setUserName(req.getUserName());
            shop.setProvince(req.getProvince());
            shop.setCity(req.getCity());
            shop.setDistrict(req.getDistrict());
            shop.setTitle(req.getTitle());
            shop.setContent(req.getContent());
            shop.setImages(req.getImages());
            shop.setWhiteImages(req.getWhiteImages());
            shop.setServiceSupport(req.getServiceSupport());
            List<PublishShop> publishShops = new ArrayList<>();
            publishShops.add(shop);
            erpShop.setPublishShop(publishShops);

            // 属性（选填）
            if (req.getChannelPv() != null && !req.getChannelPv().isEmpty()) {
                List<Channelpv> pvList = new ArrayList<>();
                for (CreateProductFromPromotionRequest.ChannelPvDto pvDto : req.getChannelPv()) {
                    Channelpv pv = new Channelpv();
                    pv.setPropertyid(pvDto.getPropertyId());
                    pv.setPropertyName(pvDto.getPropertyName());
                    pv.setValueid(pvDto.getValueId());
                    pv.setValueName(pvDto.getValueName());
                    pvList.add(pv);
                }
                erpShop.setChannelpv(pvList);
            }

            // 多规格（选填）
            if (req.getSkuItems() != null && !req.getSkuItems().isEmpty()) {
                List<SkuItems> skuItems = new ArrayList<>();
                for (CreateProductFromPromotionRequest.SkuItemDto s : req.getSkuItems()) {
                    SkuItems si = new SkuItems();
                    si.setPrice(s.getPrice());
                    si.setStock(s.getStock());
                    si.setSkuText(s.getSkuText());
                    si.setOuterid(s.getOuterId());
                    skuItems.add(si);
                }
                erpShop.setSkuItems(skuItems);
            }

            // 2) 调用开放接口
            ProductCreateRequest createRequest = new ProductCreateRequest(account);
            JSONObject body = JSONObject.parseObject(JSON.toJSONString(erpShop));
            createRequest.setRequestBody(body);
            String resp = createRequest.getResponseBody();
            
            // 解析响应并添加生成的outerId
            JSONObject responseData = JSONObject.parseObject(resp);
            if (responseData != null && responseData.getInteger("code") == 0) {
                // 如果发品成功，在响应中添加生成的outerId
                if (StringUtils.isNotEmpty(outerId)) {
                    if (responseData.get("data") instanceof JSONObject) {
                        JSONObject data = responseData.getJSONObject("data");
                        data.put("outer_id", outerId);
                        data.put("outerId", outerId);
                    } else {
                        // 如果没有data字段，创建一个
                        JSONObject data = new JSONObject();
                        data.put("outer_id", outerId);
                        data.put("outerId", outerId);
                        responseData.put("data", data);
                    }
                }
            }
            
            return R.ok(responseData);
        } catch (Exception e) {
            return R.fail("创建失败: " + e.getMessage());
        }
    }

    /**
     * 上架商品
     */
    @PostMapping("/publish")
    public R<?> publish(@RequestBody @Validated PublishRequest req) {
        try {
            IERPAccount account = resolveAccount(req.getAppid());
            ProductPublishRequest publishRequest = new ProductPublishRequest(account);
            publishRequest.setProductId(req.getProductId());
            publishRequest.setUserName(req.getUserName());
            publishRequest.setSpecifyPublishTime(req.getSpecifyPublishTime());
            String resp = publishRequest.getResponseBody();
            com.alibaba.fastjson2.JSONObject jo = com.alibaba.fastjson2.JSONObject.parseObject(resp);
            return R.ok(jo);
        } catch (Exception e) {
            return R.fail("上架失败: " + e.getMessage());
        }
    }

    /**
     * 获取类目下拉
     */
    @GetMapping("/categories")
    public R<?> categories(@RequestParam int itemBizType,
                           @RequestParam(required = false) Integer spBizType,
                           @RequestParam(required = false) Integer flashSaleType,
                           @RequestParam(required = false) String appid) {
        try {
            ProductCategoryListQueryRequest req = new ProductCategoryListQueryRequest(resolveAccount(appid));
            req.setItemBizType(itemBizType);
            if (spBizType != null) req.setSpBizType(spBizType);
            if (flashSaleType != null) req.setFlashSaleType(flashSaleType);
            String resp = req.getResponseBody();

            JSONObject jo = JSONObject.parseObject(resp);
            // 兼容不同返回格式：{"code":0,"data":{"list":[...]}}
            List<JSONObject> rows = new java.util.ArrayList<>();
            Object dataObj = jo.get("data");
            if (dataObj instanceof com.alibaba.fastjson2.JSONArray) {
                rows.addAll(((com.alibaba.fastjson2.JSONArray) dataObj).toJavaList(JSONObject.class));
            } else if (dataObj instanceof JSONObject) {
                JSONObject dataJson = (JSONObject) dataObj;
                if (dataJson.get("list") instanceof com.alibaba.fastjson2.JSONArray) {
                    rows.addAll(dataJson.getJSONArray("list").toJavaList(JSONObject.class));
                } else if (dataJson.get("categories") instanceof com.alibaba.fastjson2.JSONArray) {
                    rows.addAll(dataJson.getJSONArray("categories").toJavaList(JSONObject.class));
                }
            } else if (jo.get("list") instanceof com.alibaba.fastjson2.JSONArray) {
                rows.addAll(jo.getJSONArray("list").toJavaList(JSONObject.class));
            } else if (jo.get("categories") instanceof com.alibaba.fastjson2.JSONArray) {
                rows.addAll(jo.getJSONArray("categories").toJavaList(JSONObject.class));
            }
            List<Option> options = new java.util.ArrayList<>();
            for (JSONObject row : rows) {
                String id = firstNonBlank(
                        row.getString("channel_cat_id"),
                        row.getString("cat_id"),
                        row.getString("id"),
                        row.getString("channelCatId")
                );
                String name = firstNonBlank(
                        row.getString("channel_cat_name"),
                        row.getString("name"),
                        row.getString("cat_name"),
                        row.getString("category_name"),
                        row.getString("title")
                );
                if (id != null && name != null) options.add(new Option(id, name));
            }
            return R.ok(options);
        } catch (Exception e) {
            return R.fail("获取类目失败: " + e.getMessage());
        }
    }

    /**
     * 获取商品属性（基于 itemBizType / spBizType / channelCatId）
     */
    @GetMapping("/pv")
    public R<?> properties(@RequestParam int itemBizType,
                           @RequestParam int spBizType,
                           @RequestParam String channelCatId,
                           @RequestParam(required = false) String subPropertyId,
                           @RequestParam(required = false) String appid) {
        try {
            System.out.println("获取商品属性");
            ProductPropertyListQueryRequest req = new ProductPropertyListQueryRequest(resolveAccount(appid));
            req.setItemBizType(itemBizType);
            req.setSpBizType(spBizType);
            req.setChannelCatId(channelCatId);
            if (subPropertyId != null && !subPropertyId.isEmpty()) req.setSubPropertyId(subPropertyId);
            String resp = req.getResponseBody();

            JSONObject jo = JSONObject.parseObject(resp);
            java.util.List<JSONObject> rows = new java.util.ArrayList<>();
            Object dataObj = jo.get("data");
            if (dataObj instanceof com.alibaba.fastjson2.JSONArray) {
                rows.addAll(((com.alibaba.fastjson2.JSONArray) dataObj).toJavaList(JSONObject.class));
            } else if (dataObj instanceof JSONObject) {
                JSONObject dataJson = (JSONObject) dataObj;
                if (dataJson.get("list") instanceof com.alibaba.fastjson2.JSONArray) {
                    rows.addAll(dataJson.getJSONArray("list").toJavaList(JSONObject.class));
                } else if (dataJson.get("pv_list") instanceof com.alibaba.fastjson2.JSONArray) {
                    rows.addAll(dataJson.getJSONArray("pv_list").toJavaList(JSONObject.class));
                }
            } else if (jo.get("list") instanceof com.alibaba.fastjson2.JSONArray) {
                rows.addAll(jo.getJSONArray("list").toJavaList(JSONObject.class));
            }

            // 规范化输出
            java.util.List<java.util.Map<String, Object>> props = new java.util.ArrayList<>();
            for (JSONObject row : rows) {
                if (row == null) continue;
                String pid = firstNonBlank(row.getString("property_id"), row.getString("propertyId"), row.getString("id"));
                String pname = firstNonBlank(row.getString("property_name"), row.getString("propertyName"), row.getString("name"));
                if (pid == null || pname == null) continue;
                java.util.List<java.util.Map<String, String>> values = new java.util.ArrayList<>();
                Object vs = row.get("values");
                if (vs instanceof com.alibaba.fastjson2.JSONArray) {
                    for (Object o : (com.alibaba.fastjson2.JSONArray) vs) {
                        if (o instanceof JSONObject) {
                            JSONObject v = (JSONObject) o;
                            String vid = firstNonBlank(v.getString("value_id"), v.getString("valueId"), v.getString("id"));
                            String vname = firstNonBlank(v.getString("value_name"), v.getString("valueName"), v.getString("name"));
                            if (vid != null && vname != null) {
                                java.util.Map<String, String> m = new java.util.HashMap<>();
                                m.put("valueId", vid);
                                m.put("valueName", vname);
                                values.add(m);
                            }
                        }
                    }
                } else if (row.get("value_list") instanceof com.alibaba.fastjson2.JSONArray) {
                    for (Object o : row.getJSONArray("value_list")) {
                        if (o instanceof JSONObject) {
                            JSONObject v = (JSONObject) o;
                            String vid = firstNonBlank(v.getString("value_id"), v.getString("valueId"), v.getString("id"));
                            String vname = firstNonBlank(v.getString("value_name"), v.getString("valueName"), v.getString("name"));
                            if (vid != null && vname != null) {
                                java.util.Map<String, String> m = new java.util.HashMap<>();
                                m.put("valueId", vid);
                                m.put("valueName", vname);
                                values.add(m);
                            }
                        }
                    }
                } else if (row.get("items") instanceof com.alibaba.fastjson2.JSONArray) { // 实际返回为 items
                    for (Object o : row.getJSONArray("items")) {
                        if (o instanceof JSONObject) {
                            JSONObject v = (JSONObject) o;
                            String vid = firstNonBlank(v.getString("value_id"), v.getString("valueId"), v.getString("id"));
                            String vname = firstNonBlank(v.getString("value_name"), v.getString("valueName"), v.getString("name"));
                            if (vid != null && vname != null) {
                                java.util.Map<String, String> m = new java.util.HashMap<>();
                                m.put("valueId", vid);
                                m.put("valueName", vname);
                                values.add(m);
                            }
                        }
                    }
                }
                java.util.Map<String, Object> p = new java.util.HashMap<>();
                p.put("propertyId", pid);
                p.put("propertyName", pname);
                // 透传是否必填（0/1），不同接口可能是 required 或 must
                Integer required = row.getInteger("required");
                if (required == null) required = row.getInteger("must");
                if (required != null) p.put("required", required);
                p.put("values", values);
                props.add(p);
            }
            return R.ok(props);
        } catch (Exception e) {
            return R.fail("获取属性失败: " + e.getMessage());
        }
    }

    private static String firstNonBlank(String... vals) {
        if (vals == null) return null;
        for (String v : vals) { if (v != null && v.trim().length() > 0) return v; }
        return null;
    }

    public static class Option {
        public final String value; public final String label;
        public Option(String value, String label) { this.value = value; this.label = label; }
    }

    /**
     * 获取授权的闲鱼会员名下拉
     */
    @GetMapping("/usernames")
    public R<?> usernames(@RequestParam(defaultValue = "1") int pageNum,
                          @RequestParam(defaultValue = "100") int pageSize,
                          @RequestParam(required = false) String appid) {
        try {
            AuthorizeListQueryRequest req = new AuthorizeListQueryRequest(resolveAccount(appid));
            req.setPagination(pageNum, pageSize);
            String resp = req.getResponseBody();
            System.out.println("获取授权的闲鱼会员名下拉: " + resp);
            JSONObject jo = JSONObject.parseObject(resp);
            java.util.List<Option> options = new java.util.ArrayList<>();
            java.util.function.Consumer<JSONObject> addRow = row -> {
                if (row == null) return;
                String name = firstNonBlank(row.getString("user_name"), row.getString("xy_name"), row.getString("username"), row.getString("nick"));
                if (name != null) {
                    String label = name;
                    List<ErpOpenConfig> cfgs = erpOpenConfigService.selectEnabledOrderBySort();
                    if (cfgs != null) {
                        for (ErpOpenConfig c : cfgs) {
                            if (name.equals(c.getXyUserName())) {
                                String r = c.getRemark() != null ? c.getRemark() : c.getAppKey();
                                label = name + "(" + r + ")";
                                break;
                            }
                        }
                    }
                    if (label.equals(name)) {
                        for (ERPAccount a : ERPAccount.values()) {
                            if (name.equals(a.getXyName())) {
                                label = name + "(" + a.getRemark() + ")";
                                break;
                            }
                        }
                    }
                    options.add(new Option(name, label));
                }
            };
            Object data = jo.get("data");
            if (data instanceof com.alibaba.fastjson2.JSONArray) {
                for (Object o : (com.alibaba.fastjson2.JSONArray) data) addRow.accept((JSONObject) o);
            } else if (data instanceof JSONObject) {
                JSONObject d = (JSONObject) data;
                if (d.get("list") instanceof com.alibaba.fastjson2.JSONArray) {
                    for (Object o : d.getJSONArray("list")) addRow.accept((JSONObject) o);
                } else if (d.get("users") instanceof com.alibaba.fastjson2.JSONArray) {
                    for (Object o : d.getJSONArray("users")) addRow.accept((JSONObject) o);
                }
            }
            return R.ok(options);
        } catch (Exception e) {
            return R.fail("获取会员名失败: " + e.getMessage());
        }
    }

    /**
     * 获取可用ERP账号（仅返回appid与会员名，隐藏密钥）
     */
    @GetMapping("/ERPAccount")
    public R<?> erpAccounts() {
        java.util.List<Option> list = new java.util.ArrayList<>();
        List<ErpOpenConfig> cfgs = erpOpenConfigService.selectEnabledOrderBySort();
        if (cfgs != null) {
            for (ErpOpenConfig c : cfgs) {
                String label = StringUtils.isNotEmpty(c.getRemark()) ? c.getRemark() : c.getXyUserName();
                if (StringUtils.isEmpty(label)) {
                    label = c.getAppKey();
                }
                list.add(new Option(c.getAppKey(), "【配置】" + label));
            }
        }
        for (ERPAccount a : ERPAccount.values()) {
            list.add(new Option(a.getApiKey(), "【内置】" + a.getRemark()));
        }
        return R.ok(list);
    }

    private IERPAccount resolveAccount(String appid) {
        return erpAccountResolver.resolve(appid);
    }

    /**
     * 用于承接前端“生成的文案与图片”并补足必填参数
     */
    public static class CreateProductFromPromotionRequest {
        // 必填-类目/类型/行业
        @NotBlank
        private String channelCatId;
        @NotNull
        private Integer itemBizType;
        @NotNull
        private Integer spBizType;

        // 必填-价格/邮费/库存
        @NotNull @Min(1)
        private Long price;
        @NotNull @Min(0)
        private Long expressFee;
        @NotNull @Min(1)
        private Integer stock;

        // 发布店铺信息（必填）
        @NotBlank
        private String userName;
        @NotNull
        private Integer province;
        @NotNull
        private Integer city;
        @NotNull
        private Integer district;

        // 文案与图片（必填）
        @NotBlank
        private String title;
        @NotBlank
        private String content;
        @NotNull
        @Size(min = 1)
        private List<String> images;

        // 选填
        private String whiteImages;
        private String serviceSupport; // 多个用逗号分隔
        private String outerId;
        private String skuid; // SKUID，用于自动生成商家编码
        private Integer stuffStatus;

        private List<SkuItemDto> skuItems;
        @com.fasterxml.jackson.annotation.JsonProperty("channel_pv")
        private List<ChannelPvDto> channelPv;

        // getters/setters
        public String getChannelCatId() { return channelCatId; }
        public void setChannelCatId(String channelCatId) { this.channelCatId = channelCatId; }
        public Integer getItemBizType() { return itemBizType; }
        public void setItemBizType(Integer itemBizType) { this.itemBizType = itemBizType; }
        public Integer getSpBizType() { return spBizType; }
        public void setSpBizType(Integer spBizType) { this.spBizType = spBizType; }
        public Long getPrice() { return price; }
        public void setPrice(Long price) { this.price = price; }
        public Long getExpressFee() { return expressFee; }
        public void setExpressFee(Long expressFee) { this.expressFee = expressFee; }
        public Integer getStock() { return stock; }
        public void setStock(Integer stock) { this.stock = stock; }
        public String getUserName() { return userName; }
        public void setUserName(String userName) { this.userName = userName; }
        public Integer getProvince() { return province; }
        public void setProvince(Integer province) { this.province = province; }
        public Integer getCity() { return city; }
        public void setCity(Integer city) { this.city = city; }
        public Integer getDistrict() { return district; }
        public void setDistrict(Integer district) { this.district = district; }
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
        public List<String> getImages() { return images; }
        public void setImages(List<String> images) { this.images = images; }
        public String getWhiteImages() { return whiteImages; }
        public void setWhiteImages(String whiteImages) { this.whiteImages = whiteImages; }
        public String getServiceSupport() { return serviceSupport; }
        public void setServiceSupport(String serviceSupport) { this.serviceSupport = serviceSupport; }
        public String getOuterId() { return outerId; }
        public void setOuterId(String outerId) { this.outerId = outerId; }
        public String getSkuid() { return skuid; }
        public void setSkuid(String skuid) { this.skuid = skuid; }
        public Integer getStuffStatus() { return stuffStatus; }
        public void setStuffStatus(Integer stuffStatus) { this.stuffStatus = stuffStatus; }
        public List<SkuItemDto> getSkuItems() { return skuItems; }
        public void setSkuItems(List<SkuItemDto> skuItems) { this.skuItems = skuItems; }
        public List<ChannelPvDto> getChannelPv() { return channelPv; }
        public void setChannelPv(List<ChannelPvDto> channelPv) { this.channelPv = channelPv; }

        public static class SkuItemDto {
            @NotNull @Min(0)
            private Long price;
            @NotNull @Min(0)
            private Integer stock;
            @NotBlank
            private String skuText;
            private String outerId;
            public Long getPrice() { return price; }
            public void setPrice(Long price) { this.price = price; }
            public Integer getStock() { return stock; }
            public void setStock(Integer stock) { this.stock = stock; }
            public String getSkuText() { return skuText; }
            public void setSkuText(String skuText) { this.skuText = skuText; }
            public String getOuterId() { return outerId; }
            public void setOuterId(String outerId) { this.outerId = outerId; }
        }

        public static class ChannelPvDto {
            @NotBlank
            @com.fasterxml.jackson.annotation.JsonProperty("property_id")
            private String propertyId;
            @NotBlank
            @com.fasterxml.jackson.annotation.JsonProperty("property_name")
            private String propertyName;
            @NotBlank
            @com.fasterxml.jackson.annotation.JsonProperty("value_id")
            private String valueId;
            @NotBlank
            @com.fasterxml.jackson.annotation.JsonProperty("value_name")
            private String valueName;
            public String getPropertyId() { return propertyId; }
            public void setPropertyId(String propertyId) { this.propertyId = propertyId; }
            public String getPropertyName() { return propertyName; }
            public void setPropertyName(String propertyName) { this.propertyName = propertyName; }
            public String getValueId() { return valueId; }
            public void setValueId(String valueId) { this.valueId = valueId; }
            public String getValueName() { return valueName; }
            public void setValueName(String valueName) { this.valueName = valueName; }
        }

        // 扩展：支持多账号，多店铺
        private String appid; // 选用的ERP应用（appid）
        public String getAppid() { return appid; }
        public void setAppid(String appid) { this.appid = appid; }
    }

    /**
     * 上架请求体
     */
    public static class PublishRequest {
        @NotNull
        private Long productId;
        @NotBlank
        private String userName;
        private String specifyPublishTime;
        private String appid;

        public Long getProductId() { return productId; }
        public void setProductId(Long productId) { this.productId = productId; }
        public String getUserName() { return userName; }
        public void setUserName(String userName) { this.userName = userName; }
        public String getSpecifyPublishTime() { return specifyPublishTime; }
        public void setSpecifyPublishTime(String specifyPublishTime) { this.specifyPublishTime = specifyPublishTime; }
        public String getAppid() { return appid; }
        public void setAppid(String appid) { this.appid = appid; }
    }

    /**
     * 下架商品（单个）
     */
    @PostMapping("/downShelf")
    public R<?> downShelf(@RequestBody @Validated DownShelfRequest req) {
        try {
            IERPAccount account = resolveAccount(req.getAppid());
            ProductDownShelfRequest downShelfRequest = new ProductDownShelfRequest(account);
            downShelfRequest.setProductId(req.getProductId());
            String resp = downShelfRequest.getResponseBody();
            JSONObject jo = JSONObject.parseObject(resp);
            return R.ok(jo);
        } catch (Exception e) {
            log.error("下架商品失败: productId={}", req.getProductId(), e);
            return R.fail("下架失败: " + e.getMessage());
        }
    }

    /**
     * 批量上架商品
     */
    @PostMapping("/batchPublish")
    public R<?> batchPublish(@RequestBody @Validated BatchPublishRequest req) {
        try {
            IERPAccount account = resolveAccount(req.getAppid());
            List<Long> productIds = req.getProductIds();
            
            if (productIds == null || productIds.isEmpty()) {
                return R.fail("商品ID列表不能为空");
            }
            
            if (req.getUserName() == null || req.getUserName().isEmpty()) {
                return R.fail("闲鱼会员名不能为空");
            }

            List<HashMap<String, Object>> results = new ArrayList<>();
            int successCount = 0;
            int failCount = 0;

            for (Long productId : productIds) {
                HashMap<String, Object> result = new HashMap<>();
                result.put("productId", productId);
                
                try {
                    ProductPublishRequest publishRequest = new ProductPublishRequest(account);
                    publishRequest.setProductId(productId);
                    publishRequest.setUserName(req.getUserName());
                    if (req.getSpecifyPublishTime() != null) {
                        publishRequest.setSpecifyPublishTime(req.getSpecifyPublishTime());
                    }
                    String resp = publishRequest.getResponseBody();
                    JSONObject jo = JSONObject.parseObject(resp);
                    
                    if (jo != null && jo.getInteger("code") != null && jo.getInteger("code") == 0) {
                        result.put("success", true);
                        result.put("msg", "上架成功");
                        result.put("response", jo);
                        successCount++;
                    } else {
                        result.put("success", false);
                        result.put("msg", jo != null ? jo.getString("msg") : "上架失败");
                        result.put("response", jo);
                        failCount++;
                    }
                } catch (Exception e) {
                    log.error("批量上架商品失败: productId={}", productId, e);
                    result.put("success", false);
                    result.put("msg", "上架异常: " + e.getMessage());
                    result.put("response", null);
                    failCount++;
                }
                
                results.add(result);
            }

            HashMap<String, Object> summary = new HashMap<>();
            summary.put("total", productIds.size());
            summary.put("success", successCount);
            summary.put("fail", failCount);
            summary.put("results", results);

            JSONObject response = new JSONObject();
            response.put("code", failCount == 0 ? 0 : 500);
            response.put("msg", failCount == 0 ? "全部上架成功" : String.format("成功: %d, 失败: %d", successCount, failCount));
            response.put("data", summary);

            return R.ok(response);
        } catch (Exception e) {
            log.error("批量上架商品异常", e);
            return R.fail("批量上架失败: " + e.getMessage());
        }
    }

    /**
     * 批量下架商品
     */
    @PostMapping("/batchDownShelf")
    public R<?> batchDownShelf(@RequestBody @Validated BatchDownShelfRequest req) {
        try {
            IERPAccount account = resolveAccount(req.getAppid());
            List<Long> productIds = req.getProductIds();
            
            if (productIds == null || productIds.isEmpty()) {
                return R.fail("商品ID列表不能为空");
            }

            List<HashMap<String, Object>> results = new ArrayList<>();
            int successCount = 0;
            int failCount = 0;

            for (Long productId : productIds) {
                HashMap<String, Object> result = new HashMap<>();
                result.put("productId", productId);
                
                try {
                    ProductDownShelfRequest downShelfRequest = new ProductDownShelfRequest(account);
                    downShelfRequest.setProductId(productId);
                    String resp = downShelfRequest.getResponseBody();
                    JSONObject jo = JSONObject.parseObject(resp);
                    
                    if (jo != null && jo.getInteger("code") != null && jo.getInteger("code") == 0) {
                        result.put("success", true);
                        result.put("msg", "下架成功");
                        result.put("response", jo);
                        successCount++;
                    } else {
                        result.put("success", false);
                        result.put("msg", jo != null ? jo.getString("msg") : "下架失败");
                        result.put("response", jo);
                        failCount++;
                    }
                } catch (Exception e) {
                    log.error("批量下架商品失败: productId={}", productId, e);
                    result.put("success", false);
                    result.put("msg", "下架异常: " + e.getMessage());
                    result.put("response", null);
                    failCount++;
                }
                
                results.add(result);
            }

            HashMap<String, Object> summary = new HashMap<>();
            summary.put("total", productIds.size());
            summary.put("success", successCount);
            summary.put("fail", failCount);
            summary.put("results", results);

            JSONObject response = new JSONObject();
            response.put("code", failCount == 0 ? 0 : 500);
            response.put("msg", failCount == 0 ? "全部下架成功" : String.format("成功: %d, 失败: %d", successCount, failCount));
            response.put("data", summary);

            return R.ok(response);
        } catch (Exception e) {
            log.error("批量下架商品异常", e);
            return R.fail("批量下架失败: " + e.getMessage());
        }
    }

    /**
     * 下架请求体
     */
    public static class DownShelfRequest {
        @NotNull
        private Long productId;
        private String appid;

        public Long getProductId() { return productId; }
        public void setProductId(Long productId) { this.productId = productId; }
        public String getAppid() { return appid; }
        public void setAppid(String appid) { this.appid = appid; }
    }

    /**
     * 批量上架请求体
     */
    public static class BatchPublishRequest {
        @NotNull
        @Size(min = 1, message = "商品ID列表不能为空")
        private List<Long> productIds;
        @NotBlank(message = "闲鱼会员名不能为空")
        private String userName;
        private String specifyPublishTime;
        private String appid;

        public List<Long> getProductIds() { return productIds; }
        public void setProductIds(List<Long> productIds) { this.productIds = productIds; }
        public String getUserName() { return userName; }
        public void setUserName(String userName) { this.userName = userName; }
        public String getSpecifyPublishTime() { return specifyPublishTime; }
        public void setSpecifyPublishTime(String specifyPublishTime) { this.specifyPublishTime = specifyPublishTime; }
        public String getAppid() { return appid; }
        public void setAppid(String appid) { this.appid = appid; }
    }

    /**
     * 批量下架请求体
     */
    public static class BatchDownShelfRequest {
        @NotNull
        @Size(min = 1, message = "商品ID列表不能为空")
        private List<Long> productIds;
        private String appid;

        public List<Long> getProductIds() { return productIds; }
        public void setProductIds(List<Long> productIds) { this.productIds = productIds; }
        public String getAppid() { return appid; }
        public void setAppid(String appid) { this.appid = appid; }
    }
}


