import datetime

from common.utils.models import BaseConnection
from django.db.models import Q
from notifications.signals import notify
from common.notify.message import client as message_client
from common.accounts.models import Accounts
from console.team.models import Team

from common.notify.message import MessageObject

ORDER_TYPE_MAP = {
    "rush_to_repair": "抢修",
    "power_construction": "电力施工",
    "electrical_testing": "电力试验",
    "demand_declaration": "需量申报"
}


class WorkTicketServer(object):
    def __init__(self):
        self.conn = BaseConnection()

    def add_safety_measure(self, data, work_ticket):
        if not data:
            return
        for item in data:
            item.update({
                "work_ticket": work_ticket,
                "created_time": str(datetime.datetime.now())
            })
            key = item.keys()
            value = item.values()
            sql = "insert wt_safety_measure {}".format(tuple(key)).replace(
                "'", "").replace('"', "") + " values {}".format(tuple(value))
            self.conn.query(sql)

    def add_contact(self, data, work_ticket):
        if not data:
            return
        for item in data:
            item.update({
                "work_ticket": work_ticket,
                "created_time": str(datetime.datetime.now())
            })
            key = item.keys()
            value = item.values()
            sql = "insert wt_contact {}".format(tuple(key)).replace(
                "'", "").replace('"', "") + " values {}".format(tuple(value))
            self.conn.query(sql)

    def add_wt_person_changes(self, data, work_ticket):
        if not data:
            return
        for item in data:
            item.update({
                "work_ticket": work_ticket,
                "created_time": str(datetime.datetime.now())
            })
            key = item.keys()
            value = item.values()
            sql = "insert wt_person_changes {}".format(tuple(key)).replace(
                "'", "").replace('"', "") + " values {}".format(tuple(value))
            self.conn.query(sql)

    def add_wt_work_record(self, data, work_ticket):
        if not data:
            return
        for item in data:
            item.update({
                "work_ticket": work_ticket,
                "created_time": str(datetime.datetime.now())
            })
            key = item.keys()
            value = item.values()
            sql = "insert wt_work_record {}".format(tuple(key)).replace(
                "'", "").replace('"', "") + " values {}".format(tuple(value))
            self.conn.query(sql)

    def add_wt_child_ticket(self, data, work_ticket):
        if not data:
            return
        for item in data:
            item.update({
                "work_ticket": work_ticket,
                "created_time": str(datetime.datetime.now())
            })
            key = item.keys()
            value = item.values()
            sql = "insert wt_child_ticket {}".format(tuple(key)).replace(
                "'", "").replace('"', "") + " values {}".format(tuple(value))
            self.conn.query(sql)

    def add_wt_work_change(self, data, work_ticket):
        if not data:
            return
        for item in data:
            item.update({
                "work_ticket": work_ticket,
                "created_time": str(datetime.datetime.now())
            })
            key = item.keys()
            value = item.values()
            sql = "insert wt_work_change {}".format(tuple(key)).replace(
                "'", "").replace('"', "") + " values {}".format(tuple(value))
            self.conn.query(sql)


def order_transfer_notify(**data):
    team = Team.objects.filter(type="0", deleted=False)
    user = [
        item.team_headman.id if item.team_headman else None for item in team
    ] if team else []
    for item in team:
        user += [i.id for i in item.member.all()] if item.member else []
    # param = {
    #     "recipient": Accounts.objects.filter(id__in=user),
    #     "verb": "工单转单",
    #     "action_object": data.get("order"),
    #     "description": "工单{}已被转单，请注意处理".format(data.get("order").id),
    # }
    # 发送站内消息
    # notify.send(data.get("user"), **param)
    message_client.send_station(
        title="工单转单",
        content= "工单{}已被转单，请注意处理".format(data.get("order").id),
        sender_id=1,
        receive_ids=user,
        type=2,
        enterprise_id=team.first().enterprise_id)


def send_order_finish_message(order):
    sms = MessageObject()
    customer = order.task.customer.name if order.task.customer else None
    task_type = order.task.type if order.task else order.type
    param = [customer, ORDER_TYPE_MAP.get(task_type), order.id]
    phone_list = [order.task.customer.service_staff.phone] if \
        order.task.customer and order.task.customer.service_staff else []
    teams = Team.objects.filter(type=0, deleted=False)
    for team in teams:
        phone_list += [team.team_headman.phone] if team.team_headman else []
        phone_list += [item.phone for item in team.member.all()]
    sms.send_sms_multi(phone_list, "857416", param)


def send_order_assign_message(order, team):
    sms = MessageObject()
    customer = order.task.customer if order.task else None
    if not customer:
        return
    task_type = order.task.type if order.task else order.type
    param = [customer.name, task_type, team.name]
    phone = customer.service_staff.phone if customer.service_staff else None
    if not phone:
        return None
    sms.send_sms_single(phone, "857453", param)


def order_data_filter(queryset, user):
    if user.is_manager:
        return queryset
    team = Team.objects.filter(Q(team_headman=user) | Q(member=user)).first()
    # 调度组成员，获取全部数据
    if team and team.type in ["0", "4"]:
        return queryset
    # 巡检、抢修组员
    if team and team.type != "0":
        queryset = queryset.filter(team=team)
        return queryset
    queryset = queryset.filter(task__customer__service_staff=user)
    return queryset
