import time
import traceback
import os
from django.shortcuts import render_to_response
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import View

from Model.models import App_Info, App_Colophon
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService
from Ansjer.config import BASE_DIR, SERVER_DOMAIN

'''
http://192.168.136.45:8077/appInfo?operation=add&token=test&appBundleId=123456&appName=%E8%AF%BA%E5%9F%BA%E4%BA%9A1%E5%8F%B7&systemLanguage=US&content=dladfjklsjfdsajkdfasjkljlk&app_type=2&newAppversion=1234&bundleVersion=1234
http://192.168.136.45:8077/appInfo?operation=update&token=test&appBundleId=1234&appName=%E8%AF%BA%E5%9F%BA%E4%BA%9A3%E5%8F%B7&systemLanguage=US&content=dladfjklsjfdsajkdfasjkljlk&app_type=2&newAppversion=555&id=6
http://127.0.0.1:8000/appInfo?operation=query&token=stest&page=1&line=10
http://192.168.136.45:8077/appInfo?operation=delete&token=test&id=1&id=2&id=3&id=4&id=5

http://192.168.136.39:8000/appVer/views?lang=cn&appBundleId=com.ansjer.accloud&app_type=1
'''


class AppInfo(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(AppInfo, self).dispatch(*args, **kwargs)

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

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        self.request = request
        return self.validation(request_dict=request.POST)

    def validation(self, request_dict, *args, **kwargs):
        operation = request_dict.get('operation', None)
        response = ResponseObject()
        if not operation:
            return response.json(444, 'operation')
        if operation == 'getAppNewVersion':
            return self.getAppNewVersion(request_dict, response)
        else:
            token = request_dict.get('token', None)
            tko = TokenObject(token)
            response.lang = tko.lang
            if tko.code != 0:
                return response.json(tko.code)
            userID = tko.userID
            if not userID:
                return response.json(104)
            if operation == 'query':
                return self.query(request_dict, userID, response)
            elif operation == 'add':
                return self.add(request_dict, userID, response)
            elif operation == 'update':
                return self.update(request_dict, userID, response)
            elif operation == 'delete':
                return self.delete(request_dict, userID, response)
            else:
                return response.json(414)

    def getAppNewVersion(self, request_dict, response):
        appBundleId = request_dict.get('appBundleId', None)
        app_type = request_dict.get('app_type', None)
        if appBundleId is not None and app_type is not None:
            try:
                app_info = App_Info.objects.get(appBundleId=appBundleId, app_type=app_type)
            except Exception:
                errorInfo = traceback.format_exc()
                return response.json(424, {'details': errorInfo})
            else:
                return response.json(0, {'appBundleId': app_info.appBundleId,
                                         'appName': app_info.appName,
                                         'newAppversion': app_info.newAppversion,
                                         'systemLanguage': app_info.systemLanguage,
                                         'content': app_info.content,
                                         'app_type': app_info.app_type,
                                         'downloadLink': app_info.downloadLink,
                                         'id': app_info.id,
                                         'bundleVersion': app_info.bundleVersion,
                                         'minAppversion': app_info.minAppversion
                                         })
        else:
            return response.json(444, 'app_type,appBundleId')

    def add(self, request_dict, userID, response):
        own_perm = ModelService.check_perm(userID=userID, permID=40)
        if own_perm is not True:
            return response.json(404)
        appBundleId = request_dict.get('appBundleId', None)
        appName = request_dict.get('appName', None)
        systemLanguage = request_dict.get('systemLanguage', None)
        newAppversion = request_dict.get('newAppversion', None)
        content = request_dict.get('content', None)
        app_type = request_dict.get('app_type', None)
        bundleVersion = request_dict.get('bundleVersion', None)
        downloadLink = request_dict.get('downloadLink', None)
        minAppversion = request_dict.get('minAppversion', None)
        f = self.request.FILES.get('file', None)
        param_flag = CommonService.get_param_flag(
            data=[appBundleId, appName, systemLanguage, minAppversion, newAppversion, content, app_type, bundleVersion])
        if param_flag is not True:
            return response.json(444)
        has_app_info = App_Info.objects.filter(appBundleId=appBundleId)
        if has_app_info.exists():
            return response.json(174)
        else:
            try:
                create_dict = {
                    'appBundleId': appBundleId,
                    'appName': appName,
                    'newAppversion': newAppversion,
                    'systemLanguage': systemLanguage,
                    'content': content,
                    'app_type': app_type,
                    'bundleVersion': bundleVersion,
                    'minAppversion': minAppversion,
                    'downloadLink': downloadLink
                }
                # 产品图片
                if f:
                    try:
                        rv_path = 'static/app/image/' + appBundleId + '.png'
                        as_path = os.path.join(BASE_DIR, rv_path)
                        if os.path.exists(as_path):
                            os.remove(as_path)
                        with open(as_path, 'wb+') as destination:
                            for chunk in f.chunks():
                                destination.write(chunk)
                        create_dict['img'] = rv_path
                    except Exception as e:
                        print(repr(e))
                        pass
                app_Info = App_Info(**create_dict)
                app_Info.save()
            except Exception:
                errorInfo = traceback.format_exc()
                print(errorInfo)
                return response.json(500, {'details': errorInfo})
            else:
                if app_Info.id:
                    res = {'appBundleId': app_Info.appBundleId,
                           'appName': app_Info.appName,
                           'newAppversion': app_Info.newAppversion,
                           'systemLanguage': app_Info.systemLanguage,
                           'content': app_Info.content,
                           'app_type': app_Info.app_type,
                           'id': app_Info.id,
                           'downloadLink': downloadLink,
                           'minAppversion': app_Info.minAppversion,
                           'bundleVersion': app_Info.bundleVersion}
                    return response.json(0, res)
                else:
                    return response.json(500)

    def query(self, request_dict, userID, response):
        own_perm = ModelService.check_perm(userID=userID, permID=30)
        if own_perm is not True:
            return response.json(404)
        page = int(request_dict.get('page', None))
        line = int(request_dict.get('line', None))
        app_type = request_dict.get('app_type', None)
        if not page or not line or not app_type:
            return response.json(444, 'page,line，app_type')
        queryset = App_Info.objects.filter(app_type=app_type)
        if queryset.exists():
            count = queryset.count()
            res = queryset[(page - 1) * line:page * line]
            send_json = CommonService.qs_to_dict(res)
            for k, v in enumerate(send_json["datas"]):
                if send_json['datas'][k]['fields']['img']:
                    img = SERVER_DOMAIN + 'sysfile/' + send_json['datas'][k]['fields']['img']
                    send_json["datas"][k]['fields']['img'] = img
            send_json['count'] = count
            return response.json(0, send_json)
        return response.json(0)

    def update(self, request_dict, userID, response):
        own_perm = ModelService.check_perm(userID=userID, permID=30)
        if own_perm is not True:
            return response.json(404)
        id = request_dict.get('id', None)
        appBundleId = request_dict.get('appBundleId', None)
        appName = request_dict.get('appName', None)
        systemLanguage = request_dict.get('systemLanguage', None)
        newAppversion = request_dict.get('newAppversion', None)
        content = request_dict.get('content', None)
        app_type = request_dict.get('app_type', None)
        bundleVersion = request_dict.get('bundleVersion', None)
        minAppversion = request_dict.get('minAppversion', None)
        downloadLink = request_dict.get('downloadLink', None)
        f = self.request.FILES.get('file', None)
        try:
            res = {}
            app_info = App_Info.objects.get(id=id)
            if appBundleId:
                app_info.appBundleId = appBundleId
            if appName:
                app_info.appName = appName
            if systemLanguage:
                app_info.systemLanguage = systemLanguage
            if newAppversion:
                app_info.newAppversion = newAppversion
            if content:
                app_info.content = content
            if app_type:
                app_info.app_type = app_type
            if minAppversion:
                app_info.minAppversion = minAppversion
            if bundleVersion:
                app_info.bundleVersion = bundleVersion
            if downloadLink:
                app_info.downloadLink = downloadLink
            if f:
                try:
                    rv_path = 'static/app/image/' + appBundleId + '.png'
                    as_path = os.path.join(BASE_DIR, rv_path)
                    print(as_path)
                    if os.path.exists(as_path):
                        os.remove(as_path)
                    with open(as_path, 'wb+') as destination:
                        for chunk in f.chunks():
                            destination.write(chunk)
                except Exception as e:
                    print(repr(e))
                    pass
                else:
                    app_info.img = rv_path
                    res['img'] = SERVER_DOMAIN + 'sysfile/' + rv_path
            app_info.save()
        except Exception as e:
            return response.json(404, repr(e))
        else:
            res['update_id'] = app_info.id
            res['update_time'] = str(app_info.update_time)
            return response.json(0, res)

    def delete(self, request_dict, userID, response):
        own_perm = ModelService.check_perm(userID=userID, permID=10)
        if own_perm is not True:
            return response.json(404)
        id_list = request_dict.getlist('id', None)
        if not id_list:
            return response.json(444, 'id must list')
        try:
            for id in id_list:
                App_Info.objects.filter(id=id).delete()
        except Exception as e:
            errorInfo = traceback.format_exc()
            print(errorInfo)
            return response.json(424, {'details': repr(e)})
        else:
            return response.json(0)


class AppVersionView(View):

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

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        return self.validation(request_dict=request.POST)

    def validation(self, request_dict, *args, **kwargs):
        appBundleId = request_dict.get('appBundleId', None)
        app_type = request_dict.get('app_type', None)
        lang = request_dict.get('lang', None)
        # print (appBundleId)
        # if lang == 'cn':
        #     return render_to_response('appVersionLists_cn.html')
        # else:
        #     return render_to_response('appVersionLists_en.html')
        queryset = App_Colophon.objects.filter(lang=lang, app_id__appBundleId=appBundleId,
                                               app_id__app_type=app_type).order_by('-version_time', '-newApp_version')
        queryset_dict = CommonService.qs_to_dict(queryset).get('datas')
        print(queryset_dict)
        # 修改数据逻辑改装数据返回值
        for k, v in enumerate(queryset_dict):
            content = v['fields']['content']
            content = content.split('\n')  # 分割字符串
            v['fields']['content'] = content
            # 时间戳转日期
            version_time = v['fields']['version_time']
            version_time = time.strftime("%Y-%m-%d", time.localtime(version_time))
            v['fields']['version_time'] = version_time
        return render_to_response('appVerList.html', locals())


class AppIdDataView(View):

    def get(self, request):
        request.encoding = 'utf-8'
        return self.validation(request_dict=request.GET)

    def post(self, request):
        request.encoding = 'utf-8'
        return self.validation(request_dict=request.POST)

    def validation(self, request_dict):
        response = ResponseObject()
        token = request_dict.get('token', None)
        tko = TokenObject(token)
        if tko.code == 0:
            # 获取appbulidID
            res = {'ios': [], 'android': []}
            qs = App_Info.objects.filter().values('appBundleId', 'appName', 'app_type')
            print(qs)
            for q in qs:
                if q['app_type'] == 1:
                    res['ios'].append({'appBundleId': q['appBundleId'], 'appName': q['appName']})
                if q['app_type'] == 2:
                    res['android'].append({'appBundleId': q['appBundleId'], 'appName': q['appName']})
            return response.json(0, res)
        else:
            return response.json(tko.code)
