# coding=utf-8

from doris.models.service import SubmissionCommodity, UnitRelateService, Promotion,PromotionRule,Submission
from gm_types.poseidon import VisualUnitRelatedServiceType,CommodityAuditStatus
from rpc.tool.log_tool import logging_exception
from rpc.context import get_rpc_remote_invoker
from api.models.service import ServiceItem,Service
from api.models.smart_rank import SmartRank
from django.conf import settings
from django.db.models import Q
from trans2es.utils.es import tzlc
import datetime


def get_promotion(instance):
    try:
        package_id = instance.submission_id
        res = dict()
        res["id"] = package_id
        res["update_time"] = tzlc(datetime.datetime.now())
        try:
            promotion_ids = list(SubmissionCommodity.objects.filter(submission_id=package_id)
                                  .values_list('promotion_id', flat=True))
            promotion_list = list(PromotionRule.objects.filter(promotion_id__in=promotion_ids,
                                                               composition_rule_type="优惠套餐")
                                              .values_list('promotion_id',flat=True))
            if promotion_list:
                res["unit_ids"] = list(set(promotion_list))
            else:
                return res
        except:
            logging_exception()
            return res

        try:
            q = Q(id=package_id) & ~Q(audit_status__in=[CommodityAuditStatus.UN_AUDITED,
                                                        CommodityAuditStatus.REJECTED])
            active_submission = Submission.objects.filter(q).first().id
            if active_submission:
                sku_spu_list = list(SubmissionCommodity.objects.filter(submission_id=active_submission,deleted=0)
                                    .values_list('commodity_id', 'service_id'))
            else:
                return res
        except:
            logging_exception()
            return res

        if sku_spu_list:
            sku_list = []
            for sku_spu in sku_spu_list:
                sku_id = sku_spu[0]
                spu = sku_spu[1]
                try:
                    smart_rank_v4 = SmartRank.objects.filter(service__id=spu).first().smart_rank_v4
                except:
                    smart_rank_v4 = 0.0

                invoker = get_rpc_remote_invoker()
                rpc_client = invoker['artemis/cpc/is_promote'](service_id=spu)
                is_promote = rpc_client.unwrap()
                sku_list.append({'sku_id': sku_id, 'spu_id': spu, 'smart_rank_v4': smart_rank_v4,
                                "is_promote": is_promote})

            res["sku_list"] = sku_list
            tmp = sorted(sku_list,key=lambda x: (-x["is_promote"], -x["smart_rank_v4"]))[0]
            service_id = tmp["spu_id"]
            res["smart_rank_v4"] = tmp["smart_rank_v4"]
            res["is_promote"] = tmp["is_promote"]
            try:
                if Service.objects.get(id=service_id).doctor:
                    if Service.objects.get(id=service_id).doctor.hospital:
                        if Service.objects.get(id=service_id).doctor.hospital.city:
                            res["city_tag_id"] = Service.objects.get(id=service_id).doctor.hospital.city.tag_id
            except:
                logging_exception()

            res["is_sink"] = Service.objects.get(id=service_id).is_sink
            return res

        else:
            return res

    except:
        logging_exception()