# encoding: utf-8
"""
@project: djangoModel->Auth
@author: 孙楷炎
@Email: sky4834@163.com
@synopsis: 小程序SDK
@created_time: 2022/7/7 9:38
"""
import json
import sys
from logging import getLogger
from pathlib import Path

from django.forms import model_to_dict
import requests
from django.contrib.auth.hashers import make_password

from main.settings import BASE_DIR
if 'xj_role' in sys.modules:
    from xj_role.services.user_group_service import UserGroupService
from xj_user.services.login_service import LoginService
from xj_user.services.wechat_service import WechatService
from ..models import BaseInfo, Auth
from ..services.user_detail_info_service import DetailInfoService
from ..services.user_relate_service import UserRelateToUserService
from ..utils.custom_tool import get_short_id
from ..utils.j_config import JConfig
from ..utils.j_dict import JDict
from ..utils.nickname_generate import gen_one_word_digit
from ..utils.j_ulid_field import JULIDField

module_root = str(Path(__file__).resolve().parent)
# 配置之对象
main_config_dict = JDict(JConfig.get_section(path=str(BASE_DIR) + "/config.ini", section="xj_user"))
module_config_dict = JDict(JConfig.get_section(path=str(BASE_DIR) + "/config.ini", section="xj_user"))

payment_main_config_dict = JDict(JConfig.get_section(path=str(BASE_DIR) + "/config.ini", section="xj_payment"))
payment_module_config_dict = JDict(JConfig.get_section(path=str(BASE_DIR) + "/config.ini", section="xj_payment"))

sub_appid = payment_main_config_dict.wechat_merchant_app_id or payment_module_config_dict.wechat_merchant_app_id or ""

sub_app_secret = payment_main_config_dict.wechat_merchant_app_secret or payment_module_config_dict.wechat_merchant_app_secret or ""

app_id = main_config_dict.app_id or module_config_dict.app_id or ""
app_secret = main_config_dict.secret or module_config_dict.secret or ""
jwt_secret_key = main_config_dict.jwt_secret_key or module_config_dict.jwt_secret_key or ""
expire_day = main_config_dict.expire_day or module_config_dict.expire_day or ""
expire_second = main_config_dict.expire_second or module_config_dict.expire_second or ""

logger = getLogger('log')

# 用户短信服务
class UserSmsService:

    # 手机短信登录
    def phone_login(self, phone,  platform_id=None, other_params=None, nonexistent_alert=False):
        """
        :param phone:
        :param platform_id:
        :param other_params:
        :param nonexistent_alert: 如果用户不存在则报警，默认False
        :return:
        """
        if other_params is None:
            other_params = {}
        # 根据手机号获取用户
        current_user = BaseInfo.objects.filter(phone=phone).first()
        # print(">>>用户信息 current_user ", current_user)

        # if not sso_serve_id:
        #     return None, "单点登录不能为空"

        if not platform_id:
            return None, "平台不能为空"
        # 如果用户不存在且要求报警
        if not current_user and nonexistent_alert:
            return None, "平台用户不存在"

        # 如果用户未注册 用手机号进行注册
        if not current_user:
            base_info = {
                'uuid': JULIDField.get_u12(),
                'username': get_short_id(8),
                'nickname': gen_one_word_digit(),
                'phone': phone,
                'email': '',
            }

            BaseInfo.objects.create(**base_info)

            # 注册完成后 重新获取用户信息
            user_info_set = BaseInfo.objects.filter(phone=phone).first()
            user_info = model_to_dict(user_info_set)
            # platforms_to_users解包
            user_info['platforms_to_users'] = [model_to_dict(platforms) for platforms in
                                               user_info['platforms_to_users']]
            # 检验单点登录信息
            # sso_set, sso_err = LoginService.sso_verify(sso_serve_id, user_info.get('id', None), sub_appid)
            # if sso_err:
            #     return None, sso_err

            password = str(other_params.get("password", "123456"))
            # 生成登录token
            token = LoginService.make_token(user_info.get("id"), user_info.get('uuid', None), phone, platform_id)
            # 创建用户登录信息，绑定token
            auth_set, auth_err = LoginService.bind_token(user_info.get('id', None), token, password=password)
            if auth_err:
                return None, auth_err
            return {'token': "Bearer " + auth_set.token, 'user_info': user_info}, None
        # 如果用户已经存在
        else:
            # 存在当前用户，直接进行授权
            user_info = model_to_dict(current_user)
            # platforms_to_users解包
            user_info['platforms_to_users'] = [model_to_dict(platforms) for platforms in  user_info['platforms_to_users'] ]

            # 检验单点登录信息
            # sso_set, sso_err = LoginService.sso_verify(sso_serve_id, user_info.get('id', None), sub_appid)
            # if sso_err:
            #     return None, sso_err

            # 创建用户登录信息，绑定token
            token = LoginService.make_token(user_info.get("id"), user_info.get('uuid', None), user_info.get('phone', None), platform_id)
            # 修改用户登录信息，绑定token
            auth_set, auth_err = LoginService.bind_token(user_id=user_info.get('id', None), token=token,
                                                         is_create=False)
            if auth_err:
                return None, auth_err


        return {'token': "Bearer " + auth_set.token, 'user_info': user_info}, None
