package com.ruoyi.web.controller.jarvis;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.jarvis.domain.ErpProduct;
import com.ruoyi.jarvis.domain.ErpProductExportRow;
import com.ruoyi.jarvis.service.IErpProductService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 闲鱼商品Controller
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/jarvis/erpProduct")
public class ErpProductController extends BaseController
{
    @Autowired
    private IErpProductService erpProductService;

    /**
     * 查询闲鱼商品列表
     */
    @PreAuthorize("@ss.hasPermi('jarvis:erpProduct:list')")
    @GetMapping("/list")
    public TableDataInfo list(ErpProduct erpProduct)
    {
        startPage();
        List<ErpProduct> list = erpProductService.selectErpProductList(erpProduct);
        return getDataTable(list);
    }

    /**
     * 导出闲鱼商品列表
     */
    @PreAuthorize("@ss.hasPermi('jarvis:erpProduct:export')")
    @Log(title = "闲鱼商品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ErpProduct erpProduct)
    {
        List<ErpProduct> list = erpProductService.selectErpProductList(erpProduct);
        String batchAt = DateUtils.getTime();
        List<ErpProductExportRow> rows = ErpProductExportRow.fromList(list, batchAt);
        ExcelUtil<ErpProductExportRow> util = new ExcelUtil<ErpProductExportRow>(ErpProductExportRow.class);
        util.exportExcel(response, rows, "闲鱼商品_AI明细");
    }

    /**
     * 获取闲鱼商品详细信息
     */
    @PreAuthorize("@ss.hasPermi('jarvis:erpProduct:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(erpProductService.selectErpProductById(id));
    }

    /**
     * 新增闲鱼商品
     */
    @PreAuthorize("@ss.hasPermi('jarvis:erpProduct:add')")
    @Log(title = "闲鱼商品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ErpProduct erpProduct)
    {
        return toAjax(erpProductService.insertErpProduct(erpProduct));
    }

    /**
     * 修改闲鱼商品
     */
    @PreAuthorize("@ss.hasPermi('jarvis:erpProduct:edit')")
    @Log(title = "闲鱼商品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ErpProduct erpProduct)
    {
        return toAjax(erpProductService.updateErpProduct(erpProduct));
    }

    /**
     * 删除闲鱼商品
     */
    @PreAuthorize("@ss.hasPermi('jarvis:erpProduct:remove')")
    @Log(title = "闲鱼商品", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(erpProductService.deleteErpProductByIds(ids));
    }

    /**
     * 从闲鱼ERP拉取商品列表并保存（单页，保留用于兼容）
     */
    @PreAuthorize("@ss.hasPermi('jarvis:erpProduct:pull')")
    @Log(title = "拉取闲鱼商品", businessType = BusinessType.INSERT)
    @PostMapping("/pull")
    public AjaxResult pullProductList(
            @RequestParam(required = false) String appid,
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "50") Integer pageSize,
            @RequestParam(required = false) Integer productStatus)
    {
        try {
            int count = erpProductService.pullAndSaveProductList(appid, pageNo, pageSize, productStatus);
            if (count > 0) {
                return success("成功拉取并保存 " + count + " 个商品");
            } else {
                String statusText = getStatusText(productStatus);
                String message = "拉取完成，但没有获取到商品数据";
                if (productStatus != null) {
                    message += "（筛选条件：状态=" + statusText + "）";
                }
                message += "。建议：使用全量同步功能自动遍历所有页码";
                return success(message);
            }
        } catch (Exception e) {
            return error("拉取商品列表失败: " + e.getMessage());
        }
    }

    /**
     * 全量同步商品（自动遍历所有页码，同步更新和删除）
     */
    @PreAuthorize("@ss.hasPermi('jarvis:erpProduct:pull')")
    @Log(title = "全量同步闲鱼商品", businessType = BusinessType.UPDATE)
    @PostMapping("/syncAll")
    public AjaxResult syncAllProducts(
            @RequestParam(required = false) String appid,
            @RequestParam(required = false) Integer productStatus)
    {
        try {
            IErpProductService.SyncResult result = erpProductService.syncAllProducts(appid, productStatus);
            return success(result.getMessage());
        } catch (Exception e) {
            return error("全量同步失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取状态文本（用于提示信息）
     */
    private String getStatusText(Integer status) {
        if (status == null) {
            return "全部";
        }
        switch (status) {
            case -1:
                return "删除";
            case 21:
                return "待发布";
            case 22:
                return "销售中";
            case 23:
                return "已售罄";
            case 31:
                return "手动下架";
            case 33:
                return "售出下架";
            case 36:
                return "自动下架";
            default:
                return String.valueOf(status);
        }
    }

    /**
     * 批量上架商品
     */
    @PreAuthorize("@ss.hasPermi('jarvis:erpProduct:publish')")
    @Log(title = "批量上架商品", businessType = BusinessType.UPDATE)
    @PostMapping("/batchPublish")
    public AjaxResult batchPublish(@RequestBody BatchOperationRequest request)
    {
        try {
            return success("批量上架功能请调用 /erp/product/batchPublish 接口");
        } catch (Exception e) {
            return error("批量上架失败: " + e.getMessage());
        }
    }

    /**
     * 批量下架商品
     */
    @PreAuthorize("@ss.hasPermi('jarvis:erpProduct:downShelf')")
    @Log(title = "批量下架商品", businessType = BusinessType.UPDATE)
    @PostMapping("/batchDownShelf")
    public AjaxResult batchDownShelf(@RequestBody BatchOperationRequest request)
    {
        try {
            return success("批量下架功能请调用 /erp/product/batchDownShelf 接口");
        } catch (Exception e) {
            return error("批量下架失败: " + e.getMessage());
        }
    }

    /**
     * 批量操作请求体
     */
    public static class BatchOperationRequest {
        private java.util.List<Long> productIds;
        private String appid;

        public java.util.List<Long> getProductIds() {
            return productIds;
        }

        public void setProductIds(java.util.List<Long> productIds) {
            this.productIds = productIds;
        }

        public String getAppid() {
            return appid;
        }

        public void setAppid(String appid) {
            this.appid = appid;
        }
    }
}

