# coding:utf8
from django.db import transaction
from gm_dataquery.db import DB
from django.db.models import Q
from gm_types.error import ERROR
from rpc.exceptions import GaiaRPCFaultException
from gm_dataquery.dataquery import DataSQLQuery, DataBuilder

from hippo.models import SlaveMerchant, MasterMerchant, Merchant


class MasterMerchantDB(DataBuilder):
    def getval_slavemerchant(self, obj):
        slavemerchants = SlaveMerchant.objects.filter(mastermerchant_id=obj.id)
        if slavemerchants.count()>1:
            return u'{}等{}家'.format(slavemerchants.first().slavemerchant.name, slavemerchants.count())
        else:
            return slavemerchants.first().slavemerchant.name


    def getval_slavemerchant_ids(self, obj):
        return list(map(lambda id: str(id),
                        SlaveMerchant.objects.filter(mastermerchant_id=obj.id).values_list('slavemerchant', flat=True)))


@DB
class MasterMerchantDQ(DataSQLQuery):
    model = MasterMerchant
    data_model = MasterMerchantDB

    def filter_slavemerchant_name(self, srch_key, srch_val, regex=False):
        mr = Merchant.objects.filter(name__contains=srch_val).values_list('id', flat=True)
        return Q(slavemerchants__slavemerchant_id__in=mr)

    def filter_mastermerchant_name(self, srch_key, srch_val, regex=False):
        return Q(mastermerchant__name__contains=srch_val)

    def update(self, updates, **kwargs):
        with transaction.atomic():
            action = updates.pop('action', 'keep')
            is_login_related = updates.pop('is_login_related', None)
            is_message_related = updates.pop('is_message_related', None)
            is_operetor_related = updates.pop('is_operetor_related', None)
            is_store_classification = updates.pop('is_store_classification', None)

            if action == 'delete':
                slavemaster_id = kwargs['id']
                SlaveMerchant.objects.filter(id=slavemaster_id).delete()
                self.model.objects.get(**kwargs).delete()
            else:
                master = MasterMerchant.objects.get(id=kwargs['id'])
                if is_login_related != None:
                    master.is_login_related = is_login_related
                if is_message_related != None:
                    master.is_message_related = is_message_related
                if is_operetor_related != None:
                    master.is_operetor_related = is_operetor_related
                if is_store_classification != None:
                    master.is_store_classification = is_store_classification
                master.save()
                if updates.get('slavemerchant_ids', None):
                    old_slave_merchant_ids = set(
                        list(SlaveMerchant.objects.filter(mastermerchant=master).values_list('slavemerchant_id',
                                                                                             flat=True)))
                    if str(updates['mastermerchant']) in updates['slavemerchant_ids']:
                        raise GaiaRPCFaultException(ERROR.UNIVERSAL, u'主商户与从商户不能重复添加', data=None)
                    for merchant_id in updates['slavemerchant_ids']:
                        if long(merchant_id) in old_slave_merchant_ids:
                            old_slave_merchant_ids.remove(long(merchant_id))
                            continue
                        has_slave = SlaveMerchant.objects.filter(slavemerchant_id=merchant_id)
                        has_master = MasterMerchant.objects.filter(mastermerchant_id=merchant_id)
                        if has_slave.exists() or has_master.exists():
                            raise GaiaRPCFaultException(ERROR.UNIVERSAL, u'商户{}已被设置在其他已建的关联关系中'.format(merchant_id),
                                                        data=None)
                        try:
                            SlaveMerchant.objects.create(mastermerchant=master, slavemerchant_id=merchant_id)
                        except:
                            raise GaiaRPCFaultException(ERROR.UNIVERSAL, u'数据库存入错误', data=None)
                    SlaveMerchant.objects.filter(mastermerchant=master,
                                                 slavemerchant_id__in=old_slave_merchant_ids).delete()

    def create(self, **kwargs):
        with transaction.atomic():
            mastermerchant_id = kwargs['mastermerchant']
            is_login_related = kwargs.pop('is_login_related', True)
            is_message_related = kwargs.pop('is_message_related', True)
            is_operetor_related = kwargs.pop('is_operetor_related', True)
            is_store_classification = kwargs.pop('is_store_classification', False)
            """
            判断本次连锁关系的建立是否存在一个商户既是又是从商户
            """
            if mastermerchant_id in kwargs['slavemerchant_ids']:
                raise GaiaRPCFaultException(ERROR.UNIVERSAL, u'主商户与从商户不能重复添加', data=None)
            """
            先判断主商户是否已存在连锁关系：
            1、为其他主商户从连锁商户
            2、已有从连锁商户关联
            """
            has_slave = SlaveMerchant.objects.filter(slavemerchant_id=mastermerchant_id)
            has_master = MasterMerchant.objects.filter(mastermerchant_id=mastermerchant_id)
            if has_slave.exists() or has_master.exists():
                raise GaiaRPCFaultException(ERROR.UNIVERSAL, u'主商户已经存在关联关系', data=None)
            master = MasterMerchant.objects.create(
                mastermerchant_id=kwargs['mastermerchant'],
                is_login_related=is_login_related,
                is_message_related=is_message_related,
                is_operetor_related=is_operetor_related,
                is_store_classification=is_store_classification
            )
            """
            判断从连锁商户是否存在关联关系
            1、是否为其他商户的从连锁商户
            2、是否是主连锁商户
            """

            for merchant_id in kwargs['slavemerchant_ids']:
                has_master = MasterMerchant.objects.filter(mastermerchant_id=merchant_id)
                has_slave = SlaveMerchant.objects.filter(slavemerchant_id=merchant_id)
                if has_slave or has_master:
                    raise GaiaRPCFaultException(ERROR.UNIVERSAL, u'商户{}已被设置在其他已建的关联关系中'.format(merchant_id), data=None)
                try:
                    SlaveMerchant.objects.create(mastermerchant=master, slavemerchant_id=merchant_id)
                except:
                    raise GaiaRPCFaultException(ERROR.UNIVERSAL, u'数据库存入错误', data=None)
            return {
                'id': master.id
            }