#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "chenwei"
# Date: 2019/1/11

import datetime
from gm_dataquery.db import DB
from api.tool.wechat_push import wechat_template_push
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from api.models.user import UserExtraWechatInfo
from api.tool.log_tool import logging_exception, info_logger
from facialactivity.models import ActivityConfig, ActivityUserImage


def send_message(id):
    aui, uw, data = None, None, dict()
    try:
        aui = ActivityUserImage.objects.get(id=id)
        uw = UserExtraWechatInfo.objects.get(user_id=aui.user_id)
        data = {
            "keyword1": {
                "value": "您上传的图片不符合相关法律法规，已为您下线该图片，请重新上传"
            },
            "keyword2": {
                "value": "图片不合格"
            },
            "keyword3": {
                "value": "更美新春颜值pk活动"
            },
            "keyword4": {
                "value": "{date}".format(date=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            },
            "keyword5": {
                "value": "{nick_name}".format(nick_name=uw.wechat_nickname.encode('utf8'))
            },
            "keyword6": {
                "value": "请上传合法图片参与活动哦~"
            }
        }
    except Exception:
        logging_exception()

    code = wechat_template_push(open_id=uw.openid, template_type='template_check', form_id=aui.form_id, data=data)
    if code == 0:
        info_logger.info("用户%s图片下线消息推送成功" %aui.user_id)
    else:
        logging_exception()


class ActivityUserImageDB(DataBuilder):
    pass


@DB
class ActivityUserImageDQ(DataSQLQuery):
    model = ActivityUserImage
    data_model = ActivityUserImageDB

    def filter_create_time(self, srch_key, srch_val, regex=False):
        return self._qry_time_range(srch_key, srch_val, regex)

    def update(self, updates, **kwargs):
        is_vest = self.model.objects.get(id=kwargs['id']).is_vest
        if not is_vest:
            send_message(int(kwargs['id']))

        return super(ActivityUserImageDQ.sqlquery, self).update(updates, **kwargs)


class ActivityConfigDB(DataBuilder):
    def getval_current_nums(self, obj):
        return ActivityUserImage.objects.filter(level=obj.level, is_vest=False, is_online=True, is_deleted=False).count()


@DB
class ActivityConfigDQ(DataSQLQuery):
    model = ActivityConfig
    data_model = ActivityConfigDB

