#!/usr/bin/env python3  
# -*- coding: utf-8 -*-  
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: langer
@software: PyCharm
@DATE: 2019/6/3 17:29
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: User.py
@Contact: chanjunkai@163.com
"""
import json
import time

from django.views.generic import TemplateView

from model.models import AsImgModel, SysSetModel
from object.ResponseObject import ResponseObject
from object.TokenObject import TokenObject
from service.CommonService import CommonService
from object.SesClassObject import SesClassObject
from object.RedisObject import RedisObject


class addView(TemplateView):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = json.loads(request.body.decode('utf-8'))
        return self.validate(request_dict)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        return self.validate(request_dict)

    def validate(self, request_dict):
        response = ResponseObject()
        token = request_dict.get('token', None)
        url = request_dict.get('url', None)
        asin = request_dict.get('asin', None)
        tko = TokenObject(token)
        if tko.code == 0:
            img_md5 = CommonService.get_remote_md5_sum(url=url)
            nowTime = int(time.time())
            create_dict = {
                'asin': asin,
                'md5': img_md5,
                'url': url,
                'addTime': nowTime,
                'updTime': nowTime
            }
            AsImgModel.objects.create(**create_dict)
            return response.json(0)
        else:
            return response.json(tko.code)


class queryView(TemplateView):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = json.loads(request.body.decode('utf-8'))
        return self.validate(request_dict)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        return self.validate(request_dict)

    def validate(self, request_dict):
        response = ResponseObject()
        token = request_dict.get('token', None)
        searchAsin = request_dict.get('searchAsin', None)
        page = int(request_dict.get('page', None))
        line = int(request_dict.get('line', None))

        tko = TokenObject(token)
        if tko.code == 0:
            userID = tko.userID
            ai_qs = AsImgModel.objects.filter()
            if searchAsin:
                ai_qs = ai_qs.filter(asin__contains=searchAsin)
            count = ai_qs.count()
            ai_qs = ai_qs[(page - 1) * line:page * line]
            if ai_qs.exists():
                res = list(ai_qs.values('id', 'addTime', 'updTime', 'asin', 'md5', 'url'))
                return response.json(0, res, extra={'count': count})
            else:
                return response.json(0)
        else:
            return response.json(tko.code)


class updateView(TemplateView):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = json.loads(request.body.decode('utf-8'))
        return self.validate(request_dict)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        return self.validate(request_dict)

    def validate(self, request_dict):
        response = ResponseObject()
        token = request_dict.get('token', None)
        id = request_dict.get('id', None)
        asin = request_dict.get('asin', None)
        url = request_dict.get('url', None)

        nowTime = int(time.time())
        tko = TokenObject(token)
        if tko.code == 0:
            ai_qs = AsImgModel.objects.filter(id=id)
            update_dict = {'updTime': nowTime}
            if asin:
                update_dict['asin'] = asin
            if url:
                update_dict['url'] = url
                img_md5 = CommonService.get_remote_md5_sum(url=url)
                update_dict['md5'] = img_md5
            ai_qs.update(**update_dict)
            return response.json(0)
        else:
            return response.json(tko.code)


class deleteView(TemplateView):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = json.loads(request.body.decode('utf-8'))
        return self.validate(request_dict)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        return self.validate(request_dict)

    def validate(self, request_dict):
        response = ResponseObject()
        token = request_dict.get('token', None)
        tko = TokenObject(token)
        if tko.code == 0:
            id = request_dict.get('id', None)
            if id:
                AsImgModel.objects.filter(id=id).delete()
                return response.json(0)
            else:
                return response.json(0)
        else:
            return response.json(tko.code)


#
class cycleImgView(TemplateView):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = json.loads(request.body.decode('utf-8'))
        return self.validate(request_dict)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        return self.validate(request_dict)

    def validate(self, request_dict):
        response = ResponseObject()
        # token = request_dict.get('token', None)
        # tko = TokenObject(token)
        as_qs = AsImgModel.objects.filter().values('url', 'md5', 'asin')
        as_list = list(as_qs)
        key_list = ['asimgEmail', 'asinterval']
        sys_qs = SysSetModel.objects.filter(key__in=key_list).values('key', 'val')
        sys_dict = {}
        for i in sys_qs:
            sys_dict[i['key']] = i['val']
        asimgEmail = sys_dict['asimgEmail']
        asinterval = sys_dict['asinterval']
        redisObj = RedisObject()
        redis_asinterval = redisObj.get_data(key='asinterval')
        if redis_asinterval:
            return response.json(0, '时候未到呢')
        else:
            redisObj.set_data(key='asinterval', val=1, expire=int(asinterval))
        # 校验出的asin码列表
        err_asin_list = []
        for a in as_qs:
            try:
                md5 = CommonService.get_remote_md5_sum(a['url'])
            except Exception as e:
                print(repr(e))
                err_asin_list.append(a['asin'])
            else:
                if md5 == a['md5']:
                    pass
                else:
                    err_asin_list.append(a['asin'])
        # 发送邮件
        # from var_dump import var_dump
        # var_dump(err_asin_list)
        if len(err_asin_list) > 0:
            sesObj = SesClassObject()
            sesObj.send_email(send_address_list=[asimgEmail], subject='发现亚马逊产品图片丢失', body=','.join(err_asin_list))
            return response.json(0, {'send_count': len(err_asin_list)})

        return response.json(0)
