# _*_ coding: utf-8 _*_
# Author: Monica( nikochild@gmail.com)
from odoo.exceptions import ValidationError
from odoo import models, fields, api,_


class CrmLead(models.Model):
    _inherit = 'crm.lead'

    event_plan_id = fields.Many2one(comodel_name='event.plan', string='關聯的活動')


class EventPlan(models.Model):
    _name = 'event.plan'
    _rec_name = 'name'
    _inherit = ['mail.thread', 'mail.activity.mixin',
                'utm.mixin', 'format.address.mixin']
    _description = '活動規劃'

    name = fields.Char(string='活動名稱')
    event_description = fields.Text(string='活動說明')
    event_date = fields.Date(string='活動日期', default=fields.Date.today())
    event_company = fields.Many2one('res.company', string='活動校區>公司')
    event_class_room = fields.Many2one('jptip.class.room', string='活動地點>教室')
    event_teacher = fields.Many2one('jt.teacher', string='教師')
    state = fields.Selection(selection=([('draft', '草稿'), ('Guangxuan', '廣宣投放'), ('execution', '執行'), (
        'perfection', '完成')]), string='Status', track_visibility='onchange', copy=False, default='draft', index=True)
    event_url = fields.Char(string='活動網址', track_visibility='onchange')
    link_tracker_ids = fields.One2many(comodel_name='link.tracker', inverse_name='event_plan_id', string='活動連結明細')
    is_event_url = fields.Boolean(default=False)
    crm_register_ids = fields.One2many(
        comodel_name='crm.lead', inverse_name='event_plan_id', string='商機暫存明細')
    click_quantity = fields.Integer(
        string='點擊數量', compute='compute_click_quantity')
    number_of_applicants = fields.Integer(
        string='報名人數', compute='compute_click_quantity')
    realated_number_of_applicants = fields.Integer(related='number_of_applicants', store=True)
    attendance = fields.Integer(string='出席人數', track_visibility='onchange')
    utm_source_801 = fields.Integer(
        string='臉書-留學', compute='compute_click_quantity')
    utm_source_802 = fields.Integer(
        string='臉書-工作', compute='compute_click_quantity')
    utm_source_803 = fields.Integer(
        string='臉書-補習班', compute='compute_click_quantity')
    utm_source_804 = fields.Integer(
        string='臉書-廣告', compute='compute_click_quantity')
    utm_source_805 = fields.Integer(
        string='臉書-社團', compute='compute_click_quantity')
    utm_source_806 = fields.Integer(
        string='PTT', compute='compute_click_quantity')
    utm_source_807 = fields.Integer(
        string='背包客', compute='compute_click_quantity')
    utm_source_808 = fields.Integer(
        string='電子報', compute='compute_click_quantity')
    utm_source_809 = fields.Integer(
        string='GoogleADS', compute='compute_click_quantity')
    utm_source_810 = fields.Integer(
        string='LINE@', compute='compute_click_quantity')
    utm_source_811 = fields.Integer(
        string='DM', compute='compute_click_quantity')
    utm_source_812 = fields.Integer(
        string='雜誌', compute='compute_click_quantity')
    utm_source_813 = fields.Integer(
        string='Youtube', compute='compute_click_quantity')
    utm_source_814 = fields.Integer(
        string='紙文宣QR Code', compute='compute_click_quantity')
    utm_source_815 = fields.Integer(
        string='聯播網', compute='compute_click_quantity')
    utm_source_816 = fields.Integer(
        string='LandingPage', compute='compute_click_quantity')
    #x_category = fields.Selection(selection=([('留遊學','留遊學'),('打工度假(無簽證)','打工度假(無簽證)'),('打工度假(有簽證)','打工度假(有簽證)'),('住宿','住宿'),('日商正職','日商正職'),('顧問課程','顧問課程'),('日語課程試聽','日語課程試聽'),('Landing Page','Landing Page')]), string='分類')
    #x_datetime = fields.Datetime(string='活動日期')
    #x_budget = fields.Integer(string='廣告預算')
    jptip_event_id = fields.Many2one('jptip.event')
    jptip_event_lines = fields.One2many('jptip.event','event_id')
    count_event = fields.Integer(compute='compute_event')

    def change_to_crm(self):
        action = self.env.ref('crm.crm_lead_opportunities_tree_view').read()[0]
        action['domain'] = [('event_plan_id', '=', self.id),'|',('active','=',True),('active','=',False)]
        action['context'] = {'default_search_x_show_all_opportunity': True}
        return action

    def compute_event(self):
        for line in self:
            line.count_event = len(line.jptip_event_lines)

    @api.depends('link_tracker_ids.count', 'crm_register_ids')
    def compute_click_quantity(self):
        for line in self:
            for row in line.link_tracker_ids:
                line.click_quantity += row.count
            crm_register_ids = self.env['crm.lead'].search([('event_plan_id', '=', line.id), '|', ('active', '=', True), ('active', '=', False)])
            line.number_of_applicants = len(crm_register_ids)
            utm_source_statistics = dict()
            for row in crm_register_ids:
                utm_source_statistics.setdefault(
                    row.crm_source_id.src_identify, 0)
                utm_source_statistics[row.crm_source_id.src_identify] = utm_source_statistics[row.crm_source_id.src_identify] + 1
            for key, value in utm_source_statistics.items():
                utm_source_member = 'utm_source_%s' % key
                if hasattr(line, utm_source_member):
                    line[utm_source_member] = value

    @api.onchange('event_url')
    def onchange_event_url(self):
        if self.event_url:
            self.is_event_url = True
        elif not self.event_url:
            self.is_event_url = False

    @api.multi
    def event_url_generation(self):
        link_tracker = self.env['link.tracker']
        utm_source_ids = self.env['utm.source'].search([])
        for utm_source_id in utm_source_ids:
            link_tracker.create({
                'event_plan_id': self.id,
                'title': self.name,
                'url': self.event_url + "?field_source=" + utm_source_id.src_identify,
                'source_id': utm_source_id.id
            })
        return True

    def change_to_event(self):
        action = self.env.ref('jptip_core.event_view_action').read()[0]
        action['domain'] = [('event_id', '=', self.id)]
        return action


class LinkTracker(models.Model):
    _inherit = 'link.tracker'

    event_plan_id = fields.Many2one(comodel_name='event.plan', string='活動編號')


class UtmSource(models.Model):
    _inherit = 'utm.source'

    src_identify = fields.Char(string='來源 ID', required=True)
    _sql_constraints = [
        ('src_identify', 'unique(src_identify)', '來源 ID 不可重覆!')]
