# -*- coding: utf-8 -*-
"""
@Author: HuangJingCan
@Date: 2020-05-24 17:26:33
@LastEditTime: 2020-08-26 10:21:04
@LastEditors: HuangJingCan
@Description: App相关
"""
from seven_cloudapp.handlers.seven_base import *
from seven_cloudapp.handlers.top_base import *

from seven_cloudapp.models.db_models.app.app_info_model import *
from seven_cloudapp.models.db_models.base.base_info_model import *
from seven_cloudapp.models.db_models.login.login_log_model import *
from seven_cloudapp.models.enum import *


class BaseInfoHandler(SevenBaseHandler):
    """
    @description: 基础信息处理
    """
    def post_async(self):
        """
        @description: 基础信息处理入库
        @param {type} 
        @return: 
        @last_editors: HuangJingCan
        """
        customer_service = self.get_param("customer_service")
        experience_img = self.get_param("experience_img")
        client_ver = self.get_param("client_ver")
        server_ver = self.get_param("server_ver")
        update_function = self.get_param("update_function")
        store_study_url = self.get_param("store_study_url")
        study_url = self.get_param("study_url")
        video_url = self.get_param("video_url")
        course_url = self.get_param("course_url")
        price_gare = self.get_param("price_gare")
        product_price = self.get_param("product_price")
        decoration_poster = self.get_param("decoration_poster")
        friend_link = self.get_param("friend_link")

        # 数据入库
        base_info_model = BaseInfoModel()
        base_info = base_info_model.get_entity_by_id(1)

        is_add = False
        if not base_info:
            is_add = True
            base_info = BaseInfo()

        base_info.customer_service = customer_service
        base_info.experience_img = experience_img
        base_info.client_ver = client_ver
        base_info.server_ver = server_ver
        base_info.update_function = update_function
        base_info.store_study_url = store_study_url
        base_info.study_url = study_url
        base_info.video_url = video_url
        base_info.course_url = course_url
        base_info.price_gare = price_gare
        base_info.product_price = product_price
        base_info.decoration_poster = decoration_poster
        base_info.friend_link = friend_link
        base_info.modify_date = self.get_now_datetime()

        if is_add:
            base_info.create_date = base_info.modify_date
            base_info_model.add_entity(base_info)
        else:
            base_info_model.update_entity(base_info)

        self.reponse_json_success()

    def get_async(self):
        """
        @description: 基础信息获取
        @param {type} 
        @return: BaseInfo
        @last_editors: HuangJingCan
        """
        # 左上角信息
        info = {}
        info["company"] = "天志互联"
        info["miniappName"] = "在线拆盲盒"
        info["logo"] = "https://isv.alibabausercontent.com/010229100714/imgextra/i2/2206353354303/O1CN01GByNR91heosQQfU0Z_!!2206353354303-2-isvtu-010229100714.png"

        # 左边菜单
        menu_list = []
        menu = {}
        menu["name"] = "创建活动"
        menu["key"] = "create_action"
        menu_list.append(menu)
        menu = {}
        menu["name"] = "活动管理"
        menu["key"] = "act_manage"
        menu_list.append(menu)
        menu = {}
        menu["name"] = "装修教程"
        menu["key"] = "decoration_poster"
        menu_list.append(menu)
        menu = {}
        menu["name"] = "版本更新"
        menu["key"] = "update_ver"
        menu_list.append(menu)

        # 左边底部菜单
        bottom_button_list = []
        bottom_button = {}
        bottom_button["title"] = "发票管理"
        bottom_button["handling_event"] = "popup"
        bottom_button["event_name"] = "billManage"
        bottom_button_list.append(bottom_button)
        bottom_button = {}
        bottom_button["title"] = "配置教程"
        bottom_button["handling_event"] = "popup"
        bottom_button["event_name"] = "use_teaching"
        bottom_button_list.append(bottom_button)
        bottom_button = {}
        bottom_button["title"] = "联系旺旺"
        bottom_button["handling_event"] = "outtarget"
        bottom_button["event_name"] = "http://amos.alicdn.com/getcid.aw?v=2&uid=%E5%A4%A9%E5%BF%97%E4%BA%92%E8%81%94&site=cntaobao&s=1&groupid=0&charset=utf-8"
        bottom_button_list.append(bottom_button)
        bottom_button = {}
        bottom_button["title"] = "号码绑定"
        bottom_button["handling_event"] = "popup"
        bottom_button["event_name"] = "bind_phone"
        bottom_button_list.append(bottom_button)

        # 右边使用指引
        use_point_list = []
        use_point = {}
        use_point["index"] = "1"
        use_point["title"] = "创建活动并配置完成"
        use_point_list.append(use_point)
        use_point = {}
        use_point["index"] = "2"
        use_point["title"] = "将淘宝小程序装修至店铺"
        use_point_list.append(use_point)
        use_point = {}
        use_point["index"] = "3"
        use_point["title"] = "正式运营淘宝小程序"
        use_point_list.append(use_point)

        # 基础信息配置
        base_info_model = BaseInfoModel()
        base_info = base_info_model.get_entity_by_id(1)

        data = {}
        data["serverName"] = "在线拆盲盒模板"
        data["info"] = info
        data["menu"] = menu_list
        data["bottom_button"] = bottom_button_list
        data["use_point"] = use_point_list
        if base_info:
            # 把string转成数组对象
            if base_info.update_function:
                base_info.update_function = ast.literal_eval(base_info.update_function)
            if base_info.price_gare:
                base_info.price_gare = ast.literal_eval(base_info.price_gare)
            if base_info.product_price:
                base_info.product_price = ast.literal_eval(base_info.product_price)
            if base_info.decoration_poster:
                base_info.decoration_poster = ast.literal_eval(base_info.decoration_poster)
            if base_info.friend_link:
                base_info.friend_link = ast.literal_eval(base_info.friend_link)
            if base_info.menu_config:
                base_info.menu_config = ast.literal_eval(base_info.menu_config)
            data["base_info"] = base_info.__dict__

        if base_info:
            self.reponse_json_success(data)
        else:
            self.reponse_json_error("BaseInfoError", "基础信息出错")


class TelephoneHandler(SevenBaseHandler):
    """
    @description: 更新手机号
    """
    @filter_check_params("telephone")
    def get_async(self):
        """
        @description: 更新手机号
        @param telephone：手机号
        @return: 
        @last_editors: HuangJingCan
        """
        app_id = self.get_param("app_id")
        open_id = self.get_taobao_param().open_id
        telephone = self.get_param("telephone")
        check_code = self.get_param("check_code")
        modify_date = self.get_now_datetime()
        store_user_nick = self.get_taobao_param().user_nick.split(':')[0]


        check_code_re = self.redis_init().get("user_" + open_id + "_bind_phone_code")
        if check_code_re == None:
            return self.reponse_json_error("CheckCodeError", "验证码已过期")

        check_code_re = str(check_code_re, 'utf-8')

        if check_code != check_code_re:
            return self.reponse_json_error("CheckCodeError", "验证码错误")

        AppInfoModel().update_table("app_telephone=%s,modify_date=%s", "app_id=%s", [telephone, modify_date, app_id])

        self.reponse_json_success()


class AppUpdateHandler(TopBaseHandler):
    """
    @description: 前端版本更新
    """
    @filter_check_params()
    def get_async(self):
        """
        @description: 前端版本更新(请求top接口)
        @param {type} 
        @return: 
        @last_editors: HuangJingCan
        """
        self.app_update()


class AppInfoHandler(TopBaseHandler):
    """
    @description: 小程序信息
    """
    def get_async(self):
        #店铺主帐号名称
        store_user_nick = self.get_taobao_param().user_nick.split(':')[0]
        open_id = self.get_taobao_param().open_id

        app_info_model = AppInfoModel()
        app_info = app_info_model.get_entity("store_user_nick=%s", params=store_user_nick)
        dead_date = self.get_dead_date(store_user_nick)

        login_log = LoginLogModel().get_entity("open_id=%s", order_by="id desc", params=open_id)

        if app_info:
            access_token = self.get_token()
            if access_token != "":
                app_info.access_token = access_token
            app_info_model.update_entity(app_info)

            app_info.surplus_value = 0
            app_info.user_nick = self.get_taobao_param().user_nick
            app_info.dead_date = dead_date
            if app_info.dead_date != "expire":
                now_timestamp = TimeHelper.datetime_to_timestamp(datetime.datetime.strptime(TimeHelper.get_now_format_time('%Y-%m-%d 00:00:00'), '%Y-%m-%d %H:%M:%S'))
                dead_date_timestamp = TimeHelper.datetime_to_timestamp(datetime.datetime.strptime(app_info.dead_date, '%Y-%m-%d %H:%M:%S'))
                app_info.surplus_day = int(int(abs(dead_date_timestamp - now_timestamp)) / 24 / 3600)

            if login_log:
                app_info.last_login_date = login_log.modify_date
            else:
                app_info.last_login_date = ""

            self.reponse_json_success(app_info)
        else:
            app_info = AppInfo()

            app_info.access_token = self.get_taobao_param().access_token
            base_info = BaseInfoModel().get_dict("")

            app_info.surplus_value = 0
            app_info.user_nick = self.get_taobao_param().user_nick
            app_info.template_ver=base_info["client_ver"]

            app_info.dead_date = dead_date
            if app_info.dead_date != "expire":
                now_timestamp = TimeHelper.datetime_to_timestamp(datetime.datetime.strptime(TimeHelper.get_now_format_time('%Y-%m-%d 00:00:00'), '%Y-%m-%d %H:%M:%S'))
                dead_date_timestamp = TimeHelper.datetime_to_timestamp(datetime.datetime.strptime(app_info.dead_date, '%Y-%m-%d %H:%M:%S'))
                app_info.surplus_day = int(int(abs(dead_date_timestamp - now_timestamp)) / 24 / 3600)

            if login_log:
                app_info.last_login_date = login_log.create_date
            else:
                app_info.last_login_date = ""

            self.reponse_json_success(app_info)
