# -*- coding:utf-8 -*-
"""
Author: qiaoxinjiu
Email: qiaoxinjiu@sparkedu.com
Create Date: 2022/05/08 5:58 下午
"""
import os
from urllib import parse

from base_framework.public_tools import read_config
import requests
import sys
import json


class auth_login():
    def __init__(self):
        self.config_login_path = os.path.dirname(os.path.abspath(__file__))
        self.config_login_filePath = os.path.join(self.config_login_path, "../Config/team_config.ini")
        self.config_login_content = read_config.ReadConfig(filename=self.config_login_filePath)

    def get_json_result(self, url, request_data=None, headers=None, send_way="GET"):
        """
        # url: 测试的url
        # request_data: url请求时发送的数据
        # headers: url请求时发送的消息头
        # 功能：获取json格式的数据
        """
        if send_way == "GET":
            response = requests.request(send_way, url, headers=headers, params=json.dumps(request_data))
        else:
            response = requests.request(send_way, url, headers=headers, data=json.dumps(request_data))
        try:
            response_data = json.loads(response.text)
        except:
            info = sys.exc_info()
            response_data = info[1], info[2]
        return response_data

    def get_m_online_token(self):
        '''
        获取家长端线上登录的token
        :param username:
        :param password:
        :return:
        '''
        headers = {
            "Content-Type": "application/json;charset=UTF-8",
            "sso-client-id": "gmp"
        }
        get_login_info = eval(
            self.config_login_content.get_value(sections="m-userinfo", options="login_parent_info"))  # 获取配置文件中的默认请求参数值
        get_url_info = eval(self.config_login_content.get_value(sections="m-userinfo", options="parent_url"))
        m_token = requests.post(url=get_url_info.get("login_url"), json=get_login_info, verify=False, headers=headers)
        if m_token.status_code == 200:
            token = m_token.json()
            token = token['data']['token']
            return token
        else:
            raise KeyError('获取 parent token失败！')

    def get_student_online_token(self):
        '''
        获取学生端线上登录的token
        :param username:
        :param password:
        :return:
        '''
        headers = {
            "Content-Type": "application/json;charset=UTF-8",
            "sso-client-id": "gmp"
        }
        get_login_info = eval(
            self.config_login_content.get_value(sections="m-userinfo", options="login_student_info"))  # 获取配置文件中的默认请求参数值
        get_url_info = eval(self.config_login_content.get_value(sections="m-userinfo", options="student_url"))
        m_token = requests.post(url=get_url_info.get("login_url"), json=get_login_info, verify=False, headers=headers)
        if m_token.status_code == 200:
            token = m_token.json()
            token = token['data']['token']
            return token
        else:
            raise KeyError('获取 parent token失败！')

    def get_m_headers(self, m_token):
        '''
        获取请求的header
        :return:
        '''
        headers = {
            "Content-Type": "application/json;charset=UTF-8",
            "sso-client-id": "gmp",
            "user-token": m_token,
        }
        return headers

    def get_parent_config_info(self, url_name):
        '''
        获取家长端配置文件中的url信息
        :return:
        '''
        get_parent_url_info = eval(self.config_login_content.get_value(sections="m-userinfo", options="parent_url"))
        get_realm_name = eval(self.config_login_content.get_value(sections="m-userinfo", options="realm_name"))
        get_url = get_realm_name.get("parent_api") + get_parent_url_info.get(url_name)
        return get_url

    def get_visaprk_parent_config_info(self, url_name):
        '''
        获取海外家长端配置文件中的url信息
        :return:
        '''
        get_parent_url_info = eval(self.config_login_content.get_value(sections="m-userinfo", options="parent_course_url"))
        get_realm_name = eval(self.config_login_content.get_value(sections="m-userinfo", options="realm_name"))
        get_url = get_realm_name.get("parent_vispark_api") + get_parent_url_info.get(url_name)
        return get_url

    def get_student_config_info(self, url_name):
        '''
        获取学生端配置文件中的url信息
        :return:
        '''
        get_student_url_info = eval(self.config_login_content.get_value(sections="m-userinfo", options="student_url"))
        get_realm_name = eval(self.config_login_content.get_value(sections="m-userinfo", options="realm_name"))
        get_url = get_realm_name.get("student_api") + get_student_url_info.get(url_name)
        return get_url


class m_parent():
    def __init__(self):
        self.get_url = auth_login()

    def get_parentPayEditionPage(self):
        '''
        首页轮播页面展示
        :return:
        '''

        m_token = self.get_url.get_m_online_token()
        headers = self.get_url.get_m_headers(m_token=m_token)
        url = self.get_url.get_parent_config_info(url_name="parentPayEditionPage_url")
        get_response_data = self.get_url.get_json_result(url=url, headers=headers, request_data={"terminalType": 5})
        return get_response_data

    def get_recommendedCourse(self):
        '''
        家长端获取课程信息
        :return:
        '''
        m_token = self.get_url.get_m_online_token()
        headers = self.get_url.get_m_headers(m_token=m_token)
        url = self.get_url.get_parent_config_info(url_name="recommendedCourse_url")
        get_response_data = self.get_url.get_json_result(url=url, headers=headers)
        return get_response_data

    def get_trial_level(self,courseSubtype):
        '''
        获取试听课级别
        ap为21，cp为20
        :return:
        '''
        m_token = self.get_url.get_m_online_token()
        headers = self.get_url.get_m_headers(m_token=m_token)
        url = self.get_url.get_visaprk_parent_config_info(url_name="get_trial_url")
        request_url = url +"?courseSubtype={0}&subjectType=1".format(courseSubtype)
        get_response_data = self.get_url.get_json_result(url=request_url, headers=headers)
        # 针对ap或者cp获取级别，查看是否存在重复的level
        list_level = []
        for trial_data in get_response_data.get("data"):
            list_level.append(trial_data.get("level"))
        set_level = set(list_level)
        dict_response = {}
        for level in set_level:
            if list_level.count(level) > 1:
                dict_response[level] = list_level.count(level)
        if dict_response:
            return {"code":500,"data":dict_response}
        else:
            return {"code":200,"data":dict_response}

class student_verity():
    def __init__(self):
        self.get_url = auth_login()

    def get_schedule_count(self):
        '''

        :return:
        '''
        m_token = self.get_url.get_m_online_token()
        headers = self.get_url.get_m_headers(m_token=m_token)
        url = self.get_url.get_student_config_info(url_name="scheduleCount_url")
        print(url)
        get_response_data = self.get_url.get_json_result(url=url, headers=headers, request_data={"subjectType": 4})

        return get_response_data


if __name__ == '__main__':
    test = auth_login()
    test1 = m_parent()
    test2 = student_verity()
    # print(test.get_student_online_token())
    # print(test1.get_recommendedCourse())
    print(test1.get_trial_level(courseSubtype=22))
    # print(test2.get_schedule_count())
