# -*- coding: utf-8 -*-
import ast
import base64
import io
import json
import os
import random
import time

import re

from stl import mesh
from werkzeug import urls

import odoo
from odoo.exceptions import ValidationError
import requests
from odoo import http
from odoo.http import request, Response
from odoo.modules import get_resource_path
from odoo.tools.translate import _
import logging

_logger = logging.getLogger(__name__)


class WechatAuthController(http.Controller):

    @http.route('/wechat_auth/callback', auth='public', type='http', csrf=False)
    def wechat_auth_callback(self, **kwargs):
        _logger.info('wechat_auth_callback=============:%s' % kwargs)
        code = kwargs.get('code')
        if not code:
            return "缺少授权码 (code)"

        # 获取 access_token 和 UserId
        corp_id = 'wweaf7f1caab27a136'
        secret = 'UA95oJsgeS6cZrq_9ijaG68n0MIWFVv1nyxVnHnqiQQ'
        token_url = f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corp_id}&corpsecret={secret}'
        token_response = requests.get(token_url).json()
        access_token = token_response.get('access_token')

        user_info_url = f'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={access_token}&code={code}'
        user_info_response = requests.get(user_info_url).json()
        user_id = user_info_response.get('UserId')

        if not user_id:
            return "获取用户信息失败"

        # 根据 UserId 查询或创建 Odoo 用户
        user = request.env['res.users'].sudo().search([('wechat_user_id', '=', user_id)])

        if not user:
            # 获取企业微信用户详细信息
            user_detail_url = f'https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={access_token}&userid={user_id}'
            user_detail_response = requests.get(user_detail_url).json()

            # 创建 Odoo 用户
            user_data = {
                'login': user_detail_response.get('email'),
                'name': user_detail_response.get('name'),
                'email': user_detail_response.get('email'),
                'wechat_user_id': user_id,
            }
            user = request.env['res.users'].sudo().create(user_data)

        # 自动登录 Odoo 用户
        request.session.authenticate(request.session.db, user.login, user.password_crypt)
        return http.local_redirect('/web')
