# -*- encoding: utf-8 -*-
"""
@File    : EIoTClubObject.py
@Time    : 2023/7/18 10:49
@Author  : stephen
@Email   : zhangdongming@asj6.wecom.work
@Software: PyCharm
"""
import json
import random
import time

import requests

from Ansjer.config import DX_TECH_URL, DX_TECH_SECRET, LOGGER, DX_TECH_APP_KEY
from Object.UnicomObject import UnicomObjeect
from Object.WXTechObject import WXTechObject


class EIoTClubObject:

    def __init__(self):
        self.headers = {'content-type': 'application/json'}

    @staticmethod
    def get_system_params():
        """
        请求接口必传系统参数
        """
        nonce = ''.join(str(random.choice(range(1, 10))) for _ in range(5))
        return {
            'appkey': DX_TECH_APP_KEY,
            'nonce': int(nonce),
            'timestamp': int(time.time()),
        }

    @staticmethod
    def get_request_params(**params):
        """
        将业务参数与系统参数合并后进行加签得到请求参数体
        """
        iot_obj = WXTechObject()

        # 获取请求系统参数
        data = EIoTClubObject().get_system_params()
        # 系统参数与业务参数合并
        params = dict(data, **params)
        # 合并参数后进行升序加密得到sign
        sign = iot_obj.getSign(DX_TECH_SECRET, **params)
        params['sign'] = sign
        params = json.dumps(params)
        LOGGER.info('*****鼎芯API请求数据：{}'.format(params))
        return params

    def dx_service_api(self, url, **params):
        """
        @param url 请求地址
        @param 业务必填参数
        鼎芯业务API 统一封装加签请求
        """
        # 系统参数合并业务参数并加签得到请求参数
        rq_body = self.get_request_params(**params)
        response = requests.post(url, data=rq_body, headers=self.headers)
        assert response.status_code == 200
        return UnicomObjeect().get_text_dict(response)

    @staticmethod
    def get_cards_info(api_version, **params):
        """
        根据卡号，获取单卡信息及流量使用信息
        @param api_version: api版本号
        @param params: iccid、operator
        @return: 卡信息
        """
        url = DX_TECH_URL + f'/api/{api_version}/card/getCardsInfo'
        params['operator'] = 5  # 国际
        return EIoTClubObject().dx_service_api(url, **params)

    @staticmethod
    def query_order_package_list(api_version, **params):
        """
        查询iccid可订购套餐列表
        @param api_version: api版本号
        @param params: iccid、operator
        @return: 卡信息
        """
        url = DX_TECH_URL + f'/api/{api_version}/package/listOrderPackageByIccid'
        params['operator'] = 5  # 国际
        return EIoTClubObject().dx_service_api(url, **params)

    @staticmethod
    def query_order_record_list(api_version, **params):
        """
        查询iccid套餐订购记录
        @param api_version: api版本号
        @param params: iccid、operator
        @return: 卡信息
        """
        url = DX_TECH_URL + f'/api/{api_version}/package/packageOrderRecord'
        params['operator'] = 5  # 国际
        return EIoTClubObject().dx_service_api(url, **params)