# coding=utf-8
from __future__ import unicode_literals
import hashlib
import time
import random
import urllib
import urllib2
import json
import uuid
import csv
from multiprocessing import Manager, Pool

from django.core.management import BaseCommand
from api.models.user import User

import sys

reload(sys)
sys.setdefaultencoding('utf8')

class TextCheckAPIDemo(object):
    u"""文本在线检测接口示例代码"""
    API_URL = "https://api.aq.163.com/v3/text/check"
    VERSION = "v3"

    def __init__(self, secret_id, secret_key, business_id):
        u"""
        Args:
            secret_id (str) 产品密钥ID，产品标识
            secret_key (str) 产品私有密钥，服务端生成签名信息使用
            business_id (str) 业务ID，易盾根据产品业务特点分配
        """
        self.secret_id = secret_id
        self.secret_key = secret_key
        self.business_id = business_id

    def gen_signature(self, params=None):
        u"""生成签名信息
        Args:
            params (object) 请求参数
        Returns:
            参数签名md5值
        """
        buff = u""
        for k in sorted(params.keys()):

            buff += str(k) + str(params[k])

        buff += self.secret_key
        return hashlib.md5(buff).hexdigest()

    def check(self, params):
        u"""请求易盾接口
        Args:
            params (object) 请求参数
        Returns:
            请求结果，json格式
        """
        params["secretId"] = self.secret_id
        params["businessId"] = self.business_id
        params["version"] = self.VERSION
        params["timestamp"] = int(time.time() * 1000)
        params["nonce"] = int(random.random()*100000000)
        params["signature"] = self.gen_signature(params)
        try:
            params = urllib.urlencode(params)
            request = urllib2.Request(self.API_URL, params)
            content = urllib2.urlopen(request, timeout=5).read()
            return json.loads(content)
        except Exception, ex:
            return json.loads({'msg': u"调用API接口失败", 'detail': str(ex)})


class Params(object):
    dataType = 1
    callback = ''

    def __init__(self, content, ip="123.115.77.137", account="python@163.com",
                 deviceType="4", deviceId="92B1E5AA-4C3D-4565-A8C2-86E297055088"):
        self.content = content
        self.ip = ip
        self.account = account
        self.deviceType = deviceType
        self.deviceId = deviceId
        self.dataId = uuid.uuid4().hex

    def build(self):
        return {
            "dataId": self.dataId,
            "content": self.content,
            "dataType": self.dataType,
            "ip": self.ip,
            "account": self.account,
            "deviceType": self.deviceType,
            "deviceId": self.deviceId,
            "callback": self.callback,
            "publishTime": str(int(time.time() * 1000))
        }


uid = '914c9cb763500c23acdf121faed02c31'
key = 'ffb43924f88946f7d5b7aac1832a18e5'
text_bid = '8034f7ed207ec691c3f30d318e06e0c7'
user_info_bid = '3093224466465606d7c4f94f1b86088e'


text_api = TextCheckAPIDemo(uid, key, text_bid)
user_api = TextCheckAPIDemo(uid, key, user_info_bid)
result_list = Manager().list()


class Content(object):
    def __init__(self, user_list):
        self.user_list = user_list

    @staticmethod
    def check_is_need(text):
        return True

    def build_content(self):
        content_list = []
        for user_dict in self.user_list:
            if self.check_is_need(user_dict['last_name']):
                content_list.append(user_dict['last_name'])
        return u','.join(content_list)


def check(user_list):
    content = Content(user_list).build_content()
    pa = Params(content)
    params = pa.build()

    ret = text_api.check(params)

    # handle result
    # result_message = {
    #     'user_ids': [user['id'] for user in user_list],
    #     'dtaId': pa.dataId
    # }
    hits = []
    if ret["code"] == 200:
        action = ret["result"]["action"]
        taskId = ret["result"]["taskId"]
        labelArray = ret["result"]["labels"]
        action_verb = ''
        if action == 0:
            action_verb = u'通过'
            return []

        elif action == 1:
            action_verb = u'嫌疑， 需要人工复审'

        elif action == 2:
            action_verb = u'不通过'

        # fromat result
        for la in labelArray:
            for label in la['details']['hint']:
                _source = [user for user in user_list if set(label) & set(user['last_name'])]
                hits.append({
                    '_source': _source,
                    'action_verb': action_verb,
                    'label': label,
                    # 'content': content,
                    # 'ids': [user['id'] for user in user_list]
                })

    else:
        # get result failed
        hits.append({
            '_source': ret['msg'],
            'action_verb': 'failed',
            'label': 'failed',
        })
    result_list.extend(hits)


class DumpResult(object):
    def __init__(self, result):
        self.result = result

    def dump_to_file(self):
        with open('/tmp/check_result.csv', 'wb') as f:
            writer = csv.writer(f, quotechar=str(' '), quoting=csv.QUOTE_ALL, dialect='excel')
            writer.writerow([u'结果', u'敏感词', u'用户名', u'用户ID'])
            for r in self.result:
                for user in r['_source']:
                  writer.writerow([r['action_verb'], r['label'], user['last_name'], user['id']])

        print('done!')


class Command(BaseCommand):

    def handle(self, *args, **options):
        users = User.objects.filter(last_name__isnull=False).exclude(last_name='').values('id', 'last_name')
        user_list = self.cut_queryset(users, 1000)
        pool = Pool(processes=4)
        pool.map(check, user_list)
        pool.close()
        pool.join()

        DumpResult(result_list).dump_to_file()

    @staticmethod
    def cut_queryset(queryset, size):
        l = []
        for i in range(0, queryset.count(), size):
            l.append(list(queryset[i: i+size]))

        return l



