# -*- coding: utf-8 -*-
'''活动管理接口'''

from flask import request
from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User
from model.role import identity

from flask_jwt_extended import (fresh_jwt_required)


def demand_activity_add(activity_id, data):
    '''添加活动需求'''
    for demand_id in data:
        demand = Demand.get(Demand.id == demand_id)
        if not demand.activityId:
            demand.activityId = activity_id
            # Demand.update(activityId=activity_id).where(Demand.id == demand_id).execute()
            demand.save()


def demand_activity_del(activity_id, data):
    '''删除活动需求'''
    for demand_id in data:
        demand = Demand.get(Demand.id == demand_id)
        if demand.activityId == activity_id:
            demand.activityId = None
            # Demand.update(activityId=activity_id).where(Demand.id == demand_id).execute()
            demand.save()


def demand_activity_done(activity_id, data):
    '''更新活动需求'''
    for demand_id in data:
        demand = Demand.get(Demand.id == demand_id)
        if demand.activityId == activity_id:
            demand.status = 1
            # Demand.update(activityId=activity_id).where(Demand.id == demand_id).execute()
            demand.save()


@fresh_jwt_required
@identity.check_permission("create", 'task')
def activity_add():
    '''创建项目活动'''
    data = request.json
    if 'memberId' in data and data['memberId']:
        data['status'] = 'dev-ing'
    with database.atomic():
        activity_id = ActivityBase.create(**data).id
        if 'memberId' in data and data['memberId']:
            for member_id in data['memberId']:
                role = ProjectMember.get(
                    ProjectMember.projectId == data['projectId'],
                    ProjectMember.memberId == member_id).role
                ActivityMember.create(**{
                    'activityId': activity_id,
                    'memberId': member_id,
                    'role': role
                })
        demand_activity_add(activity_id, data['demand'])
    return {"msg": 'ok'}


@fresh_jwt_required
@identity.check_permission("update", 'task')
def activity_update():
    '''更新项目活动'''
    data = request.json
    activity_id = data.pop('activityId')
    with database.atomic():
        if 'del_memberId' in data:
            for member_id in data.pop('del_memberId'):
                ActivityMember.delete().where(
                    (ActivityMember.activityId == activity_id) &
                    (ActivityMember.memberId == member_id)).execute()
        if 'memberId' in data:
            if not 'status' in data or not data['status']:
                data['status'] = 'dev-ing'
            for member_id in data.pop('memberId'):
                ActivityMember.get_or_create(
                    activityId=activity_id,
                    memberId=member_id,
                    role=ProjectMember.get(
                        (ProjectMember.projectId == data['projectId'])
                        & (ProjectMember.memberId == member_id)).role)
        if 'done_demand' in data:
            demand_activity_done(activity_id, data.pop('done_demand'))
        if 'demand' in data:
            demand_activity_add(activity_id, data.pop('demand'))
        if 'del_demand' in data:
            demand_activity_del(activity_id, data.pop('del_demand'))
        Activity.update(**data).where(Activity.id == activity_id).execute()
    return {"msg": 'ok'}


@fresh_jwt_required
def activity_detail(activity_id):
    '''查询活动详情
        GET /api/activity/<int:activity_id>
    '''
    activity = Activity.findOne(Activity.id == activity_id)
    activity['member'] = list(
        ActivityMember.find(ActivityMember.role, User.username,
                            User.email, User.id).join(User)
        .where(ActivityMember.activityId == activity_id))
    activity['demand'] = list(
        Demand.find().where(Demand.activityId == activity_id))
    return activity


@fresh_jwt_required
def project_user(project_id):
    '''查询项目成员'''
    return {
        "data":
        list(
            ProjectMember.find(
                ProjectMember.role,
                User).join(User).where(ProjectMember.projectId == project_id))
    }

[((42, 1, 42, 44), 'model.role.identity.check_permission', 'identity.check_permission', ({(42, 27, 42, 35): '"""create"""', (42, 37, 42, 43): '"""task"""'}, {}), "('create', 'task')", False, 'from model.role import identity\n'), ((65, 1, 65, 44), 'model.role.identity.check_permission', 'identity.check_permission', ({(65, 27, 65, 35): '"""update"""', (65, 37, 65, 43): '"""task"""'}, {}), "('update', 'task')", False, 'from model.role import identity\n'), ((101, 15, 101, 59), 'model.db.Activity.findOne', 'Activity.findOne', ({(101, 32, 101, 58): 'Activity.id == activity_id'}, {}), '(Activity.id == activity_id)', False, 'from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User\n'), ((14, 17, 14, 51), 'model.db.Demand.get', 'Demand.get', ({(14, 28, 14, 50): 'Demand.id == demand_id'}, {}), '(Demand.id == demand_id)', False, 'from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User\n'), ((24, 17, 24, 51), 'model.db.Demand.get', 'Demand.get', ({(24, 28, 24, 50): 'Demand.id == demand_id'}, {}), '(Demand.id == demand_id)', False, 'from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User\n'), ((34, 17, 34, 51), 'model.db.Demand.get', 'Demand.get', ({(34, 28, 34, 50): 'Demand.id == demand_id'}, {}), '(Demand.id == demand_id)', False, 'from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User\n'), ((48, 9, 48, 26), 'model.db.database.atomic', 'database.atomic', ({}, {}), '()', False, 'from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User\n'), ((70, 9, 70, 26), 'model.db.database.atomic', 'database.atomic', ({}, {}), '()', False, 'from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User\n'), ((49, 22, 49, 49), 'model.db.ActivityBase.create', 'ActivityBase.create', ({}, {}), '(**data)', False, 'from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User\n'), ((55, 16, 59, 18), 'model.db.ActivityMember.create', 'ActivityMember.create', ({}, {}), "(**{'activityId': activity_id, 'memberId': member_id,\n    'role': role})", False, 'from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User\n'), ((107, 8, 107, 21), 'model.db.Demand.find', 'Demand.find', ({}, {}), '()', False, 'from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User\n'), ((52, 23, 54, 56), 'model.db.ProjectMember.get', 'ProjectMember.get', ({(53, 20, 53, 64): "(ProjectMember.projectId == data['projectId'])", (54, 20, 54, 55): '(ProjectMember.memberId == member_id)'}, {}), "(ProjectMember.projectId == data['projectId'], \n    ProjectMember.memberId == member_id)", False, 'from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User\n'), ((92, 8, 92, 31), 'model.db.Activity.update', 'Activity.update', ({}, {}), '(**data)', False, 'from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User\n'), ((103, 8, 104, 48), 'model.db.ActivityMember.find', 'ActivityMember.find', ({(103, 28, 103, 47): 'ActivityMember.role', (103, 49, 103, 62): 'User.username', (104, 28, 104, 38): 'User.email', (104, 40, 104, 47): 'User.id'}, {}), '(ActivityMember.role, User.username, User.email, User.id)', False, 'from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User\n'), ((83, 25, 85, 64), 'model.db.ProjectMember.get', 'ProjectMember.get', ({(84, 24, 85, 63): "((ProjectMember.projectId == data['projectId']) & (ProjectMember.memberId ==\n    member_id))"}, {}), "((ProjectMember.projectId == data['projectId']) & (\n    ProjectMember.memberId == member_id))", False, 'from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User\n'), ((117, 12, 119, 21), 'model.db.ProjectMember.find', 'ProjectMember.find', ({(118, 16, 118, 34): 'ProjectMember.role', (119, 16, 119, 20): 'User'}, {}), '(ProjectMember.role, User)', False, 'from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User\n'), ((73, 16, 73, 39), 'model.db.ActivityMember.delete', 'ActivityMember.delete', ({}, {}), '()', False, 'from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User\n')]