import hashlib
import time
from urllib.parse import urlencode

from . import http
import requests


class BsPhp:
    def __init__(self, url: str, mutual_key: str, server_PrivateKey: str ='', client_PublicKey: str =''):
        self.url = url
        self.mutual_key = mutual_key
        self.server_PrivateKey = server_PrivateKey
        self.client_PublicKey = client_PublicKey
        self.bs_php_se_ssl = ''
        self.code_url = ''
        
    def _send_data(self, api: str, attach_param: dict = None):
        """
        发送数据
        :param api:
        :return:
        """
        appsafecode = hashlib.md5(
            time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()).encode()
        ).hexdigest()
        param = {
            "api": api,
            "BSphpSeSsL": self.bs_php_se_ssl,
            "date": time.strftime("%Y-%m-%d#%H:%M:%S", time.localtime(time.time())),
            "md5": "",
            "mutualkey": self.mutual_key,
            "appsafecode": appsafecode
        }
        if attach_param is not None:
            param.update(attach_param)
        data_str = urlencode(param)
        data = http.send_data(
            self.url, data_str,
            self.client_PublicKey, self.server_PrivateKey
        )


        print("data:" , data)
        if not isinstance(data, dict):
            # 网络异常或响应解密失败时，http.send_data 可能返回空字符串
            return ''

        print("data['appsafecode']:" + str(data.get('appsafecode', '')))
        print("appsafecode:" + appsafecode)

        if data.get('appsafecode') != appsafecode:
            data['data'] = "appsafecode 安全参数验证不通过，自己写保护代码"
        return data

    def connect(self) -> bool:
       
        """网络连接验证"""
        result = self._send_data('internet.in')
        print(result)
        return isinstance(result, dict) and result.get('data') == '1'

    def get_se_ssl(self) -> bool:
        """取BSphpSeSsL"""
        result = self._send_data('BSphpSeSsL.in')
        if result == '' or result['data'] == '':
            return False
        self.bs_php_se_ssl = result['data']
        return True

    def code_is_open(self, types: str):
        """
        获取验证码是否开启
        :param types: 获取类型:登录验证码=INGES_LOGIN,用户注册验证码=INGES_RE,找回密码验证码=INGES_MACK,用户留言验证码=INGES_SAY
        :return: 成功返回开启列表 失败返回false
        """
        result = self._send_data('getsetimag.in', {"type": types})
        if result != '':
            return result['data'].split('|')
        return False

    def get_version(self):
        """获取版本"""
        result = self._send_data('v.in')
        if result != '':
            return result['data']
        return False

    def get_url(self):
        """获取地址"""
        result = self._send_data('url.in')
        if result != '':
            return result['data']
        return ''

    def get_notice(self):
        """获取公告"""
        result = self._send_data('gg.in')
        if result != '':
            return result['data']
        return "公告获取失败"

    def get_code(self):
        """获取验证码"""
        result = requests.get(self.code_url + self.bs_php_se_ssl)
        return result.content

    def login(self, user: str, password: str, coode: str, key: str = '', maxoror: str = '') -> str:
        """
        账号登录
        :param user: 用户名
        :param password: 密码
        :param coode: 验证码
        :param key: 机器码
        :param maxoror: 标记_机器码
        :return:
        """
        param = {
            "user": user,
            "pwd": password,
            "key": key,
            "coode": coode,
            "maxoror": maxoror
        }
        result = self._send_data('login.lg', param)
        print('登录', result)
        if result == "":
            return "系统错误，登录失败！"
        if result['code'] != 1011:
            return result['data']
        self.bs_php_se_ssl = result['SeSsL']
        return result['data'].split('|')

    def reg(self, user: str, pwd: str, pwdb: str, coode: str, mobile: str, mibao_wenti: str, mibao_daan: str,
            qq: str = '', mail: str = '', key: str = '', extension: str = ''):
        """
        注册
        :param user: 注册账号
        :param pwd: 密码
        :param pwdb: 再次密码
        :param qq: QQ 可空
        :param mail: 邮箱 可空
        :param key: 绑定特征 可空
        :param coode: 验证码
        :param mobile: 手机号码
        :param mibao_wenti: 密保问题
        :param mibao_daan: 密保答案
        :param extension: 邀请人 是否强制 后台设置
        :return:
        """
        param = {
            "user": user,
            "pwd": pwd,
            "pwdb": pwdb,
            "qq": qq,
            "mail": mail,
            "key": key,
            "coode": coode,
            "mobile": mobile,
            "mibao_wenti": mibao_wenti,
            "mibao_daan": mibao_daan,
            "extension": extension
        }
        result = self._send_data('registration.lg', param)
        if result == "":
            return "系统错误，注册失败！"
        return result['data']

    def unbind(self, user: str, password: str) -> str:
        """
        解绑
        :param user: 账号
        :param password: 密码
        :return:
        """
        param = {
            "user": user,
            "pwd": password
        }
        result = self._send_data('jiekey.lg', param)
        if result == "":
            return "系统错误，解绑失败！"
        return result['data']

    def pay(self, user: str, userpwd: str, userset: bool, card: str, pwd: str):
        """
        充值
        :param user: 账号
        :param userpwd: 用户密码
        :param userset: 是否验证密码
        :param card: 卡号
        :param pwd: 卡号密码
        :return:
        """
        param = {
            'user': user,
            'userpwd': userpwd,
            'userset': '1' if userset else '0',
            'ka': card,
            'pwd': pwd
        }
        result = self._send_data('chong.lg', param)
        if result == '':
            return '系统错误，解绑失败！'
        return result['data']

    def back_pass(self, user: str, pwd: str, pwdb: str, wenti: str, daan: str, coode: str = ''):
        """
        找回密码
        :param user: 账号
        :param pwd: 密码
        :param pwdb: 再次输入
        :param wenti: 问题
        :param daan: 答案
        :param coode: 验证码
        :return:
        """
        param = {
            'user': user,
            'pwd': pwd,
            'pwdb': pwdb,
            'wenti': wenti,
            'daan': daan,
            'coode': coode
        }
        result = self._send_data('backto.lg', param)
        if result == '':
            return '系统错误，找回密码失败！'
        return result['data']

    def edit_pass(self, user: str, pwd: str, pwda: str, pwdb: str, img: str):
        """
        修改密码
        :param user: 账号
        :param pwd: 密码
        :param pwda: 新密码
        :param pwdb: 再次输入新密码
        :param img:验证码
        :return:
        """
        param = {
            'user': user,
            'pwd': pwd,
            'pwda': pwda,
            'pwdb': pwdb,
            'img': img
        }
        result = self._send_data('password.lg', param)
        if result == '':
            return '系统错误，修改密码失败！'
        return result['data']

    def feedback(self, user: str, pwd: str, table: str, qq: str, leix: str, text: str, coode: str):
        """
        意见反馈
        :param user: 账号
        :param pwd: 密码
        :param table: 标题
        :param qq: 联系qq
        :param leix: 类型
        :param text: 内容
        :param coode: 验证码
        :return:
        """
        param = {
            'user': user,
            'pwd': pwd,
            'table': table,
            'qq': qq,
            'leix': leix,
            'text': text,
            'coode': coode
        }
        result = self._send_data('liuyan.in', param)
        if result == '':
            return '系统错误，意见反馈失败！'
        return result['data']

    def get_server_time(self):
        """
        获取服务器系统时间
        :return:
        """
        param = {'date': time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())}
        result = self._send_data('date.in', param)
        if result == '':
            return '系统错误，取系统时间失败！'
        return result['data']

    def get_version(self):
        """获取软件版本"""
        result = self._send_data('v.in')
        if result == '':
            return '系统错误，取系统时间失败！'
        return result['data']

    def get_bind(self):
        """取用户绑定特征"""
        result = self._send_data('userkey.lg')
        if result == '':
            return '系统错误，取绑定特征失败！'
        return result['data']

    def get_end_time(self):
        """取用户到期时间"""
        result = self._send_data('vipdate.lg')
        if result == '':
            return '系统错误，取到期时间失败！'
        return result['data']

    def get_soft_info(self):
        """取软件描述介绍"""
        result = self._send_data('miao.in')
        if result == '':
            return '系统错误，获取软件介绍失败！'
        return result['data']

    def get_verify(self, key: str = ''):
        """
        获取验证数据
        :param key: 绑定特征
        :return:
        """
        param = {'key': key}
        result = self._send_data('lgkey.lg', param)
        if result == '':
            return '系统错误，取验证数据失败！'
        return result['data']

    def get_userinfo(self, info: str = ''):
        """
        获取用户信息
        :param info: 信息字段
        :return:
        """
        param = {'info': info}
        result = self._send_data('getuserinfo.lg', param)
        if result == '':
            return '系统错误，取用户信息失败！'
        return result['data']

    def get_login_status(self):
        """取软件描述介绍"""
        result = self._send_data('lginfo.lg')
        if result == '':
            return '系统错误，获取软件介绍失败！'
        return result['data']
from bsphp.main import BsPhp