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

from django.db.models import Q

from gm_types.doctor import AGREEMENT_IMG_TYPE, BILL_INFO_TYPE
from gm_types.doctor import AGREEMENT_RECORD_STATUS

from gm_dataquery.dataquery import DataSQLQuery, DataBuilder
from gm_dataquery.db import DB
from gm_dataquery.dict_mixin import to_dict

from hippo.models import Merchant, MerchantAccount, MerchantBillInfo
from hippo.models import MerchantAgreement, MerchantAgreementRecord
from hippo.models import MerchantLicense, MerchantAgreementImg
from hippo.models import MerchantAgreementRecordImg
from hippo.models import MerchantRelatedInfo

from rpc.exceptions import UniError
from themis.models import Team
from api.models import User


class MerchantDB(DataBuilder):

    def getval_doctors(self, item):
        return [x.doctor_id for x in item.merchant_doctors.all()]

    def getval_team_name(self, item):
        team_id = item.doctor.business_group
        if not team_id:
            return ''
        team = Team.objects.filter(id=team_id).first()
        if not team:
            return ''
        return team.name

    def getval_id(self, item):
        return str(item.id)

    def getval_invoice_head(self, item):
        info_type = item.billinfo.info_type
        if info_type == BILL_INFO_TYPE.NORMAL:
            return item.agreement.first_company_name
        elif info_type == BILL_INFO_TYPE.HANDLER:
            return item.agreement.first_hosting_company_name
        else:
            return ''

    def getval_tax_number(self, item):
        info_type = item.billinfo.info_type
        if info_type == BILL_INFO_TYPE.NORMAL:
            return item.agreement.first_company_number
        elif info_type == BILL_INFO_TYPE.HANDLER:
            return item.agreement.first_hosting_company_number
        else:
            return ''

    def getval_has_agreement_to_audit(self, item):
        return item.agreement_records.filter(status=AGREEMENT_RECORD_STATUS.TODO).count()

    def getval_business_partener(self, item):
        return item.doctor.business_partener.id

    def getval_business_group(self, item):
        team_id = item.doctor.business_group
        return team_id if team_id else ''

    def getval_merchant_score(self,item):
        return '%.2f' % item.merchant_score

    def getval_advertise_score(self,item):
        return '%.2f' % item.advertise_score

    def getval_verify_gmv_score(self,item):
        return '%.2f' % item.verify_gmv_score


@DB
class MerchantDQ(DataSQLQuery):
    model = Merchant
    data_model = MerchantDB

    def filter_teams_team_id(self, key, value, regex=False):
        team = Team.objects.filter(id=value).first()
        if not team:
            return Q()
        team_ids = [team.id] + [x.id for x in team.all_children_team]
        return Q(doctor__business_group__in=team_ids)

    def filter_teams_user_id(self, key, value, regex=False):
        if not value:
            return Q()
        teams = User.objects.get(id=value).teams.all()
        children = sum([list(x.all_children_team) + [x] for x in teams], [])
        return Q(doctor__business_group__in=[x.id for x in children])


class MerchantAccountDB(DataBuilder):
    def getval_country_name(self, item):
        return '中国'

    def getval_province_name(self, item):
        return item.city_finance.province.name

    def getval_city_name(self, item):
        return item.city_finance.name

    def getval_subbranch(self, item):
        return item.subbranch or ''


@DB
class MerchantAccountDQ(DataSQLQuery):
    model = MerchantAccount
    data_model = MerchantAccountDB


class MerchantBillInfoDB(DataBuilder):

    def getval_invoice_head(self, item):
        if item.info_type == BILL_INFO_TYPE.NORMAL:
            return item.merchant.agreement.first_company_name
        elif item.info_type == BILL_INFO_TYPE.HANDLER:
            return item.merchant.agreement.first_hosting_company_name
        else:
            return ''

    def getval_tax_number(self, item):
        if item.info_type == BILL_INFO_TYPE.NORMAL:
            return item.merchant.agreement.first_company_number
        elif item.info_type == BILL_INFO_TYPE.HANDLER:
            return item.merchant.agreement.first_hosting_company_number
        else:
            return ''


@DB
class MerchantBillInfoDQ(DataSQLQuery):
    model = MerchantBillInfo
    data_model = MerchantBillInfoDB

    def create(self, **kwargs):
        business_group = kwargs.pop('business_group', '')
        business_partener = kwargs.pop("business_partener", '')
        return DataSQLQuery.create(self, **kwargs)

    def update(self, updates, **kwargs):
        business_group = updates.pop('business_group', '')
        business_partener = updates.pop("business_partener", '')
        return super(MerchantBillInfoDQ.sqlquery, self).update(updates, **kwargs)


class MerchantAgreementDB(DataBuilder):

    def getval_agreement_images(self, item):
        return [x.img_url for x in item.img.filter(img_type=AGREEMENT_IMG_TYPE.AGREEMENT)]

    def getval_hosting_images(self, item):
        return [x.img_url for x in item.img.filter(img_type=AGREEMENT_IMG_TYPE.HOSTING)]


@DB
class MerchantAgreementDQ(DataSQLQuery):
    model = MerchantAgreement
    data_model = MerchantAgreementDB


class MerchantAgreementRecordDB(MerchantAgreementDB):
    def getval_merchant_id(self, item):
        return str(item.merchant_id)


@DB
class MerchantAgreementRecordDQ(DataSQLQuery):
    model = MerchantAgreementRecord
    data_model = MerchantAgreementRecordDB

    def create(self, **kwargs):
        if not kwargs['merchant_id']:
            raise UniError('需要指定商户')
        agreement_images = kwargs.pop('agreement_images', [])
        hosting_images = kwargs.pop('hosting_images', [])
        record = self.model.objects.create(**kwargs)
        for image in agreement_images:
            MerchantAgreementRecordImg.objects.create(
                record=record,
                img_url=image,
                img_type=AGREEMENT_IMG_TYPE.AGREEMENT
            )

        for image in hosting_images:
            MerchantAgreementRecordImg.objects.create(
                record=record,
                img_url=image,
                img_type=AGREEMENT_IMG_TYPE.HOSTING
            )
        return to_dict(record)

    def update(self, updates, **kwargs):
        record = MerchantAgreementRecord.objects.filter(**kwargs).first()
        if not record:
            raise UniError(u'未找到相关合同申请')
        if record.status != AGREEMENT_RECORD_STATUS.TODO:
            raise UniError(u'状态必须为审核中')
        approve = updates.pop('approve')
        if approve:
            updates['status'] = AGREEMENT_RECORD_STATUS.APPROVE
        else:
            updates['status'] = AGREEMENT_RECORD_STATUS.REJECT
        result = super(MerchantAgreementRecordDQ.sqlquery, self).update(updates, **kwargs)
        if approve:
            record.record_approve(**kwargs)
        return result


class MerchantLicenseDB(DataBuilder):
    def getval_lincense_end_time(self, item):
        if not item.lincense_end_time:
            return u'长期'
        return str(item.lincense_end_time)


@DB
class MerchantLicenseDQ(DataSQLQuery):
    model = MerchantLicense
    data_model = MerchantLicenseDB


class MerchantRelatedInfoDB(DataBuilder):
    def getval_name(self,obj):
        return obj.doctor.name
    def getval_business_area(self, obj):
        try:
            team_name = Team.objects.get(id=obj.doctor.business_group).name
        except:
            team_name = ''
        return team_name
    def getval_business(self,obj):
        try:
            name = obj.doctor.business_partener.last_name
        except:
            name = ''
        return name

    def getval_related1(self, obj):
        infos = MerchantRelatedInfo.objects.filter(merchant=obj)
        if len(infos)>0:
            return u'{}/{}/{}'.format(infos[0].name,infos[0].role,infos[0].phone)
        else:
            return ''
    def getval_related2(self, obj):
        infos = MerchantRelatedInfo.objects.filter(merchant=obj)
        if len(infos)>1:
            return u'{}/{}/{}'.format(infos[1].name,infos[1].role,infos[1].phone)
        else:
            return ''
    def getval_related3(self, obj):
        infos = MerchantRelatedInfo.objects.filter(merchant=obj)
        if len(infos)>2:
            return u'{}/{}/{}'.format(infos[2].name,infos[2].role,infos[2].phone)
        else:
            return ''


class MerchantRelatedInfoDQ(DataSQLQuery):
    model = Merchant
    data_model = MerchantRelatedInfoDB

    def filter_name(self, key, value, regex=False):
        return Q(name=value)


    def filter_business_area(self, key, value, regex=False):
        team = Team.objects.get(id=value)
        children = list(team.all_children_team)
        team_ids = [x.id for x in children] + [team.id]
        return Q(doctor__business_group__in=team_ids)

    def filter_business(self,key, value, regex=False):
        return Q(doctor__business_partener__id=value)