# -*- coding:utf-8 -*-
'''
    青年医生1905 自动报名工具
'''

import openpyxl
import copy

from email.header import make_header

from hippo.models import Doctor
from api.models import YoungDoctorRegistrationer
from hera.utils import get_mail_instance


doc_type_map = {
    u'医生': 0,
    u'机构管理者': 1,
    u'医院': 1,
}

award_map = {
    u'人气': 7,
    u'口碑': 6,
    u'审美': 8,
    u'皮肤': 2,
    u'眼部': 0,
    u'胸部': 4,
    u'脂肪': 3,
    u'颌面': 5,
    u'鼻部': 1
}

tick_url = 'https://m.igengmei.com/gengmei-m-web/activity/young-doctor/lobby?doctor_id={id}&doctor_type={type}'

file_name = 'auto_enter.xlsx'
saved_file_name = 'yd_auto_enter.xlsx'

def auto_enter():
    '''
    自动报名入口
    '''
    ex = openpyxl.load_workbook(filename=file_name)
    at_sheet = ex.active
    max_row = at_sheet.max_row
    for rn in range(2, max_row):
        try:
            process_doctor_enter(at_sheet, rn)
        except:
            pass
    ex.save(saved_file_name)
    _notify()


def _notify():
    mail = get_mail_instance('青年医生自动报名结果', '', ['2414063487@qq.com', 'wangkai@igengmei.com'])

    text = open(saved_file_name, 'rb').read()
    mail.attach(make_header([(saved_file_name, 'utf-8')]).encode('utf-8'), text)
    mail.send()


def format_ticket_url(doc_info):
    '''
    格式化拉票页面链接
    '''
    return tick_url.format(id=doc_info['doc_id'], type=doc_info['doc_type'])


def data_unique(data_list):
    if not data_list:
        return data_list
    temp_list = copy.deepcopy(data_list)
    temp_list = list(set(temp_list))
    return sorted(temp_list, key=lambda x:data_list.index(x))


def get_award_ids(doc_info):
    '''
    获取奖项id
    '''
    award_name_list = doc_info['award_name_list']
    doc_type = int(doc_info['doc_type'])
    award_ids = [award_map.get(x) for x in award_name_list]
    award_ids = data_unique(award_ids)
    award_ids = [doc_type*9 + x for x in award_ids]
    return award_ids


def process_doctor_enter(sheet, rn):
    '''
    处理单个医生报名
    '''
    rd = sheet[rn]
    doc_info = read_doc_info(rd)
    if not doc_info:
        return
    res, reason = process_enter(doc_info)
    if not res:
        record_fail_info(rd, reason)
    else:
        ticket_url = format_ticket_url(doc_info)
    	record_success_info(rd, ticket_url)


def record_fail_info(rd, reason):
    rd[11].value = reason

def record_success_info(rd, t_url):
    rd[10].value = t_url

def get_doc_obj_by_id(doc_id):
    try:
        return Doctor.objects.get(id=doc_id)
    except:
        return None

def get_doc_obj_by_name(doc_name, hos_name):
    try:
        return Doctor.objects.get(name__contains=doc_name, hospital__name__contains=hos_name)
    except:
        return None

def process_enter(doc_info):

    if doc_info['doc_id']:
        doctor_id = doc_info['doc_id']
    	doc_obj = get_doc_obj_by_id(doctor_id)
    else:
        doc_obj = get_doc_obj_by_name(doc_info['doc_name'], doc_info['hos_name'])

    reason = ''
    if not doc_obj:
        reason = '未找到医生'
        return False, reason
    if not doc_obj.is_online:
        reason = '医生已下线'
        return False, reason
    doc_info['doc_id'] = doc_obj.id
    doc_info['doc_type'] = doc_obj.doctor_type
    doc_type = doc_type_map.get(doc_info['doc_type_name'])
    if doc_info['doc_type_name'] and str(doc_type) != str(doc_obj.doctor_type):
        reason = '医生类型不匹配'
        return False, reason
    is_enter = YoungDoctorRegistrationer.is_entered_by_doc_id(doc_obj.id)
    if is_enter:
        reason = '已经报名, 不可重复报名'
        return True, reason
    else:
        award_ids = get_award_ids(doc_info)
	return YoungDoctorRegistrationer.enter_at_award_ids(doc_obj.id, doc_obj.doctor_type, award_ids)


def read_doc_info(row_data):
    '''
        返回医生数据
    医生名字,医院名字,奖项必填, 否则视为无效行
    '''
    rd = row_data
    result = {}
    if rd[0] == '>>>>>>':
        print('结束')
        return result
    doc_name = rd[3].value
    doc_type = rd[4].value
    hos_name = rd[5].value
    doc_id = rd[9].value
    award_name_list = (rd[6].value or '').strip(), (rd[7].value or '').strip(), (rd[8].value or '').strip()
    if not any(award_name_list) or not any([doc_id, doc_name and hos_name]):
        return result
    result['doc_name'] = (doc_name or '').strip()
    result['hos_name'] = (hos_name or '').strip()
    result['doc_id'] = (doc_id or '').strip()
    result['doc_type_name'] = (doc_type or '').strip()
    result['award_name_list'] = filter(None, award_name_list)
    return result

