# coding:utf-8
import os
from django.core.management.base import BaseCommand
from django.db import IntegrityError

from gm_types.gaia import AGILE_TAG_CREATE_TYPE, AGILE_TAG_STYLE, AGILE_TAG_TYPE

from utils.execel import ExcelReader, ExcelWriter
from agile.models.agile_tag import AgileTag, AgileTagMapping, AgileTagType


AGILE_TAG_TYPE_MAP = {
    u'项目': AGILE_TAG_TYPE.PROJECT,
    u'-': AGILE_TAG_TYPE.UNDEFINED,
    u'医院': AGILE_TAG_TYPE.HOSPITAL,
    u'医生': AGILE_TAG_TYPE.DOCTOR,
    u'仪器': AGILE_TAG_TYPE.INSTRUMENT,
    u'品牌': AGILE_TAG_TYPE.BRAND,
    u'部位': AGILE_TAG_TYPE.POSITION,
    u'症状': AGILE_TAG_TYPE.SYMPTOM,
    u'材料': AGILE_TAG_TYPE.MATERIAL,
    u'城市': AGILE_TAG_TYPE.CITY,
    u'省份': AGILE_TAG_TYPE.PROVINCE,
    u'国家': AGILE_TAG_TYPE.COUNTRY,
}

CREATE_TAG_TYPE_MAP = {
    u'项目': AGILE_TAG_CREATE_TYPE.SYSTEM,
    u'-': AGILE_TAG_CREATE_TYPE.OPERATOR,
    u'医生': AGILE_TAG_CREATE_TYPE.SYSTEM,
    u'医院': AGILE_TAG_CREATE_TYPE.SYSTEM,
}

EXCEL_SHEET = [u'医院', u'医生']


def get_path():
    parent_path = os.path.dirname(os.path.dirname(__file__))

    path = parent_path + '/files/医院医生新标签映射表格.xlsx'

    return path


class Command(BaseCommand):
    """
    医生、医院标签
    sync_agile_tag_v2
    """

    def handle(self, *args, **options):
        print('START')
        excel_write = ExcelWriter("agile_tags.xlsx")
        excel_read = ExcelReader(get_path())

        for sheet in EXCEL_SHEET:
            excel_read.sheet_select_by_name(sheet)

            excel_write.create_sheet(sheet)
            excel_write.write_header(['标签名称', '标签id'])
            agile_tag_type = []
            write_rows = []
            for row in range(1, excel_read.row_number):
                data = excel_read.read_row(row)
                # data[0], data[1], data[2]  标签类型  老标签id  新标签name
                if not any([data[0], data[1], data[2]]):
                    break
                try:
                    agile = AgileTag.objects.create(
                        name=data[2],
                        create_tag_type=CREATE_TAG_TYPE_MAP[data[0]],
                        style=AGILE_TAG_STYLE.UNDEFINED
                    )
                except:
                    continue
                agile_tag_type.append(
                    AgileTagType(
                        agile_tag_id=agile.id,
                        agile_tag_type=AGILE_TAG_TYPE_MAP[data[0]]
                    )
                )
                write_rows.append([data[2], agile.id])

            offset = 1000
            while agile_tag_type:
                AgileTagType.objects.bulk_create(agile_tag_type[:offset])
                agile_tag_type = agile_tag_type[offset:]

            excel_write.write_rows(2, write_rows)

            excel_write.save()

        print('DONE')
