package com.fs.live.controller;

import com.alibaba.fastjson.JSONObject;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.system.service.ISysConfigService;
import com.fs.wx.order.domain.FsWxExpressTask;
import com.fs.wx.order.service.IFsWxExpressTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 微信快递任务Controller
 *
 * @author fs
 * @date 2025-01-XX
 */
@RestController
@RequestMapping("/live/wxExpressTask")
public class FsWxExpressTaskController extends BaseController {

    @Autowired
    private IFsWxExpressTaskService fsWxExpressTaskService;

    @Autowired
    private ISysConfigService configService;

    /**
     * 查询微信快递任务列表
     */
    @PreAuthorize("@ss.hasPermi('live:wxExpressTask:list')")
    @GetMapping("/list")
    public TableDataInfo list(FsWxExpressTask fsWxExpressTask) {
        startPage();
        List<FsWxExpressTask> list = fsWxExpressTaskService.selectFsWxExpressTaskList(fsWxExpressTask);
        return getDataTable(list);
    }

    /**
     * 获取当前使用小程序的微信上传失败订单数量
     */
    @GetMapping("/getFailedCount")
    public AjaxResult getFailedCount() {
        try {
            // 获取his.store配置
            String configJson = configService.selectConfigByKey("his.config");
            if (configJson == null || configJson.isEmpty()) {
                return AjaxResult.success(0);
            }
            
            // 解析JSON获取appId
            JSONObject config = JSONObject.parseObject(configJson);
            String appId = config.getString("appid");
            
            if (appId == null || appId.isEmpty()) {
                return AjaxResult.success(0);
            }
            
            // 查询失败订单数量（status=3）
            int count = fsWxExpressTaskService.countFailedTasksByAppId(appId);
            return AjaxResult.success(count);
        } catch (Exception e) {
            return AjaxResult.error("查询失败订单数量失败：" + e.getMessage());
        }
    }
}