# 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
from agile.models.agile_tag import AgileTag, AgileTagMapping, AgileTagType


AGILE_TAG_TYPE_MAP = {
    u'项目': AGILE_TAG_TYPE.PROJECT,
    u'-': AGILE_TAG_TYPE.UNDEFINED
}

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


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

    path = parent_path + '/files/新老标签映射1.4.xlsx'  # 文件上传地址确定

    return path


class Command(BaseCommand):
    """
    新老标签关系映射
    sync_tag_agile_tag
    """

    def handle(self, *args, **options):
        print('START')

        excel = ExcelReader(get_path())
        excel.sheet_select_by_name(u"映射关系for后端")

        for row in range(1, excel.row_number):
            data = excel.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 IntegrityError:
                agile = AgileTag.objects.get(name=data[2])
                if not agile.is_online:
                    agile.is_online = True
                    agile.save(update_fields=['is_online'])
            AgileTagType.objects.create(
                agile_tag_id=agile.id,
                agile_tag_type=AGILE_TAG_TYPE_MAP[data[0]]
            )

            raw_mapping_data = data[1]
            if raw_mapping_data:
                old_tag_mapping = str(data[1]).split(',')
            else:
                old_tag_mapping = []
            agiletagmapping_list = []
            for _id in old_tag_mapping:
                tag_mapping = AgileTagMapping(
                    agile_tag_id=agile.id,
                    old_tag_id=int(_id)
                )
                agiletagmapping_list.append(tag_mapping)

            AgileTagMapping.objects.bulk_create(agiletagmapping_list)

        print('DONE')
