# -*- coding:utf-8 -*-

"""
Author: 罗志鹏
Email: luozhipeng@huohua.cn
Create Date: 2022/03/03 11:25 下午
"""
from base_framework.public_tools import log
from base_framework.public_tools.sqlhelper import MySqLHelper
from library.UBRD_interface import UBRDInterface
from base_framework.public_tools.edu_user_helper import EDUUserHelper
from base_framework.public_tools.redis_api import RedisApi
from base_framework.public_tools.read_config import ReadConfig
from base_framework.base_config.current_pth import env_choose_path
from redis import Redis
from base_framework.public_tools.runner import Runner
from base_framework.public_tools.utils import Tools
from base_framework.public_business.common.UBRD.UBRD_public_business import BaseLogic
from base_framework.public_business.common.UBRD.kw.user_keyword import UserKW
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
import base64
obj_runner = Runner()
obj_log = log.get_logger()
obj_my_sql_helper = MySqLHelper()
obj_edu_user_helper = EDUUserHelper()
obj_redis_api = RedisApi()
obj_tools = Tools()
obj_base_logic = BaseLogic()
user_kw_obj = UserKW()


class UserCommon(UBRDInterface):

    def __init__(self):
        super().__init__()
        self.evn_cfg = ReadConfig(env_choose_path)
        self.current_business = self.evn_cfg.get_value(sections="run_evn_name", options="current_business")

    @staticmethod
    def update_user_pwd_by_phone(phone):
        """
            功能：初始化用户密码为A123456
            | 输入参数: | phone      string | 手机号  |
            | 作者：   | lzp          | 2022.03.07 |
        """
        sql_user_by_phone = "SELECT x.id FROM ucenter.user_profile x WHERE x.phone IN ('{0}')".format(phone)
        user_by_phone = obj_my_sql_helper.select_all(sql_user_by_phone)

        if isinstance(user_by_phone, tuple):
            raise RuntimeError("未找到手机号为{0}的用户".format(phone))
        sql_update_pwd = "update ucenter.user_profile set auth_hash = '2ad5381b6a2952287a95b9accb0bb51c'," \
                         "auth_salt='fFRzeLZGR5' WHERE phone IN ('{0}')".format(phone)
        obj_my_sql_helper.update(sql_update_pwd)
        obj_log.info('成功更新{0}用户密码为A123456'.format(phone))

    def update_teacher_pwd_by_classroom(self, classroom_Code):
        """
            功能：初始化教师账号密码为Huohua123456
            | 输入参数: | classroom_Code      string | 课堂code  |
            | 作者：   | lzp          | 2022.03.07 |
        """
        teacher_info = self.get_teacher_info_by_classroom(classroom_Code)
        sql_update_pwd = "update account.account set pwd = 'e1NTSEF9dzE4ZlFhRytVNzZWeFVKMFFIV2VUNy83U2hxOE5oNUhMT0doTnc9PQ==' WHERE id ={0}".format(
            teacher_info["account_id"])
        obj_my_sql_helper.update(sql_update_pwd)
        obj_log.info('成功更新{0}课堂教师{1}密码为Mima@123'.format(classroom_Code, teacher_info["phone"]))

    def update_teacher_pwd_by_classroom_2(self,classroom_Code):
        """
            功能：初始化教师账号密码为MIma@123456
            | 输入参数: | classroom_Code      string | 课堂code  |
            | 作者：   | lrq          | 2024.06.12 |
        """
        teacher_info = self.get_teacher_info_by_classroom(classroom_Code)
        sql_update_pwd = "update account.account set pwd = 'e1NTSEF9dzE4ZlFhRytVNzZWeFVKMFFIV2VUNy83U2hxOE5oNUhMT0doTnc9PQ==' WHERE id ={0}".format(teacher_info["account_id"])
        obj_my_sql_helper.update(sql_update_pwd)
        obj_log.info('成功更新{0}课堂教师{1}密码为MIma@123456'.format(classroom_Code,teacher_info["phone"]))

    def update_teacher_pwd_by_teacher_id(self, teacher_id):
        """
            功能：初始化教师账号密码为Huohua123456
            | 输入参数: | classroom_Code      string | 课堂code  |
            | 作者：   | lzp          | 2022.03.07 |
        """
        teacher_info = self.get_teacher_info_by_teacher_id(teacher_id)
        sql_update_pwd = "update account.account set pwd = 'e1NTSEF9dzE4ZlFhRytVNzZWeFVKMFFIV2VUNy83U2hxOE5oNUhMT0doTnc9PQ==' WHERE id ={0}".format(
            teacher_info["account_id"])
        obj_my_sql_helper.update(sql_update_pwd)
        obj_log.info('成功更新{0}教师{1}密码为Mima@123'.format(teacher_id, teacher_info["phone"]))

    def get_chess_classroom_by_mcr_code(self, mcr_code):
        """
            功能：获取课堂教师信息 仅支持emp教师
            | 输入参数: | teacher_id      int | 老师id  |
            | 作者：   | lzp          | 2022.03.07 |
        """
        sql_chess_classroom = "SELECT x.relation_classroom_code FROM learning_plan.classroom_relation x WHERE x.classroom_code IN ('{0}') and status =1 and relation_type = 1".format(
            mcr_code)
        chess_classroom = obj_my_sql_helper.select_all(sql_chess_classroom)
        return chess_classroom

    def get_teacher_info_by_teacher_id(self, teacher_id):
        """
            功能：获取课堂教师信息 仅支持emp教师
            | 输入参数: | teacher_id      int | 老师id  |
            | 作者：   | lzp          | 2022.03.07 |
        """
        sql_phone_by_classroom_code = "select tp.id,e.phone,tp.account_id from  emp.employee e inner join teach_teacher.teacher_profile tp on tp.employee_id = e.id  inner join account.account a on a.id= tp.account_id where tp.id = {0}".format(
            teacher_id)
        teacher_info = obj_my_sql_helper.select_all(sql_phone_by_classroom_code)
        return teacher_info[0]

    def get_teacher_info_by_classroom(self, classroom_Code):
        """
            功能：获取课堂教师信息 仅支持emp教师
            | 输入参数: | classroom_Code      string | 课堂code  |
            | 作者：   | lzp          | 2022.03.07 |
        """
        sql_phone_by_classroom_code = "select  c.teacher_id,e.phone,tp.account_id from  emp.employee e inner join teach_teacher.teacher_profile tp on tp.employee_id = e.id inner join teach_classes.classroom c on c.teacher_id = tp.id inner join account.account a on a.id= tp.account_id where c.code = '{0}'".format(
            classroom_Code)
        teacher_info = obj_my_sql_helper.select_all(sql_phone_by_classroom_code)
        return teacher_info[0]

    def get_student_info_by_phone(self, phone):
        """
            功能：根据手机号码获取学生基本信息
            | 输入参数: | phone      string | 手机号  |
        """
        user_info = user_kw_obj.kw_ubrd_public_get_user_info_by_phone(phone)
        sql = "SELECT id studentId FROM ucenter.student_profile where user_id ='{}'".format(user_info["user_id"])
        return obj_my_sql_helper.select_one(sql)

    def get_classroom_info_by_code(self, code):
        """
            功能：根据课堂号获取课堂信息
            | 输入参数: | phone      string | 手机号  |
        """
        sql = "SELECT id,code,classes_id,classes_code,course_id,course_name,lesson_id,lesson_name,teacher_id,open_time,close_time,is_closed,status FROM teach_classes.classroom where code = '{0}'".format(
            code)
        return obj_my_sql_helper.select_one(sql)

    def register_by_code_phone(self, phone, countryCode=86):
        auth_code_send_result = obj_base_logic.logic_public_send_auth_code(
            {'h': {'accept-language': 'en'}, 'phone': phone, 'countryCode': '{}'.format(countryCode), 'authType': 2,
             'verifyAppId': 2})
        obj_log.info(auth_code_send_result)
        sms_code = obj_edu_user_helper.get_sms_code_by_phone(phone)
        obj_log.info(sms_code)
        login_post_result = self.kw_in_ubrd_login_post(
            **{'phone': phone, 'countryCode': '86', 'password': 'A123456', 'authCode': sms_code})
        obj_log.info(login_post_result)
        # 更新密码
        obj_my_sql_helper.update(
            "update ucenter.user_profile set auth_hash = 'e2a0c8ec7503d1bfea587d5ffa0efc2f',auth_salt='fTvsqofig7' WHERE phone='{}'".format(
                phone))

    def get_change_pwd_vcode_by_sms_code(self, phone):
        """ 获取学生端修改密码验证码 """
        sms_code = obj_edu_user_helper.get_sms_code_by_phone(phone)
        return sms_code

    def get_register_vccode_by_redis(self, phone):
        """
        获取学生端注册验证码
        """
        key = "api:AUTH_CODE:{0}_SIGN_IN".format(phone)
        obj_log.info(key)
        return self.get_student_key_value_by_redis(key, 9)

    def delete_change_student_pwd_limit_redis(self, phone):
        """
        功能：删除学生端修改密码次数限制缓存
            | 作者：   | lzp          | 2021.08. 15 |
        """
        key_1 = "GRANULARITY:PHONE_AUTH_RECEIVE_COUNT_CHANNEL_MOBILE_API{0}".format(phone)
        key_2 = "GRANULARITY:PHONE_AUTH_RECEIVE_COUNT_CHANNEL_MOBILE_API{0}_1".format(phone)
        self.delete_student_key_redis(key_1, 9)
        self.delete_student_key_redis(key_2, 9)

    def delete_student_key_redis(self, key: object, db: object):
        """
        删除指定key
        """
        if self.current_business == "hh":
            host = 'redis.qa.huohua.cn'
            password = 'AcUVeRb8lN'
            port = 6379
        elif self.current_business == "hhi":
            host = 'redis.qa.visparklearning.com'
            password = 'hxTjlWBYdK6UpAGF'
            port = 6379
        else:
            raise RuntimeError("读取本地配置环境失败，未能正常连接redis")
        pool = Redis(host=host, port=port, password=password, db=db)
        pool.delete(key)

    def get_student_key_value_by_redis(self, key, db):
        """
        获取指定key的value
        """
        if self.current_business == "hh":
            host = 'redis.qa.huohua.cn'
            password = 'AcUVeRb8lN'
            port = 6379
        elif self.current_business == "hhi":
            host = 'redis.qa.visparklearning.com'
            password = 'hxTjlWBYdK6UpAGF'
            port = 6379
        else:
            raise RuntimeError("读取本地配置环境失败，未能正常连接redis")
        pool = Redis(host=host, port=port, password=password, db=db, decode_responses=True)
        value = pool.get(key)
        return value

    def check_data_in_list(self, array: list, item):
        """
        判断某个数据是否在数组中
        """
        if item in array:
            return True
        else:
            return False

    def update_classroom_data_to_join(self, classroom_id):
        """
        更新学习服务课堂数据
        """
        open_time_timestamp = obj_tools.get_format_date(r_type=12)
        close_time_timestamp = obj_tools.get_format_date(r_type=12, add_hours=1)

        open_time_standard_time = obj_tools.get_format_date(r_type=4)
        close_time_standard_time = obj_tools.get_format_date(r_type=4, add_hours=1)
        # 更新学员课表数据
        sql_learning_schedule = "update learning_plan.learning_schedule set open_time ='{0}',close_time = '{1}' " \
                                "where classroom_id  = {2}".format(open_time_standard_time, close_time_standard_time,
                                                                   classroom_id)
        obj_my_sql_helper.update(sql_learning_schedule)

        # 更新教师课表数据
        sql_teaching_schedule = "update learning_plan.teaching_schedule set open_time ='{0}',close_time = '{1}', class_status =0 " \
                                "where classroom_id  = {2}".format(open_time_timestamp, close_time_timestamp,
                                                                   classroom_id)
        obj_my_sql_helper.update(sql_teaching_schedule)

    def check_data_in_db(self, sql, retry_count):
        """
        判断某个数据是否在数据库中
        """
        obj_my_sql_helper.check_result_exist(sql, retry_count=retry_count)

    def encryption_aes(self,data,key=None):
        if not key:
            key = b"y3wa93twda35eqer"
        cipher = AES.new(key, AES.MODE_ECB)
        padded_data = pad(data.encode(), AES.block_size)  # PKCS5Padding
        encrypted_data = cipher.encrypt(padded_data)
        return base64.b64encode(encrypted_data).decode()





if __name__ == '__main__':
    user_common_obj = UserCommon()
    a = 138475
    s=user_common_obj.update_teacher_pwd_by_teacher_id(teacher_id=183152 )
    print(s)
    # print(user_common_obj.get_user_info_by_phone('13458500234'))
    # phone_dict ={'phone': '65-98760021'}
    # user_common_obj.get_register_vccode_by_redis('65-98760021')
    # user_common_obj.update_classroom_data_to_join(classroom_id=500852944)
