import { Provide, Inject } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import axios from 'axios';
import { BaseSysParamService } from '../../base/service/sys/param';

@Provide()
export class Ys7Service extends BaseService {
    @Inject()
    baseSysParamService: BaseSysParamService;

    /**
     * 获取萤石云 AccessToken
     * 内部自动读系统参数，不走缓存建议上层包一层 Redis
     */
    async getAccessToken(): Promise<{
        accessToken: string;
        expireTime: number;
    }> {
        // 从 Cool-Admin 系统参数表读取
        const appKey = await this.baseSysParamService.dataByKey('ys7.appKey');
        const appSecret = await this.baseSysParamService.dataByKey('ys7.appSecret');

        if (!appKey || !appSecret) {
            throw new Error('萤石云 appKey/appSecret 未配置，请在系统参数中维护 ys7.appKey / ys7.appSecret');
        }

        try {
            const res = await axios.post(
                'https://open.ys7.com/api/lapp/token/get',
                new URLSearchParams({
                    appKey,
                    appSecret,
                }),
                {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    timeout: 8000,
                }
            );

            const { code, msg, data } = res.data;

            if (String(code) !== '200') {
                throw new Error(`萤石云获取 Token 失败：${msg}（code: ${code}）`);
            }

            return {
                accessToken: data.accessToken,
                expireTime: data.expireTime,
            };
        } catch (err) {
            throw err;
        }
    }
}