# coding=utf-8

import os

from django.core.management import BaseCommand

import tablib

from talos.libs.image_utils import get_full_path
from api.models import Problem, Order, Person
from talos.models.diary.diary import Diary
from api.models import Service, ServiceItem, User
from api.models import Hospital, Doctor
from answer.models import Question, Answer

from gm_types.gaia import TOPIC_TYPE


def save_json(func):
    file_name = {
        'data_diary': u'日记本',
        'data_problem': u'日记',
        'data_doctor': u'医生',
        'data_hospital': u'医院',
        'data_question': u'问题',
        'data_answer': u'回答',
        'data_article': u'专栏',
        'data_spu': u'spu',
        'data_sku': u'sku',
        'data_user': u'用户',
    }
    directory = u'data_export'

    if not os.path.exists(directory):
        os.makedirs(directory)

    def _wrap(*args, **kwargs):
        dataset, result = func(*args, **kwargs)
        fname = u'./{}/{}.'.format(directory, file_name[func.__name__])
        with open(fname+'json', 'w') as f:
            f.write(dataset.json)
        with open(fname+'csv', 'w') as f:
            f.write(dataset.csv)
        return result
    return _wrap


class Command(BaseCommand):
    """
    给百度数据，包括
    日记本 日记 用户 医生 医院 SPU SKU 专栏 问题 回答
    """
    head_doctor = [
        '医生ID', '头像', '姓名', '职称', '所在医院', '医院ID', '执业年限',
        '擅长项目', '临床经验', '简介', '是否核验', '是否认证', '执业医师编码',
        '身份证号', '医生资格证图片', '医生执业证图片', '医生荣誉图片',
        '医生相册url', '中整协认证信息', '是否购买医责险', '保险ID', '数据来源'
    ]

    head_hospital = [
        '医院ID', '业务类型', 'logo图', '头图', '医院名称', '别名',
        '医院类型', '省', '市', '地址', '经度', '纬度', '医院相册地址',
        '医院介绍', '医院荣誉', '医疗执业许可证', '中整协认证信息', '是否核验',
        '是否认证', '联系电话', '门诊时间', '数据来源'
    ]

    head_user = [
        'UID', 'passid', '头像', '昵称', '用户名', '性别',
        '年龄', '所在城市', '用户来源', '注册时间'
    ]

    head_question = [
        '问题ID', '问题标题', '问题详情', '发布时间', '数据来源'
    ]

    head_answer = [
        '答案ID', '问题ID', '答案详情', '发布时间', '数据来源'
    ]

    head_article = [
        '文章ID', '标题', '发布时间', '展现来源', '发布机构', '机构ID',
        '发布作者', '作者ID', '正文', '标签', '卡片标题', '卡片图片（支持多图）',
        '卡片摘要', '数据来源'
    ]

    head_diary = [
        '日记一级ID', '日记一级发布时间',
        '术前描述', '术前照片', '术后恢复时间', '术后描述', '术后照片', '数据来源',
        '当前SKU名称', '当前SKUID', '患者UID', '手术时间',
        '就诊医院', '就诊医院ID', '主刀医生', '主刀医生ID'
    ]

    head_problem = [
        '日记二级ID', '日记一级ID', '日记二级发布时间', '发布类型', '卡片标题',
        '卡片图片（支持多图）', '卡片摘要', '数据来源'
    ]

    head_spu = [
        'SPUID', 'SPU标题', '图集url', '手术医生', '手术医生ID', '就诊医院', '就诊医院ID',
        '产品详情', '服务保障', '数据来源'
    ]

    head_sku = [
        'SKUID', 'SPUID', 'SKU标题', '图片url', '原价', '优惠价', '预约金',
        '支付方式', '数据来源'
    ]

    all_data = False

    @save_json
    def data_diary(self):
        print('....diary....')
        data = tablib.Dataset()
        data.headers = self.head_diary
        queryset = Diary.objects.filter(is_online=True, topics__isnull=False).order_by('-id')
        if not self.all_data:
            queryset = queryset[:100]
        for diary in queryset:
            order = Order.objects.filter(id=diary.order_id).first()
            if order:
                order_data = [
                    order.service_item_key,
                    order.service_item_id,
                    order.user.person.id.hex,
                    str(order.validate_time or ''),
                    order.service.doctor.hospital.name,
                    order.service.doctor.hospital.id,
                    order.service.doctor.name,
                    order.service.doctor.id,
                ]
            else:
                order_data = [""]*8
            row = [
                    diary.id,
                    str(diary.created_time),
                    "", get_full_path(diary.pre_operation_image, '-w'),
                    "", "", get_full_path(diary.post_operation_image, '-w'),
                    u"更美"
                ] + order_data
            data.append(row)
        return data, [x.id for x in queryset]

    @save_json
    def data_problem(self, diary_ids=[]):
        print('....problem....')
        data = tablib.Dataset()
        data.headers = self.head_problem
        queryset = Problem.objects.filter(topic_type=TOPIC_TYPE.SHARE)
        if not self.all_data:
            queryset = queryset.filter(diary_id__in=diary_ids)
        for problem in queryset:
            row = [
                problem.id,
                problem.diary_id,
                str(problem.created_time),
                "UGC",
                problem.get_title(),
                [get_full_path(x.image_url, '-w') for x in problem.images.all()],
                problem.content[:200],
                u"更美"
            ]
            data.append(row)
        return data, None

    @save_json
    def data_user(self, diary_ids=[]):
        print('....user....')
        data = tablib.Dataset()
        data.headers = self.head_user
        queryset = Person.objects.all()
        if not self.all_data:
            user_ids = Diary.objects.filter(id__in=diary_ids).values_list('user_id', flat=True)
            # FXXK DJANGO 不改动一下user_ids 就会联表diary查询
            queryset = queryset.filter(user_id__in=user_ids[::-1])
        for person in queryset:
            _data = person.data()
            row = [
                _data['id'],
                '',
                get_full_path(_data['portrait'], '-w'),
                _data['nickname'],
                '', '', '', '', u'更美', ''
            ]
            data.append(row)
        return data, None

    @save_json
    def data_doctor(self, diary_ids=[]):
        print('....doctor....')
        data = tablib.Dataset()
        data.headers = self.head_doctor
        queryset = Doctor.objects.all()
        if not self.all_data:
            doctor_ids = Diary.objects.filter(id__in=diary_ids).values_list('doctor_id', flat=True)
            queryset = queryset.filter(id__in=doctor_ids[::-1])
        from gm_types.doctor import DOCTOR_TITLE_TYPE
        for doctor in queryset:
            extra = doctor.extra_info or {}
            row = [
                doctor.id,
                doctor.portrait,
                doctor.name,
                DOCTOR_TITLE_TYPE.getDesc(doctor.title),
                doctor.hospital.name,
                doctor.hospital_id,
                "",
                doctor.good_at,
                "",
                doctor.introduction,
                "",
                "",
                extra.get('professional_certificate_num', ''),
                "", # 身份证号
                doctor.b_licences,
                doctor.p_licences,
                "",
                doctor.personalized_photo_album,
                "",
                "",
                "",
                "更美",
            ]
            data.append(row)
        return data, None

    @save_json
    def data_hospital(self, diary_ids=[]):
        print('....hospital....')
        data = tablib.Dataset()
        data.headers = self.head_hospital
        queryset = Hospital.objects.all()
        if not self.all_data:
            doctor_ids = Diary.objects.filter(id__in=diary_ids).values_list('doctor_id', flat=True)
            queryset = queryset.filter(doctor_hospital__in=doctor_ids[::-1]).distinct()
        from gm_types.doctor import HOSPITAL_MEDICAL_TYPE
        from gm_types.gaia import HOSPITAL_TYPE
        for hospital in queryset:
            extra = getattr(hospital, 'hospital_extra', None)
            row = [
                hospital.id,
                HOSPITAL_MEDICAL_TYPE.getDesc(extra.hospital_type) if extra else '',
                "",
                hospital.get_hospital_portrait(),
                hospital.name,
                "",
                HOSPITAL_TYPE.getDesc(hospital.hospital_type),
                hospital.city.province.name,
                hospital.city.name,
                hospital.location,
                hospital.baidu_loc_lng,
                hospital.baidu_loc_lat,
                "",
                hospital.description,
                "",
                hospital.p_licences,
                "",
                "",
                "",
                hospital.desk_phone,
                "",
                "更美"
            ]
            data.append(row)
        return data, None

    @save_json
    def data_spu(self, diary_ids=[]):
        print('....spu....')
        data = tablib.Dataset()
        data.headers = self.head_spu
        queryset = Service.objects.all()
        if not self.all_data:
            service_ids = Diary.objects.filter(id__in=diary_ids).values_list('service_id', flat=True)
            queryset = queryset.filter(id__in=service_ids[::-1])
        for service in queryset:
            row = [
                service.id,
                service.show_name,
                service.image_detail,
                service.doctor.name,
                service.doctor_id,
                service.doctor.hospital.name,
                service.doctor.hospital_id,
                service.detail_description,
                "随时退" if service.refund_anytime else "",
                "更美"
            ]
            data.append(row)
        return data, None

    @save_json
    def data_sku(self, diary_ids=[]):
        print('....sku....')
        data = tablib.Dataset()
        data.headers = self.head_sku
        queryset = ServiceItem.objects.all()
        if not self.all_data:
            service_ids = Diary.objects.filter(id__in=diary_ids).values_list('service_id', flat=True)
            queryset = queryset.filter(service__in=service_ids[::-1]).distinct()
        for item in queryset:
            row = [
                item.id,
                item.service.id,
                item.key,
                "",
                item.original_price,
                item.gengmei_price,
                item.pre_payment_price,
                ["支付全款", "支付预约金"][bool(item.pre_payment_price)],
                "更美"
            ]
            data.append(row)
        return data, None

    @save_json
    def data_article(self):
        print('....article....')
        data = tablib.Dataset()
        data.headers = self.head_article
        queryset = Problem.objects.filter(topic_type=TOPIC_TYPE.COLUMN_ARTICLE).order_by('-id')
        from api.models import Tag
        if not self.all_data:
            queryset = queryset[:100]
        for article in queryset:
            row = [
                article.id,
                article.get_title(),
                str(article.created_time),
                "更美", "更美", "更美", "更美", "更美",
                article.answer_richtext,
                [x.name for x in Tag.objects.filter(id__in=article.tag_ids)],
                article.get_title(),
                [get_full_path(x.image_url, '-w') for x in article.images.all()],
                article.answer_richtext[:200],
                "更美"
            ]
            data.append(row)
        return data, None

    @save_json
    def data_question(self):
        print('....question....')
        data = tablib.Dataset()
        data.headers = self.head_question
        queryset = Question.objects.all()
        if not self.all_data:
            queryset = queryset[:50]
        for question in queryset:
            row = [
                question.id,
                question.title,
                question.content,
                str(question.create_time),
                '更美'
            ]
            data.append(row)
        return data, [x.id for x in queryset]

    @save_json
    def data_answer(self, question_ids=[]):
        print('....answer....')
        data = tablib.Dataset()
        data.headers = self.head_answer
        queryset = Answer.objects.all()
        if not self.all_data:
            queryset = queryset.filter(question__in=question_ids).distinct()
        for answer in queryset:
            row = [
                answer.id,
                answer.question_id,
                answer.content,
                str(answer.create_time),
                '更美'
            ]
            data.append(row)
        return data, None

    def handle(self, *args, **options):
        """

        :param args:
        :param options:
        :return:
        """
        diary_ids = self.data_diary()
        self.data_problem(diary_ids)
        self.data_user(diary_ids)
        self.data_doctor(diary_ids)
        self.data_hospital(diary_ids)
        self.data_spu(diary_ids)
        self.data_sku(diary_ids)
        self.data_article()
        question_ids = self.data_question()
        self.data_answer(question_ids)
