# -*- coding: UTF-8 -*-
import time
import random

from gm_types.poseidon import PromotionStatus, CommodityAuditStatus

from api.models.types import DOCTOR_TYPE

from hippo.models import Doctor


def time_base_prikey():
    """生成64位时间相关的id

    第0位(最高位): 默认0
    第1~41位: timestamp, 毫秒
    第42~47位: 默认0
    第42~63位: [0, 2**17-1]的随机
    """
    return (int(time.time() * 1000) << 22) + (0 << 17) + random.randint(0, 131071)


def get_merchant(doctor_id):
    """
    根据医生ID获取医生的商户ID
    :param doctor_id:
    :return:
    """
    try:
        doctor = Doctor.objects.get(id=doctor_id)
        merchants = doctor.merchantrelevance_set.all()
        if merchants.exists():
            return merchants.first().merchant
        else:
            return None
    except:
        return None


def merchant_doctors(doctor_id):
    """
    获取商户可管理的医生列表
    :param doctor_id:
    :return:
    """
    doctor = Doctor.objects.get(id=doctor_id)
    from hippo.models import Merchant
    merchants = Merchant.objects.filter(doctor=doctor, is_online=True)
    if merchants.exists():
        doctors = [merchant_doctor.doctor for merchant_doctor in doctor.merchant.merchant_doctors.all()]
        return doctors
    else:
        return None


def get_doctors(doctor_id, only_doctor_id=False, include_master=False):
    """
    获取医生可管理的医生列表
    :param include_master:是否包含机构连锁
    :param only_doctor_id:只返回doctor_id
    :param doctor_id:
    :return:
    """
    from hippo.models.chain_hospital import MasterMerchant
    doctors = merchant_doctors(doctor_id)
    if not doctors:
        doctors = [Doctor.objects.get(id=doctor_id), ]
    if include_master:
        try:
            doctor = Doctor.objects.filter(id=doctor_id)
            mastermerchant = MasterMerchant.objects.filter(mastermerchant_id=doctor.first().d_merchant.id).first()
            if mastermerchant:
                doctor_ids = mastermerchant.slavemerchants.values_list('slavemerchant__doctor_id', flat=True)
                for d_id in doctor_ids:
                    doctors.extend(merchant_doctors(d_id))
            else:
                doctors = merchant_doctors(doctor_id)
        except:
            pass
    if only_doctor_id:
        return [ d.id for d in doctors]
    return [{
                'doctor_id': d.id,
                'doctor_name': d.name,
                'h_doctor_name': u'{}-{}'.format(d.hospital.name, d.name)
                if d.doctor_type == DOCTOR_TYPE.DOCTOR else d.name,
                'user_id': d.user_id,
                'portrait': d.portrait if d.portrait else 'https://heras.igengmei.com/slide/2016/11/30/07b076e423',
                'doctor': d,
            } for d in doctors]


def has_add_dairy_rank_permission(diary, current_doctor, doctor):
    """权限的判断 如果日记本不属于医生  或者操作人没有权限为该doctor_id的日记本设置排序  都会抛出没有权限

    :param diary: 日记本实例
    :param current_doctor: 当前操作的医生/机构实例
    :param doctor: 添加日记本对应医生/机构的实例
    :return:
    """
    merchant_doctor_ids = [_['doctor_id'] for _ in current_doctor.get_merchant_doctors()]
    if current_doctor == doctor:
        if diary.doctor_id not in merchant_doctor_ids:
            return False
    else:
        if doctor.id not in merchant_doctor_ids or diary.id != doctor.id:
            return False
    return True


def has_add_service_rank_permission(service, current_doctor, doctor):
    """权限的判断 如果美购不属于医生  或者操作人没有权限为该doctor_id的美购设置排序  都会抛出没有权限

    :param service: 美购实例
    :param current_doctor: 当前操作的医生/机构实例
    :param doctor: 添加美购对应医生/机构的实例
    :return:
    """
    merchant_doctor_ids = [_['doctor_id'] for _ in current_doctor.get_merchant_doctors()]
    if current_doctor == doctor:
        if service.doctor_id not in merchant_doctor_ids:
            return False
    else:
        if doctor.id not in merchant_doctor_ids or service.id != doctor.id:
            return False
    return True


def has_delete_service_rank_permission(current_doctor, service):
    """判断当前用户有没有权限删除美购排名

    :param current_doctor: 当前操作的医生/机构实例
    :param service: 美购实例
    :return: boolean
    """
    if service.doctor_id not in [_['doctor_id'] for _ in current_doctor.get_merchant_doctors()]:
        return False
    return True


def has_delete_diary_rank_permission(current_doctor, diary):
    """判断当前用户有没有权限删除日记本排名

    :param current_doctor: 当前操作的医生/机构实例
    :param diary: 日记本实例
    :return: boolean
    """
    if diary.doctor_id not in [_['doctor_id'] for _ in current_doctor.get_merchant_doctors()]:
        return False
    return True


def build_edit_status_from_sign_up_data(sign_up_data):
    """
    格式化sku活动提报相关信息
    :param sign_up_data:
    :return:
    """
    if not sign_up_data:
        return {}
    submissions = sign_up_data.get('submissions')
    if not submissions:
        return {}
    result = {}
    for submission in submissions:
        service_item_list = submission.get('commodity', [])

        activity_status = submission.get('promotion_detail', {}).get('status')
        audit_status = submission.get('audit_status')

        for service_item in service_item_list:
            service_item_id = service_item.get('commodity_id')
            if service_item_id is not None and not service_item_id:
                continue
            exists_value = result.get(service_item_id)
            if exists_value == False:  # 一个item参加了多个活动的情况
                continue

            # 正在进行：活动状态为「已开始」，提报商品为「审核成功」和「审核中」，且未被删除
            # 即将开始：活动状态为「提报中」和「提报结束」、提报商品为「审核成功」和「审核中」，且未被删除；
            if activity_status == PromotionStatus.START and \
                    audit_status in [CommodityAuditStatus.AUDITED,
                                     CommodityAuditStatus.UN_AUDITED
                                     ]:
                result[service_item_id] = False
            if activity_status in [PromotionStatus.TO_SIGN_UP,
                                   PromotionStatus.SIGN_UP_END] and \
                    audit_status in [CommodityAuditStatus.UN_AUDITED,
                                     CommodityAuditStatus.AUDITED]:
                result[service_item_id] = False
    return result