package com.ruoyi.front.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.annotation.InnerAuth;
import com.ruoyi.logistics.config.SFExpressConfig;
import com.ruoyi.logistics.constant.SysConfigConstants;
import com.ruoyi.logistics.service.IMonthQRCodeTaskService;
import com.ruoyi.logistics.service.LogisticsOrderService;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * WX-月结二维码生成
 *
 * @author lydgt
 * @date 2026-02-04
 */
@RestController
@RequestMapping("/front/qrcode")
public class MonthQRCodeController extends BaseController {

    @Autowired
    private LogisticsOrderService logisticsOrderService;

    @Autowired
    private IMonthQRCodeTaskService monthQRCodeService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SFExpressConfig sfExpressConfig;

    /**
     * 获取月结二维码
     * @return
     */
    @RequestMapping
    public AjaxResult qrcode(@RequestParam("source") Integer source, @RequestParam("type") Integer type) {
        try{
            JSONObject jsonObject = logisticsOrderService.getQRCode(source, type);
            // 返回完整的二维码信息，包括图片数据
            return AjaxResult.success(jsonObject);
        } catch (ServiceException e) {
            return AjaxResult.error("获取二维码失败！ 原因:"+e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @InnerAuth
    @PostMapping("/consume")
    public R<String> consume() {
        try {
            monthQRCodeService.consumeQRCode();
            return R.ok();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取月结卡号
     * @return
     */
    @GetMapping("/getMonthCard")
    public AjaxResult getMonthCard(@RequestParam("source") Integer source, @RequestParam("type") Integer type) {
        if (source == 1) {
            if (type == 1) {
                return success(configService.selectConfigByKey(SysConfigConstants.JD_LOGISTICS_CUSTOMERCODE));
            } else if (type == 2) {
                return success(configService.selectConfigByKey(SysConfigConstants.JD_LOGISTICS_BUSINESSUNITCODE));
            }
        }
        return success(sfExpressConfig.getMonthlyCord());
    }
}
