# coding: utf-8

import tablib

from django.core.management import BaseCommand
from django.conf import settings

from api.models.feedback import FunctionFeedback
from api.models.user_face_image import FaceOneImageV2

func2name = {u"skin": u"测肤", u"face": u"扫脸"}


class Command(BaseCommand):

	def handle(self, *args, **options):
		# 查询 使用从库

		# 查询不准确的 device_ids
		inaccuracy_device_ids = set()
		for function_feedback in FunctionFeedback.objects.using(
				settings.SLAVE_DB_NAME).filter(rank=1, answer=u"不准确"):
			inaccuracy_device_ids.add(function_feedback.device_id)
		print(u"不准确的device_id数量")
		print(len(inaccuracy_device_ids))

		# 查询不准确的原因
		feedback_result = dict()
		for function_feedback in FunctionFeedback.objects.using(
				settings.SLAVE_DB_NAME).filter(device_id__in=list(inaccuracy_device_ids), rank=2):
			feedback_result.setdefault(function_feedback.function, dict())
			feedback_result[function_feedback.function].setdefault(function_feedback.device_id, dict())
			feedback_result[function_feedback.function][function_feedback.device_id][function_feedback.question] = function_feedback.answer
		print(u"不准确的原因查询成功！")

		device_id2face_info = dict()
		faces = FaceOneImageV2.objects.using(settings.SLAVE_DB_NAME).filter(device_id__in=list(inaccuracy_device_ids))
		for face in faces:
			device_id2face_info.setdefault(face.device_id, []).append(
				{"face_id": face.id, "face_url": face.face_url}
			)
		print(u"查询脸部照片成功")

		result = list()
		for func, device2question_answer in feedback_result.items():
			for device_id, question2answer in device2question_answer.items():
				face_info = device_id2face_info.get(device_id, {})
				face_ids = [str(f['face_id']) for f in face_info]
				face_urls = [f['face_url'] for f in face_info]
				for question, answer in question2answer.items():
					device_result = (
						func2name.get(func),
						device_id,
						",".join(face_ids),
						",".join(face_urls),
						question,
						answer
					)
					print(device_result)
					result.append(device_result)

		headers = (u"功能", u"设备id", u"face_ids", u"face_urls", u"问题", u"答案")
		headers = tuple(headers)
		data = tablib.Dataset(*result, headers=headers)
		with open('feedback_url_question_answer.xlsx', 'wb') as f:
			f.write(data.xlsx)
		print(u"完成， 请把生成的Excel文件 feedback_url_question_answer.xlsx 发送给相应开发，谢谢！")