# -*- coding: utf-8 -*-
import base64
from odoo.http import Controller, request, route
from werkzeug.utils import redirect
import odoo
from odoo import http
from odoo.http import request
# from odoo.http import request, redis_ref
from odoo.addons.web.controllers.main import Home
from core.middleware.utils import change_image_with_time_pass
import datetime
import simplejson
import math
import random
import string
import pytz
import json

DEFAULT_IMAGE = '/jd_theme/static/src/img/material-background.png'


def random_num(n):  # 产生随机数字
    return random.sample(string.digits, n)


class DashboardBackground(Controller):
    @route(['/dashboard'], type='http', auth='user', website=False)
    def dashboard(self, **post):
        user = request.env.user
        company = user.company_id
        if company.dashboard_background:
            image = base64.b64decode(company.dashboard_background)
        else:
            # values = change_image_with_time_pass(request.env['ir.config_parameter'], request.params.copy())
            # return redirect(values['background_src'])
            # 更换大屏页背景图
            return redirect(DEFAULT_IMAGE)

        return request.make_response(
            image, [('Content-Type', 'image')])


# ----------------------------------------------------------
# Odoo Web web Controllers
# ----------------------------------------------------------
class Home(Home):
    @http.route('/web/login', type='http', auth="none")
    def web_login(self, redirect=None, **kw):
        request.params = change_image_with_time_pass(request.env['ir.config_parameter'], request.params.copy())
        return super(Home, self).web_login(redirect, **kw)

    # @http.route('/web/forgot/password', type='http', auth="public")
    # def forgot_password(self, redirect=None, **kw):
    #     odoo.addons.web.controllers.main.ensure_db()
    #     values = change_image_with_time_pass(request.env['ir.config_parameter'], request.params.copy())
    #     values['random_number'] = str(int(math.ceil(random.random() * 100000)))
    #     values['disable_reset_password'] = True
    #     values['disable_database_manager'] = True
    #     if request.httprequest.method == 'POST':
    #         request_user = request.params['login']
    #         user_obj = request.env['res.users'].sudo().search([('login', '=', request_user)])
    #         if request.params.get('verifyCode', None) and request.params.get('newPassword', None):
    #             # 验证验证码是否有效且正确
    #             validation_code_cli = request.params['verifyCode']
    #             tel = request.params['tel']
    #             vals = json.loads(redis_ref.get('send_msg_' + request_user))
    #             time_now = datetime.datetime.now(pytz.timezone('Asia/Shanghai')).strftime("%Y-%m-%d %H:%M:%S")
    #             if vals['expire_time'] >= time_now:
    #                 validation_code = vals['validation_code']
    #             else:
    #                 validation_code = None
    #             if validation_code:
    #                 if validation_code_cli == validation_code:
    #                     # 验证码有效
    #                     if request.params['newPassword'] == request.params['confirmPassword']:
    #                         # 两次新密码正确
    #                         if len(user_obj) == 1:
    #                             try:
    #                                 user_obj._set_password(request.params['newPassword'])
    #                                 uid = request.session.authenticate(request.session.db, request_user,
    #                                                                    request.params['newPassword'])
    #                                 if not redirect:
    #                                     if uid is not False:
    #                                         redirect = '/web'
    #                                     else:
    #                                         redirect = '/web/login'
    #                                 vals['validation_code'] = None
    #                                 redis_ref.set('send_msg_' + request_user, json.dumps(vals))
    #                                 return http.redirect_with_hash(redirect)
    #                             except Exception:
    #                                 values['error'] = u"密码修改失败！服务器错误！"
    #                     else:
    #                         values['error'] = u'两次密码输入不一致！'
    #                 else:
    #                     values['error'] = u'验证码错误！'
    #             else:
    #                 values['error'] = u'验证码已失效！请重新获取。'
    #         # 拿到电话号码
    #         if len(user_obj) > 0 and not values.get('tel', None):
    #             if user_obj.mobile:
    #                 if len(user_obj.mobile) != 11:
    #                     values['error'] = u"你的手机号码配置有误，请联系管理员。"
    #                 else:
    #                     values['tel'] = user_obj.mobile
    #             else:
    #                 values['error'] = u"该账号没有配置手机号码，无法找回密码。"
    #         else:
    #             if not values.get('tel', None):
    #                 values['error'] = u"你输入的账号不存在。"
    #     return request.render('jd_theme.forgot_password', values)
    #
    # @http.route('/web/sent/message', type='http', auth="none", csrf=False)
    # def sent_message(self, redirect=None, **kw):
    #     result = {'code': 1}
    #     # 生成验证码
    #     validation_code = ''.join(random_num(6))
    #     tel = int(filter(str.isdigit, request.params['tel'].encode("utf-8")))
    #     login = request.params['login']
    #     # redis_key
    #     key = 'send_msg_' + login
    #     # redis_value
    #     vals = json.loads(redis_ref.get(key)) if redis_ref.get(key) else None
    #     # 短信发送时间
    #     send_time = datetime.datetime.now(pytz.timezone('Asia/Shanghai'))
    #     # 短信过期时间
    #     expire_time = send_time + datetime.timedelta(minutes=5)
    #     # 发送次数，一天限制五次，超过五次则发送失败
    #     if vals:
    #         send_time_last = datetime.datetime.strptime(vals['send_time'], "%Y-%m-%d %H:%M:%S")
    #         if send_time.day > send_time_last.day:
    #             send_times_last = 0
    #         else:
    #             send_times_last = vals['send_times']
    #     else:
    #         send_times_last = 0
    #     if send_times_last < 5:
    #         msg = u"【玉龙科技】您的验证码为%s,(五分钟内有效),为了保证您的账户安全，请勿向任何人提供此验证码。" % validation_code
    #         request.env['jd.notify.channel'].sudo().notify(channel_code='md_async', receiver=[tel],
    #                                                     body=msg)
    #         redis_ref.set(key, json.dumps({
    #             'tel': tel,
    #             'validation_code': validation_code,
    #             'expire_time': expire_time.strftime("%Y-%m-%d %H:%M:%S"),
    #             'send_time': send_time.strftime("%Y-%m-%d %H:%M:%S"),
    #             'send_times': send_times_last + 1
    #         }))
    #         result['send_times'] = send_times_last + 1
    #     else:
    #         result['send_times'] = 5
    #     return http.Response(simplejson.dumps(result), status=200)
