# coding=utf-8

import time
import json
import requests

from django.core.management import BaseCommand
from gm_types.gaia import SPECIAL_MODULE
from rpc.tool.log_tool import info_logger
from api.models.special import SpecialStorey, SpecialLayout


class Command(BaseCommand):

    @classmethod
    def handle_data(cls, data):
        # 处理套娃data
        for item in data:
            try:
                if 'img' in item:
                    if not item.get('img'):
                        continue
                    res = requests.get(item['img'] + "-imageinfo", verify=False).json()
                    item['img' + '_width'] = res.get("width") or ""
                    item['img' + '_height'] = res.get("height") or ""
                if 'below_img' in item:
                    if not item.get('below_img'):
                        continue
                    res = requests.get(item['below_img'] + "-imageinfo", verify=False).json()
                    item['below_img' + '_width'] = res.get("width") or ""
                    item['below_img' + '_height'] = res.get("height") or ""
                if 'cover_img' in item:
                    if not item.get('cover_img'):
                        continue
                    res = requests.get(item['cover_img'] + "-imageinfo", verify=False).json()
                    item['cover_img' + '_width'] = res.get("width") or ""
                    item['cover_img' + '_height'] = res.get("height") or ""
                if 'background_img' in item:
                    if not item.get('background_img'):
                        continue
                    res = requests.get(item['background_img'] + "-imageinfo", verify=False).json()
                    item['background_img' + '_width'] = res.get("width") or ""
                    item['background_img' + '_height'] = res.get("height") or ""
                if 'data' in item:
                    item['data'] = cls.handle_data(item['data']) or item['data']
            except:
                continue
        return data

    @classmethod
    def update_img_data(cls):
        storey_list = ['p_select_before_img', 'p_child_floor_img', 'p_select_after_img', 'c_select_before_img',
                       'c_select_after_img']
        storey_objs = SpecialStorey.objects.all()
        for storey in storey_objs:
            img_data = json.loads(storey.related)
            try:
                for key, value in img_data.items():
                    try:
                        if key in storey_list:
                            if not value:
                                continue
                            res = requests.get(value + "-imageinfo", verify=False).json()
                            img_data[key + '_width'] = res.get("width") or ""
                            img_data[key + '_height'] = res.get("height") or ""
                        if key == 'data':
                            img_data['data'] = cls.handle_data(img_data['data']) or img_data['data']
                    except:
                        continue
            except:
                info_logger.info(u"failed handle SpecialStorey id == {id}".format(id=storey.id))
                continue
            storey.related = json.dumps(img_data)
            storey.save()

        layout_objs = SpecialLayout.objects.all()
        for item in layout_objs:
            try:
                if item.module == SPECIAL_MODULE.FLOOR:
                    img_data = json.loads(item.related)
                    if 'background_img' in img_data:
                        if not img_data.get('background_img'):
                            continue
                        res = requests.get(img_data['background_img'] + "-imageinfo", verify=False).json()
                        img_data['background_img' + '_width'] = res.get("width") or ""
                        img_data['background_img' + '_height'] = res.get("height") or ""
                # 美券直领
                if item.module == SPECIAL_MODULE.COUPONS:
                    img_data = json.loads(item.related)
                    for coupon in img_data:
                        for img_item in coupon.get('data') or []:
                            if not img_item.get('img'):
                                continue
                            res = requests.get(img_item['img'] + "-imageinfo", verify=False).json()
                            img_item['img' + '_width'] = res.get("width") or ""
                            img_item['img' + '_height'] = res.get("height") or ""
                # 转盘活动
                if item.module == SPECIAL_MODULE.TURNTABLE:
                    img_data = json.loads(item.related)
                    for img in img_data:
                        for img_item in img.get("image_data") or []:
                            if not img_item.get('img'):
                                continue
                            res = requests.get(img_item['img'] + "-imageinfo", verify=False).json()
                            img_item['img' + '_width'] = res.get("width") or ""
                            img_item['img' + '_height'] = res.get("height") or ""
                # 图片设置
                if item.module == SPECIAL_MODULE.GADGET_TEMPLATE:
                    img_data = json.loads(item.related)
                    for img in img_data:
                        if img.get("background_img"):
                            res = requests.get(img["background_img"] + "-imageinfo", verify=False).json()
                            img['background_img' + '_width'] = res.get("width") or ""
                            img['background_img' + '_height'] = res.get("height") or ""
                        if img.get("spread_img"):
                            res = requests.get(img["spread_img"] + "-imageinfo", verify=False).json()
                            img['spread_img' + '_width'] = res.get("width") or ""
                            img['spread_img' + '_height'] = res.get("height") or ""
                        if img.get("retract_img"):
                            res = requests.get(img["retract_img"] + "-imageinfo", verify=False).json()
                            img['retract_img' + '_width'] = res.get("width") or ""
                            img['retract_img' + '_height'] = res.get("height") or ""
                        for img_item in img.get("data") or []:
                            try:
                                if not img_item.get('img'):
                                    continue
                                res = requests.get(img_item['img'] + "-imageinfo", verify=False).json()
                                img_item['img' + '_width'] = res.get("width") or ""
                                img_item['img' + '_height'] = res.get("height") or ""
                            except:
                                continue
                # 视频
                if item.module == SPECIAL_MODULE.VIDEO:
                    img_data = json.loads(item.related)
                    for img in img_data:
                        if img.get("background_img"):
                            res = requests.get(img["background_img"] + "-imageinfo", verify=False).json()
                            img['background_img' + '_width'] = res.get("width") or ""
                            img['background_img' + '_height'] = res.get("height") or ""
                        if img.get("cover_img"):
                            res = requests.get(img["cover_img"] + "-imageinfo", verify=False).json()
                            img['cover_img' + '_width'] = res.get("width") or ""
                            img['cover_img' + '_height'] = res.get("height") or ""
                        if img.get("below_img"):
                            res = requests.get(img["below_img"] + "-imageinfo", verify=False).json()
                            img['below_img' + '_width'] = res.get("width") or ""
                            img['below_img' + '_height'] = res.get("height") or ""
                # ToolBar配置
                if item.module == SPECIAL_MODULE.TOOL_BAR:
                    img_data = json.loads(item.related)
                    for img in img_data:
                        if img.get("selected_img"):
                            res = requests.get(img["selected_img"] + "-imageinfo", verify=False).json()
                            img['selected_img' + '_width'] = res.get("width") or ""
                            img['selected_img' + '_height'] = res.get("height") or ""
                        if img.get("unselected_img"):
                            res = requests.get(img["unselected_img"] + "-imageinfo", verify=False).json()
                            img['unselected_img' + '_width'] = res.get("width") or ""
                            img['unselected_img' + '_height'] = res.get("height") or ""
            except:
                info_logger.info(u"failed handle SpecialLayout id == {id}".format(id=item.id))
                continue

            item.related = json.dumps(img_data)
            item.save()


    def handle(self, *args, **kwargs):
        time_start = int(time.time() * 1000)

        print('----------开始更新数据-----------------')

        self.update_img_data()

        print('----------更新数据完成-----------------')
        time_end = int(time.time() * 1000)
        print("----------耗时 {} 毫秒----------------".format(time_end-time_start))



