from django.conf import settings
from django.template import loader

from domain.imdb.domain_model import Region
from imdb.models import CelebrityModel
from utils import date_utils
from django.core import mail


class Config:
    DESC = {}

    @classmethod
    def describe(cls, code):
        return cls.DESC.get(code, "")


class ProjectGenre(Config):
    DESC = {
        1: '搞笑',
        2: '唱跳',
        3: '魔法',
        4: '冒险',
        5: '玩具',
        6: '机甲',
        7: '交通工具',
        8: '合家欢',
        9: '幼教',
        10: '真人特摄',
        11: '王道',
        12: '热血',
        13: '儿歌',
        14: '运动',
        15: '科幻',
        16: '恋爱',
        17: '职场',
        18: '推理',
        19: '奇幻/玄幻',
        20: '励志',
        21: '校园',
        22: '美食',
        23: '科普',
        100: '其他'
    }


class AgeGroup(Config):
    DESC = {
        1: '0-3岁',
        2: '3-6岁',
        3: '6-9岁',
        4: '9-16岁',
        5: '16岁以上'
    }


class GenderGroup(Config):
    DESC = {
        1: '男孩向',
        2: '女孩向',
        11: '青少年女性向',
        12: '青少年男性向'
    }


class ProjectState(Config):
    INIT_PENDING = 1
    INIT_RATING = 2
    INIT_DONE = 3

    INNER_PENDING = 11
    # INNER_RATING = 12
    INNER_DONE = 13

    # OUT_PENDING = 21
    OUT_RATING = 22
    OUT_DONE = 23

    FINAL_ABORT = 40
    FINAL_PENDING = 41
    FINAL_SUCCESS = 42

    DESC = {
        INNER_PENDING: "资料补充",
        # INNER_RATING: "内部评级中",
        INNER_DONE: "内部评级完成",

        # OUT_PENDING: '外部待评估',
        OUT_RATING: '平台评估中',
        OUT_DONE: '平台评估完成',

        FINAL_ABORT: "终审放弃",
        FINAL_PENDING: "签约中",
        FINAL_SUCCESS: '签约完成',
    }


class ProjectTags(Config):
    TAG0 = 0
    TAG1 = 1
    TAG2 = 2
    TAG3 = 3
    TAG4 = 4
    TAG5 = 5
    TAG6 = 6
    TAG7 = 7
    TAG8 = 8
    TAG9 = 9
    TAG11 = 11

    DESC = {
        TAG0: "新增项目",
        TAG1: "项目情况更新",
        TAG2: "平台需求",
        TAG3: "运营需求",
        TAG4: "采购评估报价",
        TAG5: "片方回复报价",
        TAG6: "竞争对手报价",
        TAG7: "复盘",
        TAG8: "重要时间节点",
        TAG9: "会议纪要",
        TAG11: "字段更新"
    }

    @staticmethod
    def json_format(tags):
        return ProjectTags.TAG0 in tags or ProjectTags.TAG11 in tags


class ProjectBizMode(Config):
    PURCHASE = 1
    INVEST = 2
    PROFIT_SHARE = 3
    PROFIT_GRANT_SHARE = 4
    DESC = {
        PURCHASE: "采购",
        INVEST: "投资",
        PROFIT_SHARE: "分账",
        PROFIT_GRANT_SHARE: "保底分账"
    }


class ProjectRating:
    VALUES = ['S', 'A', 'B', 'C', 'X']


class ProjectSale:
    VALUES = ['高丞', '张雪', '周斯超']


class ProjectExclusive(Config):
    UND = 0
    SOLO = 1
    SHARE = 2
    ONLY1 = 3

    DESC = {
        UND: "暂无",
        SOLO: "独家",
        SHARE: "非独",
        ONLY1: "定向"
    }


def project_to_dict(project, simple=False):
    result = {
        'id': project.id,
        'title': project.title,
        'alias': project.alias,
        'priority': project.priority,
        'img_url': project.img_url,
        'score': project.score,
        'rating': project.rating,
        'state': {project.state: ProjectState.describe(project.state)},
        'biz_mode': [{mode: ProjectBizMode.describe(mode)} for mode in project.biz_mode],
        'country': [{cid: Region().get_by_id(cid).name} for cid in project.country],
        'episodes': project.episodes,
        'ep_duration': project.ep_duration,
        'ip_year': project.ip_year,
        'ip_exclusive': {project.ip_exclusive: ProjectExclusive.describe(project.ip_exclusive)},
        'ip_property': project.ip_property,
        'create_time': date_utils.dt_format(project.create_time),
        'buyer': project.buyer_name,
        'sale': project.sale_name
    }
    if not simple:
        result.update({
            'story_line': project.story_line,
            'sample_url': project.sample_url,
            'company': project.company,
            'company_role': project.company_role,
            'online_time': date_utils.dt_format(project.online_time),
            'inner_dt_limit': date_utils.dt_format(project.inner_dt_limit),
            'grant_dt_limit': date_utils.dt_format(project.grant_dt_limit),
            'opera_income': project.opera_income,
            'grant_income': project.grant_income,
            'area_limit': project.area_limit,
            'product_category': project.product_category,
            'has_3d_model': project.has_3d_model,
            'has_2d_model': project.has_2d_model,
            'grant_eval_comment': project.grant_eval_comment,
            'genre': [{item: ProjectGenre.describe(item)} for item in project.genre],
            "focus": project.focus,
            "age_group": [{item: AgeGroup.describe(item)} for item in project.age_group],
            "gender_group": [{item: GenderGroup.describe(item)} for item in project.gender_group],
            'other_info': project.other_info
        })

        if project.department == 3:
            result.update({
                'actors': project.actors,
                'directors': project.directors,
                'money': project.money,
                'evaluation': project.evaluation,
                'evaluation1': project.evaluation1,
                'distributor': project.distributor
            })
            result.pop("has_3d_model")
            result.pop("has_2d_model")
            result.pop("age_group")
            result.pop("gender_group")
            result.pop("img_url")
            result.pop("company_role")

    return result


def send_notification_mail(project, created_flag=False):
    dept = project.department
    project = project_to_dict(project)
    template = loader.render_to_string('ip_design/project.html', context={'project': project})
    # print(template)
    title = "项目新增通知" if created_flag else "项目更新通知"
    __do_send_mail(title, template, dept)
    return


def __do_send_mail(title, template, dept, html=True):
    sender = 'mailer@sh-senyu.com'
    passwd = 'Lzzh123!'
    sender_show = "运营平台<{}>".format(sender)
    # refer ProjectModel in models.py for department choices
    receiver = settings.MAIL_GROUP_CT if dept == 1 else settings.MAIL_GROUP_OP
    mail.send_mail(title, template, sender_show, [receiver], auth_user=sender, auth_password=passwd,
                   html_message=template if html else "")


def filter_usefull_fields(jobj: dict):
    ignore_fields = ['priority', 'img_url', 'country', 'story_line', 'focus', 'other_info',
                     'company', 'company_role', 'has_3d_model', 'has_2d_model', 'buyer_id']

    result = {
        k: v for k, v in jobj.items() if k not in ignore_fields
    }

    return result


def inner_date_limit_warning(items, dept):
    title = "项目评估期限到期提醒"
    msg = "以下项目即将到期，请相关人员尽快完成评估!\n"
    for item in items:
        msg += "项目:{}，英文名:{}, 采购负责人:{}，评估期限:{}\n". \
            format(item['title'], item['alias'], item['buyer_name'], item['inner_dt_limit'])
    __do_send_mail(title, msg, dept, html=False)
    return


def clean_data(jobj: dict):
    def format_name(key):
        name = jobj.get(key, '')
        name = name.strip().title()
        if name:
            jobj[key] = name
        return jobj

    format_name('title')
    format_name('alias')

    return jobj
