#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
#   Author  :   zhangxiaolin
#   E-mail  :   petelin1120@gmail.com
#   Date    :   17/6/27 18:23
#   Desc    :   补单相关
import json

from django.db.models import Q
from gm_types.gaia import DOCTOR_TYPE, BUDAN_STATUS, HERA_OPERATE_LOG_ACTION, BUDAN_OPERATE, BUDAN_OPERATOR
from gm_dataquery.db import DB

from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from api.tool.verification_code import VerifiedCode
from api.tool.datetime_tool import get_timestamp_epoch, get_timestamp
from api.models import VERIFY_CODE_TYPE, BuDan, OrderExtra, Order
from api.models import Doctor, Reservation, RESERVATION_STATUS, DoctorAccount


class BuDanDB(DataBuilder):
    def getval_id(self, obj):
        return int(obj.id)

    def getval_appeal_conversation(self, obj):
        result = []
        for record in obj.records.order_by('-create_time').all():
            result.append({
                "message": record.message,
                "create_time": get_timestamp(record.create_time),
                "role": record.role,
                "user_name": record.user.get_full_name(),
                "operate": dict(BUDAN_OPERATE)[int(record.operate)],
            })
        return result

    def getval_dev_projects_json(self, obj):
        return json.loads(obj.dev_projects)

    def getval_create_time(self, obj):
        return obj.create_time.strftime("%Y-%m-%d %H:%M:%S")

    def getval_happen_time(self, obj):
        return obj.happen_time.strftime("%Y-%m-%d %H:%M:%S")

    def getval_related_order_data(self, obj):
        from api.models.budan import BuDanRealtedOrder
        related_order_ids = BuDanRealtedOrder.get_order_ids_by_budan_id(obj.id)
        if related_order_ids:
            return BuDanRealtedOrder.batch_get_to_dict_data_by_order_ids(related_order_ids)
        return []

    def getval_create_user__username(self, obj):
        return obj.create_user.username

    def getval_business_partener_name(self, obj):
        return obj.doctor.business_partener.username


@DB
class BuDanDQ(DataSQLQuery):
    model = BuDan
    data_model = BuDanDB

    def filter_create_time(self, srch_key, srch_val, regex):
        return self._qry_time_range(srch_key, srch_val, regex)

    def filter_revocation_time(self, srch_key, srch_val, regex):
        return self._qry_time_range(srch_key, srch_val, regex)
