# coding: utf-8

import json
import os
import tablib

from django.core.management import BaseCommand

from gm_types.gaia import TAG_TYPE_ATTR, TAG_V3_TYPE

from api.models.tag import Tag
from agile.models.tag import (
	AttrTag,
	TagV3,
	TagExtra,
	TagMapTag,
	TagV3Relation,
	TagV3MapAttrTag,
	TagV3WikiRelation,
	TagCategory,
	TagSynonym,
	TagCategoryMapTag,
	TagMapOldTag,
)


def use_pandas_to_excel(data_list, filepath, sheet_name, header):
	dt1 = tablib.Dataset(title=sheet_name)
	dt1.headers = header
	for data in data_list:
		data_rows = [data[h] for h in header]
		dt1.append(data_rows)
	open(filepath, 'wb').write(dt1.xlsx)


def query_table_about_tag_v3_detail(filepath):
	columns = {
		"name": "新标签",
		"category_name": "分类",
		"id": "id",
		"is_display": "is_display",
		"is_online": "is_online",
		"homoionym": "近义词",
		"synonym_name": "同义词",
		"first_solutions": "1级方式",
		"second_solutions": "1级耗材",
		"first_demands": "1级诉求",
		"second_demands": "2级诉求",
		"first_positions": "1级部位",
		"second_positions": "2级部位",
		"old_tag_name": "关联老标签",
		"old_tag_id": "老标签id",
	}
	header = [
		"新标签",
		"分类",
		"id",
		"is_display",
		"is_online",
		"近义词",
		"同义词",
		"1级方式",
		"1级耗材",
		"1级诉求",
		"2级诉求",
		"1级部位",
		"2级部位",
		"关联老标签",
		"老标签id"
	]
	all_tag_v3 = TagV3.objects.filter().all()
	all_tag_v3_ids = [t.id for t in all_tag_v3]

	# 同义词
	tag_synonyms = TagSynonym.objects.filter(tag_id__in=all_tag_v3_ids)
	tag_v3_ids2synonyms = dict()
	for tag_synonym in tag_synonyms:
		tag_v3_ids2synonyms.setdefault(tag_synonym.tag_id, []).append(tag_synonym.name)

	# 标签属性
	tag_v3_id2tag_attr_ids = dict()
	all_tag_attr_ids = set()
	tag_v3_attr_infos = TagV3MapAttrTag.objects.filter(
		tag_id__in=all_tag_v3_ids,
		is_online=1
	)
	for tag_v3_attr in tag_v3_attr_infos:
		tag_v3_id2tag_attr_ids.setdefault(
			tag_v3_attr.tag_id, []
		).append(tag_v3_attr.tag_attr_id)
		all_tag_attr_ids.add(tag_v3_attr.tag_attr_id)

	tag_attrs = AttrTag.objects.filter(id__in=list(all_tag_attr_ids))
	tag_attr_id2attr_info = dict()
	for tag_attr in tag_attrs:
		tag_attr_info = dict()
		tag_attr_info["name"] = tag_attr.name
		tag_attr_info["aggregate_type"] = tag_attr.aggregate_type
		tag_attr_id2attr_info[tag_attr.id] = tag_attr_info

	tag_id2tag_attr_info = dict()
	for tag_v3_id, tag_attr_ids in tag_v3_id2tag_attr_ids.items():
		tag_attr_detail = dict()
		for tag_attr_id in tag_attr_ids:
			tag_attr_info = tag_attr_id2attr_info.get(tag_attr_id, {})
			if not tag_attr_info:
				continue

			if tag_attr_info["aggregate_type"] == TAG_TYPE_ATTR.MODE:
				tag_attr_detail["second_solutions"] = tag_attr_info["name"]
			elif tag_attr_info["aggregate_type"] == TAG_TYPE_ATTR.MACROSCOPIC_MODE:
				tag_attr_detail["first_solutions"] = tag_attr_info["name"]
			elif tag_attr_info["aggregate_type"] == TAG_TYPE_ATTR.FIRST_APPEAL:
				tag_attr_detail["first_demands"] = tag_attr_info["name"]
			elif tag_attr_info["aggregate_type"] == TAG_TYPE_ATTR.SECOND_APPEAL:
				tag_attr_detail["second_demands"] = tag_attr_info["name"]
			elif tag_attr_info["aggregate_type"] == TAG_TYPE_ATTR.FIRST_POSITION:
				tag_attr_detail["first_positions"] = tag_attr_info["name"]
			elif tag_attr_info["aggregate_type"] == TAG_TYPE_ATTR.POSITION:
				tag_attr_detail["second_positions"] = tag_attr_info["name"]

		tag_id2tag_attr_info[tag_v3_id] = tag_attr_detail

	tag_map_old_tags = TagMapOldTag.objects.filter(tag_id__in=all_tag_v3_ids)
	old_tag_ids = set()
	tag_v3_id2old_tag_ids = {}
	for tag_map in tag_map_old_tags:
		tag_v3_id2old_tag_ids.setdefault(tag_map.tag_id, []).append(tag_map.old_tag_id)
		old_tag_ids.add(tag_map.old_tag_id)

	old_tags = Tag.objects.filter(id__in=old_tag_ids)
	old_tag_id2tag_name = {t.id: t.name for t in old_tags}

	tag_category_maps = TagCategoryMapTag.objects.filter(
		tag_id__in=all_tag_v3_ids
	)

	tag_category_ids = set()
	tag_v3_id2tag_category_ids = dict()
	for tag_category_map in tag_category_maps:
		tag_category_ids.add(tag_category_map.tag_category_id)
		tag_v3_id2tag_category_ids.setdefault(
			tag_category_map.tag_id, []
		).append(tag_category_map.tag_category_id)

	tag_categories = TagCategory.objects.filter(id__in=list(tag_category_ids))
	tag_category_id2name = {t.id: t.name for t in tag_categories}

	tag_v3_id2tag_category_name = dict()
	for tag_v3_id, tag_category_ids in tag_v3_id2tag_category_ids.items():
		tag_category_names = list()
		for tag_category_id in tag_category_ids:
			category_name = tag_category_id2name.get(tag_category_id)
			if category_name:
				tag_category_names.append(category_name)
		tag_v3_id2tag_category_name[tag_v3_id] = ",".join(tag_category_names)

	all_tag_details = list()
	for tag_v3 in all_tag_v3:
		tag_detail = dict()
		tag_detail["category_name"] = tag_v3_id2tag_category_name.get(tag_v3.id, "")
		tag_detail["name"] = tag_v3.name
		tag_detail["id"] = tag_v3.id
		tag_detail["is_display"] = tag_v3.is_display
		tag_detail["is_online"] = tag_v3.is_online
		tag_detail["homoionym"] = json.loads(tag_v3.homoionym) if tag_v3.homoionym else ""
		tag_detail["synonym_name"] = tag_v3_ids2synonyms.get(tag_v3.id, [])
		old_tag_ids = tag_v3_id2old_tag_ids.get(tag_v3.id, [])
		tag_detail["old_tag_id"] = old_tag_ids
		tag_detail["old_tag_name"] = [
			old_tag_id2tag_name.get(tid) for tid in old_tag_ids if old_tag_id2tag_name.get(tid)
		]
		tag_detail.update(tag_id2tag_attr_info.get(tag_v3.id, {}))

		for key, new_key in columns.items():
			if key in ["id", "is_online", "is_display"]:
				continue
			values = tag_detail.get(key, [])
			new_values = list()
			if isinstance(values, list):
				for value in values:
					if isinstance(value, int) or isinstance(value, long):
						new_values.append(str(value))
					else:
						new_values.append(value)

			tag_detail[new_key] = ",".join(new_values) if isinstance(values, list) else values
			if key in tag_detail:
				tag_detail.pop(key)
		all_tag_details.append(tag_detail)

	sheet_name = u"新标签相关"
	use_pandas_to_excel(all_tag_details, filepath, sheet_name, header)


def replace_key(detail, columns):
	new_detail = dict()
	for key, value in detail.items():
		new_detail[columns[key]] = value
	return new_detail


def query_repetition_tag_or_category(filepath):
	columns = {
		"tag_id": "新标签id",
		"tag_name": "新标签名称",
		"tag_type": "分类名称",
	}
	header = [
		"新标签id",
		"新标签名称",
		"分类名称",
	]

	all_tag_v3_infos = TagV3.objects.filter()

	id2tv3_info = dict()
	pik_name2ids = dict()
	for t_v3_info in all_tag_v3_infos:
		pik_name = t_v3_info.name + TAG_V3_TYPE.getDesc(t_v3_info.tag_type, "")
		pik_name2ids.setdefault(pik_name, []).append(t_v3_info.id)
		id2tv3_info[t_v3_info.id] = t_v3_info

	tag_details = [{"新标签id": "1", "新标签名称": "1", "分类名称": "1"}]
	for _, tag_v3_ids in pik_name2ids.items():
		if len(tag_v3_ids) < 2:
			continue

		for tag_id in tag_v3_ids:
			tag_info = id2tv3_info.get(tag_id)
			if not tag_info:
				continue

			tag_detail = dict()
			tag_detail["tag_id"] = str(tag_id)
			tag_detail["tag_name"] = tag_info.name
			tag_detail["tag_type"] = TAG_V3_TYPE.getDesc(tag_info.tag_type, "")
			tag_details.append(replace_key(tag_detail, columns))
	sheet_name = u"重复标签"
	if tag_details:
		use_pandas_to_excel(tag_details, filepath, sheet_name, header)
		print u"运行完成，请Copy repetition_tag.xlsx 文件给开发！"
	else:
		print u"运行完成，没有重复标签+分类的数据"


class Command(BaseCommand):
	""" Export tag_v3 to Excel and Format tag_v3 information """

	def handle(self, *args, **options):
		tag_detail_filepath = os.path.join(os.getcwd(), "repetition_tag.xlsx")
		query_repetition_tag_or_category(tag_detail_filepath)
