# ! /usr/bin/env python
# -*- coding: utf-8 -*-
from agile.models import AttrTag, AttrTagSynonym, TagSynonym, TagMapOldTag
from django.core.management import BaseCommand
from openpyxl import Workbook
from agile.models.tag import TagV3Relation
from api.models import Tag, TAG_TYPE, TagRelation, TagV3, TAG_V3_TYPE


class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('param', nargs='+', type=str)
    '''
       导出execl命令 sudo python manage.py export_new_old_tag export,
    '''

    def handle(self, *args, **options):
        for param in options['param']:
            if param == 'export':
                excel = HandleExcel()
                excel.export_old()
                excel.export_new()


class HandleExcel:
    def __init__(self):
        # 新标签和老标签是多对多的关系
        all_tag_v3 = TagV3.objects.filter().all()
        # 所有新标签的ids
        all_tag_v3_ids = [t.id for t in all_tag_v3]
        # 新标签{新标签id:新标签name}字典
        self.new_tag_id2tag_name = {t.id: t.name for t in all_tag_v3}
        old_tag_ids = set()
        # 新标签id对应老标签id的映射
        self.new_old_id_map = {}
        # 老标签id对应新标签id的映射
        self.old_new_id_map = {}
        self.tag_map_old_tags = TagMapOldTag.objects.filter(tag_id__in=all_tag_v3_ids)
        for tag_map in self.tag_map_old_tags:
            self.new_old_id_map[tag_map.tag_id] = tag_map.old_tag_id
            self.old_new_id_map[tag_map.old_tag_id] = tag_map.tag_id
            old_tag_ids.add(tag_map.old_tag_id)
        old_tags = Tag.objects.filter(id__in=old_tag_ids)
        # {老标签id:老标签name}
        self.old_tag_id2tag_name = {t.id: t.name for t in old_tags}
        # print "新标签{新标签id:新标签name}字典", self.new_tag_id2tag_name
        # print "{老标签id:老标签name}", self.old_tag_id2tag_name
        # print "新标签id对应老标签id的映射", self.new_old_id_map
        # print "老标签id对应新标签id的映射", self.old_new_id_map

    def export_old(self):
        # 根据三级标签反推出二级和三级标签
        # 查找所有的旧的三级标签
        tag_list = Tag.objects.filter(tag_type=TAG_TYPE.ITEM_WIKI)
        excel = Workbook()
        excel_active = excel.get_active_sheet()
        excel_active.title = 'tag_old'
        head = [u'一级分类ID',
                u'一级分类',
                u'二级分类ID',
                u'二级分类',
                u'三级分类ID',
                u'三级通用标签',
                u'三级分类同义词',
                u'三级分类近义词',
                u'映射新标签-三级分类ID',
                u'映射新标签-三级分类'
                ]
        for col in range(len(head)):
            excel_active.cell(row=1, column=col + 1).value = head[col]
        record_count = 0
        for index1, tag in enumerate(tag_list):
            list_data = []
            # 查找三级分类近义词
            try:
                attrTag = AttrTag.objects.filter(name=tag.name)
                homoionym = ",".join([i.homoionym for i in attrTag]) if attrTag.count() != 0 else ''
            except AttrTag.DoesNotExist:
                homoionym = ""
            # 同义词
            try:
                attrTagSynonym = AttrTagSynonym.objects.filter(tag_attr_id=tag.id)
                synonym = ",".join([i.name for i in attrTagSynonym]) if attrTagSynonym.count() != 0 else ''
            except AttrTagSynonym.DoesNotExist:
                synonym = ""
            # 查找映射新标签
            new_tag_id = self.old_new_id_map.get(tag.id, "")
            if new_tag_id:
                new_tag_name = self.new_tag_id2tag_name.get(new_tag_id, "")
            else:
                new_tag_name = ""
            try:
                seconed_type = TagRelation.objects.filter(child_id=tag.id)
                if not seconed_type.first():
                    list_data.append({
                        'first_type_id': "",
                        'first_type_name': "",
                        'seconed_type_id': "",
                        'seconed_type_name': "",
                        'id': tag.id,
                        'name': tag.name,
                        "homoionym": homoionym,
                        "synonym": synonym,
                        "new_tag_id": new_tag_id,
                        "new_tag_name": new_tag_name
                    })
                    continue
                for second in seconed_type:
                    # 确认是否有二级分类
                    if second.parent.tag_type != TAG_TYPE.BODY_PART_SUB_ITEM:
                        continue
                    first_type = TagRelation.objects.filter(child_id=second.parent.id)
                    if not first_type.first():
                        list_data.append({
                            'first_type_id': "",
                            'first_type_name': "",
                            'seconed_type_id': second.parent.id,
                            'seconed_type_name':second.parent.name ,
                            'id': tag.id,
                            'name': tag.name,
                            "homoionym": homoionym,
                            "synonym": synonym,
                            "new_tag_id": new_tag_id,
                            "new_tag_name": new_tag_name
                        })
                    for first in first_type:
                        third_dic = {}
                        # 说明没有一级分类
                        if first.parent.tag_type != TAG_TYPE.BODY_PART:
                            continue
                        third_dic['first_type_id'] = first.parent.id
                        third_dic['first_type_name'] = first.parent.name
                        third_dic['seconed_type_id'] = second.parent.id
                        third_dic['seconed_type_name'] = second.parent.name
                        third_dic['id'] = tag.id
                        third_dic['name'] = tag.name
                        third_dic["homoionym"] = homoionym
                        third_dic["synonym"] = synonym
                        third_dic["new_tag_id"] = new_tag_id
                        third_dic["new_tag_name"] = new_tag_name
                        list_data.append(third_dic)
                for index, dt in enumerate(list_data):
                    excel_active.cell(row=record_count + index + 2, column=1).value = dt['first_type_id']
                    excel_active.cell(row=record_count + index + 2, column=2).value = dt['first_type_name']
                    excel_active.cell(row=record_count + index + 2, column=3).value = dt['seconed_type_id']
                    excel_active.cell(row=record_count + index + 2, column=4).value = dt['seconed_type_name']
                    excel_active.cell(row=record_count + index + 2, column=5).value = dt['id']
                    excel_active.cell(row=record_count + index + 2, column=6).value = dt['name']
                    excel_active.cell(row=record_count + index + 2, column=7).value = dt['homoionym']
                    excel_active.cell(row=record_count + index + 2, column=8).value = dt['synonym']
                    excel_active.cell(row=record_count + index + 2, column=9).value = dt['new_tag_id']
                    excel_active.cell(row=record_count + index + 2, column=10).value = dt['new_tag_name']
                record_count = len(list_data) + record_count
            except Exception, ex:
                print("error.log", 'tag_id :%s,error:%s' % (str(tag.id), str(ex)))
            excel.save(filename='老标签.xlsx')
        print '******************************文件名为老标签.xlsx导出完成 请将文件交给开发许国亮******************************'

    def export_new(self):
        all_tag_v3 = TagV3.objects.filter(tag_type=TAG_V3_TYPE.NORMAL)
        excel = Workbook()
        excel_active = excel.get_active_sheet()
        excel_active.title = 'tag_new'
        head = [u'一级分类ID',
                u'一级分类',
                u'二级分类ID',
                u'二级分类',
                u'三级通用标签（新）ID',
                u'三级通用标签（新）',
                u'三级分类同义词',
                u'三级分类近义词',
                u'映射老标签-三级分类ID',
                u'映射老标签-三级分类'
                ]
        for col in range(len(head)):
            excel_active.cell(row=1, column=col + 1).value = head[col]
        record_count = 0
        for index1, tag in enumerate(all_tag_v3):
            list_data = []
            # 查找三级分类近义词
            homoionym = ",".join(tag.homoionym)if tag.homoionym else ""
            # 同义词
            try:
                attrTagSynonym = TagSynonym.objects.filter(tag_id=tag.id)
                synonym = ",".join([i.name for i in attrTagSynonym]) if attrTagSynonym.count() != 0 else ''
            except AttrTagSynonym.DoesNotExist:
                synonym = ""
            # 查找映射老标签
            old_tag_id = self.new_old_id_map.get(tag.id)
            if old_tag_id:
                old_tag_name = self.old_tag_id2tag_name.get(old_tag_id)
            else:
                old_tag_name = ""
            try:
                seconed_type = TagV3Relation.objects.filter(child_id=tag.id)
                if not seconed_type.first():
                    list_data.append({
                        'first_type_id': "",
                        'first_type_name': "",
                        'seconed_type_id': "",
                        'seconed_type_name': "",
                        'id': tag.id,
                        'name': tag.name,
                        "homoionym": homoionym,
                        "synonym": synonym,
                        "old_tag_id": old_tag_id,
                        "old_tag_name": old_tag_name
                    })
                    continue
                for second in seconed_type:
                    # 确认是否有二级分类
                    if second.parent.tag_type != TAG_V3_TYPE.SECOND_CLASSIFY:
                        continue
                    first_type = TagV3Relation.objects.filter(child_id=second.parent.id)
                    if not first_type.first():
                        list_data.append({
                            'first_type_id': "",
                            'first_type_name': "",
                            'seconed_type_id': second.parent.id,
                            'seconed_type_name':second.parent.name ,
                            'id': tag.id,
                            'name': tag.name,
                            "homoionym": homoionym,
                            "synonym": synonym,
                             "old_tag_id": old_tag_id,
                        "old_tag_name": old_tag_name
                        })
                    for first in first_type:
                        third_dic = {}
                        # 说明没有一级分类
                        if first.parent.tag_type != TAG_V3_TYPE.FIRST_CLASSIFY:
                            continue
                        third_dic['first_type_id'] = first.parent.id
                        third_dic['first_type_name'] = first.parent.name
                        third_dic['seconed_type_id'] = second.parent.id
                        third_dic['seconed_type_name'] = second.parent.name
                        third_dic['id'] = tag.id
                        third_dic['name'] = tag.name
                        third_dic["homoionym"] = homoionym
                        third_dic["synonym"] = synonym
                        third_dic["old_tag_id"] = old_tag_id
                        third_dic["old_tag_name"] = old_tag_name
                        list_data.append(third_dic)
                for index, dt in enumerate(list_data):
                    excel_active.cell(row=record_count + index + 2, column=1).value = dt['first_type_id']
                    excel_active.cell(row=record_count + index + 2, column=2).value = dt['first_type_name']
                    excel_active.cell(row=record_count + index + 2, column=3).value = dt['seconed_type_id']
                    excel_active.cell(row=record_count + index + 2, column=4).value = dt['seconed_type_name']
                    excel_active.cell(row=record_count + index + 2, column=5).value = dt['id']
                    excel_active.cell(row=record_count + index + 2, column=6).value = dt['name']
                    excel_active.cell(row=record_count + index + 2, column=7).value = dt['homoionym']
                    excel_active.cell(row=record_count + index + 2, column=8).value = dt['synonym']
                    excel_active.cell(row=record_count + index + 2, column=9).value = dt['old_tag_id']
                    excel_active.cell(row=record_count + index + 2, column=10).value = dt['old_tag_name']
                record_count = len(list_data) + record_count
            except Exception, ex:
                print("error.log", 'tag_id :%s,error:%s' % (str(tag.id), str(ex)))
        excel.save(filename='新标签.xlsx')
        print '******************************文件名为新标签.xlsx导出完成 请将文件交给开发许国亮******************************'



