# coding=utf-8
# owner: lipeng or zhouyang
#
#
from __future__ import unicode_literals, absolute_import, print_function

import os
import StringIO
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

import urllib2

from gm_types.doctor import DOCTOR_TITLE_TYPE

from rpc.tool.log_tool import logging_exception,info_logger
from api.tool.image_utils import get_thumb_path

from api.models import Doctor
from api.models import Hospital
from hippo.models.hospital import HospitalMap
from hippo.models.doctor import DoctorCard
from api.models import DOCTOR_ORDER_TYPE, ORDER_STATUS, DOCTOR_TYPE, TOPIC_TYPE

from gm_types.gaia import HOSPITAL_TYPE

from rpc.decorators import bind
from gm_upload import upload, IMG_TYPE, upload_file
from api.util.wechat_util import create_wx_qarcode

def get_image(filepath):
    if os.path.isfile(filepath):
        image = Image.open(filepath)
        return image
    else:
        return filepath

def get_size(image):
    width, height = image.size
    return width, height

def add_text(filepath, size, text, color, font=None, direction=None, is_file=True):
    """
    filepath 图片的地址
    size 所添加文字位于什么位置
    text 文本内容
    font 字体样式
    color 字体颜色
    """
    if is_file:
        image = get_image(filepath)
    else:
        image = filepath

    draw = ImageDraw.Draw(image)

    if not font:
        font = ImageFont.truetype(os.path.join(BASE_DIR, "api/view/img/SimHei.ttf"), 13, encoding="utf-8")

    draw.text(size, text, fill=color, font=font, direction=direction)
    return image

def merge_image(parent_im, child_im, box, size_width=None, size_height=None):
    """
    parent_im 父图片
    child_im 子图片
    box 合并的位置
    """
    if size_width and size_height:
        child_im.resize((size_width, size_height))
    parent_im.paste(child_im, (box[0], box[1]), child_im)
    return parent_im

def create_wx_qr(map_id, width):
    """
    创建微信二维码
    """
    #path = "pages/org/code/main"
    path = "pages/org/main"
    scene = "id={map_id}".format(map_id=map_id)

    res = create_wx_qarcode(path, scene, width)
    if res["errcode"] != 0:
        info_logger.info("errmsg"+"================"+res["errmsg"])
        return str(res["errcode"]) + "====" + str(res["errmsg"]) 

    wx_qr = res["buffer"]
    im = StringIO.StringIO(wx_qr)
    image = Image.open(im).convert("RGBA")
    return image


@bind('api/doctor_card/create')
def get_doctor_card(doctor_id, is_officer):
    """
    获取医生名片
    """
    doctor = Doctor.objects.filter(id=doctor_id, doctor_type=DOCTOR_TYPE.DOCTOR).first()
    if int(is_officer) == 1:
        return {}

    if not doctor:
        return {}

    name = doctor.name                               #医生名称
    if doctor.title == "0" or doctor.title == u"无职称":
        title = ""
    else:
        title = DOCTOR_TITLE_TYPE.getDesc(doctor.title) if DOCTOR_TITLE_TYPE.getDesc(doctor.title) else doctor.title  #职称
    if doctor.good_at:
        good_at = "擅长：" + doctor.good_at
        if len(good_at) > 12:
            good_at = good_at[0:12]+"..."
    else:
        good_at = ""
    hospital_name = doctor.hospital.name             #医院名称
    hospital_id = doctor.hospital.id                 #医院id
    hospital_map = HospitalMap.objects.filter(hospital_id=hospital_id).first()
    if hospital_map:
        map_id = str(hospital_map.id)
    else:
        return {"error": hospital_id+"===is exist map"}

    BASE_DIR = os.path.dirname(os.path.abspath("__file__"))

    image_bg2 = Image.open(os.path.join(BASE_DIR, "api/view/img/bg2@2x.png"))
    image_bg1 = Image.open(os.path.join(BASE_DIR, "api/view/img/bg1@2x.png"))
    image_doctor_bg = Image.open(os.path.join(BASE_DIR, "api/view/img/doctor@2x.png"))
    image_promote_bg = Image.open(os.path.join(BASE_DIR, "api/view/img/promote@2x.png"))
    image_auth_bg = Image.open(os.path.join(BASE_DIR, "api/view/img/doctor_auth@2x.png"))
    image_introduce_bg = Image.open(os.path.join(BASE_DIR, "api/view/img/doctor_int@2x.png"))

    image_qrcode = create_wx_qr(map_id, 126)
    if isinstance(image_qrcode, unicode):
        return {"error": image_qrcode}

    #image_qrcode = Image.open(os.path.join(BASE_DIR, "api/view/img/logo.png"))
    image_qrcode = image_qrcode.resize((126, 126))

    default_url = "https://heras.igengmei.com/2020/02/07/92f6294ce4"

    head_url = doctor.portrait              #医生头像
    try:
        r = urllib2.urlopen(head_url)            #通过r.read()生成文件
    except:
        r = urllib2.urlopen(default_url)
    w = r.read()
    imgBuf = StringIO.StringIO(w)    #采用StringIO直接将验证码文件写到内存，省去写入硬盘
    image_head = Image.open(imgBuf).convert("RGBA")         #PIL库加载图片
    image_head = image_head.resize((415, 415))

    target = Image.new('RGBA', (image_bg2.width, image_bg2.height+27))  #对下半部分进行结合

    image0 = merge_image(image_doctor_bg, image_head, (14, 14))       #将头像和医生照片背景进行结合
    image1 = merge_image(image0, image_auth_bg, (269, 20))            #将医生背景和认证背景进行结合

    image22 = merge_image(image_promote_bg, image_qrcode, (487, 252)) #将二维码和宣传卡片进行结合
    image2 = merge_image(image_bg2, image22, (39, 508))               #将宣传卡片和背景2进行结合
    image3 = merge_image(target, image2, (0, 51))
    image3 = merge_image(target, image1, (240, 0))

    target1 = Image.new('RGB', (image3.width, image3.height+422), "#FFFFFF")
    image4 = merge_image(target1, image3, (0, 372))
    image4 = merge_image(target1, image_bg1, (0, 0))

    #医生介绍和文字的生成
    font1 = ImageFont.truetype(os.path.join(BASE_DIR, "api/view/img/SimHei.ttf"), 30, encoding="utf-8")
    font2 = ImageFont.truetype(os.path.join(BASE_DIR, "api/view/img/SimHei.ttf"), 30, encoding="utf-8")
    font3 = ImageFont.truetype(os.path.join(BASE_DIR, "api/view/img/SimHei.ttf"), 25, encoding="utf-8")
    font4 = ImageFont.truetype(os.path.join(BASE_DIR, "api/view/img/SimHei.ttf"), 22, encoding="utf-8")
    image = add_text(image_introduce_bg, (48, 28), name, "rgb(77, 75, 78)", font1, direction=None, is_file=False)
    image = add_text(image, (48, 77), hospital_name, "#FFFFFF", font2, direction=None, is_file=False)
    image = add_text(image, (162, 33), title, "rgb(74, 91, 92)", font3, direction=None, is_file=False)
    image = add_text(image, (48, 127), good_at, "rgb(68, 118, 117)", font4, direction=None, is_file=False)

    image = merge_image(image4, image, (45, 735))
    file_url = os.path.join(BASE_DIR, "api/view/img/"+doctor_id+"_doctor.png")
    image.save(file_url)

    try:
        url=upload_file(file_url)
        os.remove(file_url)
        DoctorCard.objects.create(doctor=doctor, card_url=url)
        return {"image_url": url}
    except:
        logging_exception()
        return ""


@bind('api/officer_card/create')
def get_officer_card(doctor_id, is_officer):
    """
    获取机构名片
    """
    doctor = Doctor.objects.filter(id=doctor_id, doctor_type=DOCTOR_TYPE.OFFICER).first()
    if int(is_officer) == 0:
        return {}

    if not doctor:
        return {}

    if doctor.hospital.name:
        name = doctor.hospital.name             #机构名称
        if len(name) > 13:
            name = name[0:13]+"..."
    else:
        name = ""

    if doctor.hospital.location:
        location = doctor.hospital.location     #地址
        if len(location) > 17:
            location = location[0:17]+"..."
    else:
        location = ""
    hospital_id = doctor.hospital.id        #医院id
    hospital_map = HospitalMap.objects.filter(hospital_id=hospital_id).first()
    if hospital_map:
        map_id = str(hospital_map.id)
    else:
        return {"error": hospital_id+"===is exist map"}

    BASE_DIR = os.path.dirname(os.path.abspath("__file__"))

    image_bg2 = Image.open(os.path.join(BASE_DIR, "api/view/img/bg2@2x.png"))
    image_bg1 = Image.open(os.path.join(BASE_DIR, "api/view/img/bg1@2x.png"))
    image_doctor_bg = Image.open(os.path.join(BASE_DIR, "api/view/img/doctor@2x.png"))
    image_promote_bg = Image.open(os.path.join(BASE_DIR, "api/view/img/promote@2x.png"))
    image_auth_bg = Image.open(os.path.join(BASE_DIR, "api/view/img/doctor_auth@2x.png"))
    image_introduce_bg = Image.open(os.path.join(BASE_DIR, "api/view/img/hospital_int@2x.png"))

    default_url = "https://heras.igengmei.com/2020/02/07/92f6294ce4"

    head_url = doctor.portrait
    hospital_head_url = doctor.hospital.portrait
    try:
        r = urllib2.urlopen(head_url)            #说明head_url存在，并且有效
    except:                                      #head_url无效或者不存在
        try:
            r = urllib2.urlopen(hospital_head_url)
        except:
            r = urllib2.urlopen(default_url)

    w = r.read()
    imgBuf = StringIO.StringIO(w)    #采用StringIO直接将验证码文件写到内存，省去写入硬盘
    image_head = Image.open(imgBuf).convert("RGBA")         #PIL库加载图片
    image_head = image_head.resize((415, 415))

    image_qrcode = create_wx_qr(map_id, 126)
    if isinstance(image_qrcode, unicode):
        return {"error": image_qrcode}

    #image_qrcode = Image.open(os.path.join(BASE_DIR, "api/view/img/logo.png"))
    image_qrcode = image_qrcode.resize((126, 126))

    target = Image.new('RGBA', (image_bg2.width, image_bg2.height+27))  #对下半部分进行结合

    image0 = merge_image(image_doctor_bg, image_head, (14, 14))       #将头像和医生照片背景进行结合
    image1 = merge_image(image0, image_auth_bg, (269, 20))            #将医生北京和认证背景进行结合
    image22 = merge_image(image_promote_bg, image_qrcode, (487, 252)) #将二维码和宣传卡片进行结合
    image2 = merge_image(image_bg2, image22, (39, 508))               #将宣传卡片和背景2进行结合
    image3 = merge_image(target, image2, (0, 51))
    image3 = merge_image(target, image1, (240, 0))

    target1 = Image.new('RGB', (image3.width, image3.height+422), "#FFFFFF")
    image4 = merge_image(target1, image3, (0, 372))
    image4 = merge_image(target1, image_bg1, (0, 0))

    #医生介绍和文字的生成
    font1 = ImageFont.truetype(os.path.join(BASE_DIR, "api/view/img/SimHei.ttf"), 30, encoding="utf-8")
    font2 = ImageFont.truetype(os.path.join(BASE_DIR, "api/view/img/SimHei.ttf"), 22, encoding="utf-8")
    image = add_text(image_introduce_bg, (48, 37), name, "rgb(77, 75, 78)", font1, direction=None, is_file=False)
    image = add_text(image, (48, 90), location, "#FFFFFF", font2, direction=None, is_file=False)

    image = merge_image(image4, image, (45, 735))

    file_url = os.path.join(BASE_DIR, "api/view/img/"+doctor_id+"_officer.png")
    image.save(file_url)
    try:
        url=upload_file(file_url)
        os.remove(file_url)
        DoctorCard.objects.create(doctor=doctor, card_url=url)
        return {"image_url": url}
    except:
        logging_exception()
        return ""


