#!/usr/bin/env python
# -*- coding: utf_8 -*-

import copy
import time
import types
import json
import logging
import traceback
from datetime import datetime
from pony.orm import *
from flask import request
from model import fullStackDB
from model.annex import Annex
from model.user import User
from utils import sql_filter

logger = logging.getLogger("AnnexManager")

class AnnexManager(object):
    def __init__(self):
        super(AnnexManager, self).__init__()

    def add(self, data):
        editor = User.get(id=request.current_user.get("id"))
        if not editor:
            return False, "current user is not exists"

        if data.get("flow"):
            flow = Flow.get(uuid=data.get("flow"))
            if not flow:
                return False, "flow does not exists."
            data.update({ "flow": flow })
        elif data.get("project"):
            project = Project.get(uuid=data.get("project"))
            if not project:
                return False, "project does not exists."
            data.update({ "project": project })

        data.update({
            'title': data.get("title"),
            'path': data.get("path"),
            'size': data.get("size"),
            'create_by': editor,
            'create_at': datetime.now(),
            'update_by': editor,
            'update_at': datetime.now(),
        })

        result = fullStackDB.add(Annex, **data)
        return result, "add annex {}.".format("success" if result else "fail")

    def delete(self, uuid):
        result = False
        with db_session:
            editor = User.get(id=request.current_user.get("id"))
            if not editor:
                return False, "current user is not exists"

            result = Annex.get(uuid=uuid)
            if result:
                if result.project:
                    count = Annex.select(project=result.project, remarks=result.remarks, is_delete=False).count()
                    if count == 1:
                        project = Project.get(id=result.project.id)
                        if project:
                            condition = dict()
                            if result.remarks == "bidding": # 中标通知书
                                condition.update({ "is_bidding": False })
                            elif result.remarks == "acceptance": # 验收表
                                condition.update({ "is_acceptance": False })
                            elif result.remarks == "evaluation": # 评价表
                                condition.update({ "is_evaluation": False })
                            elif result.remarks == "contract": # 合同
                                condition.update({ "is_contract": False })
                            project.extend1.get("uploads").update({ result.remarks: False })
                            project.set(extend1=project.extend1, **condition)
                result.set(is_delete=True, delete_at=datetime.now(), delete_by=editor)
                commit()
                result = True

        return result, "delete annex {}.".format("success" if result else "fail")

    def get(self, data):
        result = Annex.get(**data)
        if result:
            result = result.to_dict(with_collections=True, related_objects=True, only=["uuid", "title", "create_at", "update_at", "delete_at"])
        return result, "get annex {}.".format("success" if result else "fail")

    def getList(self, data):
        if not data or len(data) <= 0:
            return False, 0, "parameters can not be null."

        result = Annex.select().where(is_delete=False, **data)
        if len(result):
            temp = []
            for item in result:
                # t = item.to_dict(with_collections=True, only=["uuid", "title", "project", "path", "remarks"])
                # temp.append(t)
                temp.append({
                    "uuid": item.uuid,
                    "name": item.title,
                    "project": item.project.id,
                    "url": item.path,
                    "type": item.remarks
                })
            result = temp

        return result, len(result), "get annex {}.".format("success" if result else "no data")

    def update(self, uuid, data):
        # 当参数为空时，直接返回错误
        if len(data) <= 0 or (len(data.keys()) == 1 and "id" in data):
            return False, "parameters can not be null."

        # 查询请求者是否存在
        editor = User.get(id=request.current_user.get("id"))
        if not editor:
            return False, "current user is not exists"

        result = fullStackDB.update(Annex, { 'uuid': uuid }, update_at=datetime.now(), update_by=editor, **data)
        return result, "update annex {}.".format("success" if result else "fail")

annexManager = AnnexManager()
