# coding=utf-8

import time
import xlrd

from django.core.management import BaseCommand

from api.models.face.facial import FacialCombi
from gm_types.gaia import CONTOUR_TYPE, EYE_TYPE

class Command(BaseCommand):

    @classmethod
    def update_old_to_offline(cls):
        FacialCombi.objects.filter().update(is_online=False)

    @classmethod
    def read_and_insert(cls, file_path):
        xls_file = xlrd.open_workbook(file_path)
        xls_sheet = xls_file.sheets()[0]
        data_list = []

        key_map = {}
        for item in [CONTOUR_TYPE, EYE_TYPE]:
            [key_map.update({i[1]: i[0]}) for i in item]
        key_map.update({u"椭圆": 'tuoyuanlian'})
        key_map.update({u"长脸": 'changlian'})
        key_map.update({u"圆脸": 'yuanlian'})
        key_map.update({u"倒三角脸": 'daosanjiaolian'})
        key_map.update({u"菱形脸": 'lingxinglian'})
        key_map.update({u"凤眼": 'fengyan'})
        key_map.update({u"下垂眼": 'xiachuiyan'})
        key_map.update({u"三角眼": 'sanjiaoyan'})
        key_map.update({u"细长眼": 'xichangyan'})

        for line in range(1, xls_sheet.nrows):
            row_value = xls_sheet.row_values(line)
            create_kwargs = {
                'contour': key_map[row_value[0]],
                'eye': key_map[row_value[1]],
                "gender": 1 if row_value[2] == u"男" else 2,
                "title": row_value[3],
                "desc": row_value[4],
                "celebrity": row_value[5],
                'chin': "unknown",
                "eyebrow": "unknown",
                "nose": "unknown",
                "lip": "unknown",
            }

            data_list.append(FacialCombi(**create_kwargs))
        FacialCombi.objects.bulk_create(data_list)

    def handle(self, *args, **kwargs):
        time_start = int(time.time() * 1000)
        print('----------开始执行命令-----------------')
        print('----------开始更新老数据-----------------')
        self.update_old_to_offline()
        print('----------更新老数据完成-----------------')

        print('----------开始数据导入-----------------')
        file_path = "./api/management/files/facial_info.xlsx"  # args[2]
        self.read_and_insert(file_path)
        print('----------数据导入完成-----------------')
        time_end = int(time.time() * 1000)
        print("----------耗时 {} 毫秒----------------".format(time_end-time_start))






