# -*- coding: UTF-8 -*-

from hippo.models import *
from gm_dataquery.dataquery import DataSQLQuery, DataBuilder
from gm_dataquery.db import DB

from hippo.views.advertise import is_deal


@DB
class  Advertise_pv_statsDQ(DataSQLQuery):
    model =  Advertise_pv_stats

    def filter_doctor_id(self, srch_key, srch_val, regex=False):
        doctors = Doctor.objects.filter(hospital__hospital_type=HOSPITAL_TYPE.PRIVATE) \
            .values_list('id', flat=True)
        if srch_val:
            merchant = Merchant.objects.filter(doctor_id=srch_val,is_online=True).first()
        return Q(merchant_id=merchant.id)


class Advertise_conver_statsDB(DataBuilder):
    def getval_is_handled(self, item):
        return is_deal(item.id)


@DB
class Advertise_conver_statsDQ(DataSQLQuery):
    model = Advertise_conver_stats
    data_model = Advertise_conver_statsDB

    def filter_doctor_id(self, srch_key, srch_val, regex=False):
        if srch_val:
            merchant = Merchant.objects.filter(doctor_id=srch_val,is_online=True).first()
        return Q(merchant_id=merchant.id)


@DB
class AdWhiteListDQ(DataSQLQuery):
    model = AdWhiteList

    def filter_created_time(self, srch_key, srch_val, regex=False):
        return self._qry_time_range(srch_key, srch_val, regex)

    def update(self, updates, **kwargs):
        length = len(kwargs)
        id = kwargs.get('id')
        AdWhiteList.objects.get(id=int(id)).delete()
        return {'id': length}

    def create(self, **kwargs):
        city = kwargs.get('city')
        doctor_id = kwargs.get('doctor_id')
        if city:
            hospitals = Hospital.objects.filter(city=city[0]).values_list('id', flat=True)
            if hospitals:
                for hos in hospitals:
                    doctors = Doctor.objects.filter(hospital=hos, is_merchant=True, is_online=True).values_list('id', flat=True)
                    if doctors:
                        for doc_id in doctors:
                            _ = AdWhiteList.objects.get_or_create(doctor_id=doc_id)
        if doctor_id:
            doctors = Doctor.objects.filter(id=doctor_id, is_merchant=True, is_online=True).values_list('id', flat=True)
            for doc_id in doctors:
                _ = AdWhiteList.objects.get_or_create(doctor_id=doc_id)
        return {'id': len(kwargs)}

