# -*- coding:utf-8 -*-
"""
Author: 陈江
Email: chenjiang@sparkedu.com
Create Date: 2022/09/23 2:06 下午
"""
from base_framework.public_business.common.UBRD.UBRD_public_business import BaseLogic
from base_framework.public_business.common.UBRD.kw.coursePackage_keyword import CoursePackageKW
from base_framework.public_tools import utils
from base_framework.public_tools.sqlhelper import MySqLHelper
from base_framework.public_tools.log import get_logger
from base_framework.public_business.common.UBRD.kw.user_keyword import UserKW
from base_framework.public_tools.mg_keyword import ManageKeyWord
from library.CommonFun.handle_tools import Handle_tools
import requests

obj_base_logic = BaseLogic()
obj_course_package_kw = CoursePackageKW()
obj_get_way = utils.Tools()
obj_mysql_helper = MySqLHelper()
log = get_logger()
obj_user_kw = UserKW()
obj_manage_kw = ManageKeyWord()
obj_handle_tools = Handle_tools()


class User:
    def __init__(self):
        pass

    def add_user_recharge(self, post_data_input):
        """
        | 功能说明： | 新增用户，充值课时 |
        | 输入参数： |
        |phone/userId| 用户手机号/用户id | 非必填，不传会默认随机注册一个账号；传的手机号不存在会自动进行注册；
        |coursePackageCode/courseId/coursePackageId/coursePackageName| 传一个即可 | 传了就给用充值课时，不传就不充
        |classHour |  | 充值课时 | 不传，需要充值时默认充值100
        |new_user_count |  | 生成新账号数量，存在这个参数时只会生成相应数量的账号 |
        | 作者信息： |  陈江     |  修改时间  | 2022-9-23 |
        """
        user_list = []
        try:
            post_data_input = eval(post_data_input)
        except:
            post_data_input = post_data_input

        if post_data_input.get('new_user_count'):
            new_user_count = post_data_input.pop('new_user_count')
            for count in range(0, int(new_user_count)):
                user_info = obj_base_logic.logic_public_add_user_recharge(post_data_input)
                user_list.append(user_info)
            return user_list
        return obj_base_logic.logic_public_add_user_recharge(post_data_input)

    def add_new_user(self, post_data_input):
        """
        | 功能说明： | 新增用户 |
        | 输入参数： |
        |fu_phone/fu_user_Id| 邀请人手机号或者user_id | 非必填,不传新增用户无邀请人；
        |new_phone| 新增用户手机号 | 传了用该手机号注册，不传则随机一个手机号
        |new_user_count |  | 生成新账号数量，存在这个参数时只会生成相应数量的账号 |
        | 作者信息： |  陈江     |  修改时间  | 2022-11-01 |
        """
        user_list = []
        try:
            post_data_input = eval(post_data_input)
        except:
            post_data_input = post_data_input

        # 构造增加用户请求参数
        add_user_params = {}
        # 判断是否需要进行邀请
        if post_data_input.get('fu_phone'):
            user_info = obj_user_kw.kw_ubrd_public_get_user_info_by_phone(phone=post_data_input.get('fu_phone'))
            add_user_params['fromUserId'] = user_info.get('user_id')
        elif post_data_input.get('fu_user_Id'):
            add_user_params['fromUserId'] = post_data_input.get('fu_user_Id')
        else:
            pass

        if post_data_input.get('new_phone'):
            user_info = obj_user_kw.kw_ubrd_public_get_user_info_by_phone(phone=post_data_input.get('new_phone'))
            if user_info:
                raise RuntimeWarning(f"该手机号{post_data_input.get('new_phone')}已经存在")
            add_user_params['phone'] = post_data_input.get('new_phone')
            obj_user_kw.kw_ubrd_public_add_user_profile(post_data_input=add_user_params)
            user_info = obj_user_kw.kw_ubrd_public_get_user_info_by_phone(phone=post_data_input.get('new_phone'))
            return user_info
        else:
            if post_data_input.get('new_user_count'):
                new_user_count = post_data_input.pop('new_user_count')
                for count in range(0, int(new_user_count)):
                    phone = obj_user_kw.kw_ubrd_public_get_unregistered_phone()
                    add_user_params['phone'] = phone
                    obj_user_kw.kw_ubrd_public_add_user_profile(post_data_input=add_user_params)
                    user_info = obj_user_kw.kw_ubrd_public_get_user_info_by_phone(phone=phone)
                    user_list.append(user_info)
                return user_list
            else:
                phone = obj_user_kw.kw_ubrd_public_get_unregistered_phone()
                add_user_params['phone'] = phone
                obj_user_kw.kw_ubrd_public_add_user_profile(post_data_input=add_user_params)
                user_info = obj_user_kw.kw_ubrd_public_get_user_info_by_phone(phone=phone)
                return user_info

    def add_new_haihua_user(self, post_data_input):
        """
        | 功能说明： | 生成海华标签新用户 |
        | 输入参数： |
        |fu_phone/fu_user_Id| 邀请人手机号或者user_id | 非必填,不传新增用户无邀请人；
        |new_phone| 新增用户手机号 | 传了用该手机号注册，不传则随机一个手机号
        |new_user_count |  | 生成新账号数量，存在这个参数时只会生成相应数量的账号 |
        | 作者信息： |  陈江     |  修改时间  | 2022-11-01 |
        """
        user_info_list = self.add_new_user(post_data_input)
        if user_info_list:
            for user_info in user_info_list:
                # 设置权益信息
                obj_mysql_helper.insert_one(
                    f"""INSERT INTO `operation`.`haibao_task_equity`(`user_id`, `order_id`, `order_business_side`, `course_package_id`, `course_package_name`, `equity_num`, `used_num`, `remain_num`, `lock_num`, `start_time`, `end_time`, `effect_period`, `generated_first_task`, `frozen_status`, `refund_status`, `equity_status`, `policy`, `subject_type`, `related_order_id`, `creator_id`, `creator_name`, `created_time`, `modifier_id`, `modifier_name`, `modified_time`) VALUES ({user_info.get('user_id')}, 8881050, 0, 23002, '逻辑思维直播系统课48课包', 20, 0, 20, 0, '2023-02-09 14:44:36', '2023-02-09 14:44:36', 360, 0, 0, 0, 0, 2, 0, 0, 0, '', '2023-02-01 00:00:01', 0, '', '2023-02-09 14:44:36');""")
                # 设置海华标签
                obj_mysql_helper.insert_one(
                    f"""INSERT INTO `utag_mass`.`user_tag`(`user_id`, `tag_id`, `tag_name`, `creator_id`, `creator_name`, `created_time`, `status`, `is_del`, `source_type`, `expiration_time`, `modifier_id`, `modifier_name`, `modified_time`) VALUES ({user_info.get('user_id')}, 51, '海外及港澳台用户', 587312, '陈江', '2023-02-09 16:08:24', 1, 0, 0, NULL, 587312, '陈江', '2023-02-09 16:08:24');""")
        return user_info_list

    def get_unregistered_user(self, post_data_input):
        """
        | 功能说明： | 获取未注册手机号 |
        | 输入参数： |
        |user_count |  | 返回未注册手机号数量 |
        | 作者信息： |  刘涛婷     |  修改时间  | 2022-11-10 |
        """
        user_list = []
        try:
            post_data_input = eval(post_data_input)
        except:
            post_data_input = post_data_input

        if post_data_input.get('user_count'):
            user_count = post_data_input.pop('user_count')
            for count in range(0, int(user_count)):
                user_phone = obj_user_kw.kw_ubrd_public_get_unregistered_phone()
                user_list.append(user_phone)
            return user_list
        return obj_user_kw.kw_ubrd_public_get_unregistered_phone()

    def get_sms_code_by_phone(self, post_data_input):
        """
        | 功能说明： | 发送验证码 |
        | 输入参数：
            | phone | 手机号｜ 必填
            | countryCode | 国家码 | 默认 86
            | authType | 验证码类型 | 默认2
            | verifyAppId | 验证appId | 默认2
        | 作者信息： | 陈江     | 2022/10/21 |
        """
        # 发送验证码
        obj_base_logic.logic_public_send_auth_code(post_data_input)
        # 获取验证码内容
        # 根据phone获取phone_code
        phone_server_ip = obj_get_way.get_container_ip_from_eureka('PHONE-SERVER', need_jira_id='qa',
                                                                   eureka_url='http://eureka.qa.huohua.cn')
        if post_data_input.get('countryCode'):
            phone = f"{post_data_input.get('countryCode')}-{post_data_input.get('phone')}"
        else:
            phone = post_data_input.get('phone')

        if phone_server_ip.get('container_ip'):
            url = 'http://{}:8080/encrypt/regdata?biztype=phone&uid=123456&sourceData={}'.format(
                phone_server_ip.get('container_ip'), phone)
            response = requests.post(url=url)  # 三个参数
            response_json = response.json()
        else:
            raise "获取phone server ip失败"

        if response_json.get('data'):
            msg = obj_mysql_helper.select_all(
                'SELECT msg FROM `push_service`.`sms` WHERE `phone_code` = \'{}\' ORDER BY id DESC LIMIT 1 '.format(
                    response_json.get('data')))
            if msg:
                web_hook = "https://open.feishu.cn/open-apis/bot/v2/hook/c9baf09d-55f1-46a6-8d67-9d4ff30b1be2"
                message_data = {"msg_type": "post", "content": {
                    "post": {"zh_cn": {"title": "message",
                                       "content": [[{"tag": "text", "text": msg[0].get('msg')}]]}}}}
                obj_handle_tools.send_message_by_feishu(web_hook, message_data)
            else:
                raise f"{phone}获取验证码失败"
            return msg[0].get('msg')

        else:
            return response_json

    def register_user(self, post_data_input):
        """
            | 功能说明： | 通过注册接口进行注册用户并设置密码A123456(支持邀请码，渠道) |
            | 输入参数： |
            |          |         |   channelId | string | 渠道id |
            |          |         |   invitePhone | string | 手机号 | "12030690001/86-13400114600"
            |          |         |   registerPhone | string | 手机号 | "12030690001/86-13400114600"
            | 作者信息： |  陈江     |  修改时间  | 2022-11-10 |
        """
        return obj_base_logic.logic_public_register_user(post_data_input)


if __name__ == '__main__':
    ff = {'phone': '13400234500','coursePackageId':29497}
    # User().add_user_recharge(ff)
    User().add_new_user(post_data_input={"new_user_count":"2"})
