import datetime

from console.team.models import Team
from django.db.models import Q


from common.notify.message import client as message_client
from common.notify.message import MessageObject

from common.utils.models import BaseConnection

from common.notify.calling import Sample

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


def send_message(task_obj, user):
    teams = Team.objects.filter(type="0",
                                deleted=False).prefetch_related("member")
    team_headman = teams.values("team_headman").distinct()
    member = teams.values("member").distinct()
    user_ids = [t.get("team_headman") for t in team_headman]

    user_ids += [m.get("member") for m in member]
    if task_obj.customer and task_obj.customer.service_staff:
        user_ids.append(task_obj.customer.service_staff.id)
    user_ids = list(set(user_ids))
    # account = Users.objects.filter(deleted=False,
    #                                id__in=user_ids).values_list("account")

    # data = {
    #     "recipient": Accounts.objects.filter(id__in=account),
    #     "verb": "新建了一条{}任务".format(task_obj.type),
    #     "action_object": task_obj,
    #     "description": "{}新建了一条{}任务".format(user.username, task_obj.type)
    # }
    # 自动拨号
    # client = ClientObject()
    # client.send_call(["+8617343184154", "+8618601179258"])
    # 短信通知
    sms = MessageObject()
    param = [task_obj.customer.name, TASK_TYPE_MAP.get(task_obj.type)]
    phone_list = [task_obj.customer.service_staff.phone] \
        if task_obj.customer.service_staff else []
    teams = Team.objects.filter(deleted=False, type=0)
    for team in teams:
        phone_list.append(team.team_headman.phone)
        phone_list += [item.phone for item in team.member.all()]
    sms.send_sms_multi(phone_list, "856763", param)
    message_client.send_station(
        title="新建任务",
        content="{}新建了一条{}任务".format(user.username, TASK_TYPE_MAP.get(task_obj.type)),
        sender_id=1,
        receive_ids=user_ids,
        type=2,
        enterprise_id=teams.first().enterprise_id)
    # return notify.send(user, **data)


def create_order_notify(**data):
    team = Team.objects.filter(
        id=data.get("team_id")).prefetch_related("member").first()
    receive_ids = [team.team_headman.id] if team.team_headman else []
    receive_ids += [item.id for item in team.member.all()]
    # account = Users.objects.filter(deleted=False,
    #                                id__in=user_ids).values_list("account",
    #                                                             flat=True)
    # param = {
    #     "recipient":
    #     Accounts.objects.filter(id__in=account),
    #     "verb":
    #     "派发工单",
    #     "action_object":
    #     data.get("order"),
    #     "description":
    #     "{} {}给您分派了一个工单".format(
    #         data.get("user").username,
    #         datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")),
    # }
    # notify.send(data.get("user"), **param)
    message_client.send_station(
        title="派发工单",
        content="{} {}给您分派了一个工单".format(
            data.get("user").username,
            datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")),
        sender_id=1,
        receive_ids=receive_ids,
        type=2,
        enterprise_id=team.enterprise_id)


# def task_close_notify(**data):
#     task = data.get("task")
#     customer = task.customer
#     # 给客户发送任务完成消息
#     sms = MessageObject()
#
#     # 给客户发送任务完成消息
#     if customer:
#         user = CustomerAdmin.objects.filter(customer=customer).values_list(
#             "user_id", flat=True).distinct()
#         users = Users.objects.filter(id__in=user)
#         phones = [item.phone for item in users]
#         params = ["您的" + TASK_TYPE_MAP.get(task.type), task.id]
#         # 发送短信通知
#         sms.send_sms_multi(phones, "829626", params)
#         param = {
#             "recipient":
#             Accounts.objects.filter(id__in=user),
#             "verb":
#             "任务已完成",
#             "action_object":
#             task,
#             "description":
#             "您的{}任务{}已完成，请确认！".format(TASK_TYPE_MAP.get(task.type), task.id),
#         }
#         # 发送站内消息
#         notify.send(data.get("user"), **param)
#     # 给客户代表发送通知
#     if customer.service_staff:
#         phones = [customer.service_staff.phone]
#         params = [customer.name + "的" + TASK_TYPE_MAP.get(task.type), task.id]
#         # 发送短信通知
#         sms.send_sms_multi(phones, "829626", params)
#         param = {
#             "recipient":
#             Accounts.objects.filter(id=customer.service_staff.account),
#             "verb":
#             "任务已完成",
#             "action_object":
#             task,
#             "description":
#             "{}任务{}已完成，请确认！".format(
#                 customer.name + "的" + TASK_TYPE_MAP.get(task.type), task.id),
#         }
#         # 发送站内消息
#         notify.send(data.get("user"), **param)


def get_customer_list(keyword, page, page_size, enterprise):
    conn = BaseConnection()
    sql = """
    select
     a.id as customer_id,a.name ,b.id as ele_user_id,b.number,b.addr,c.address
    from customer a left join electricity_user b on a.id=b.customer_id
    left join enterprise c on a.enterprise_id=c.id
    where a.service_enterprise_id in {}
    """.format(
        tuple(enterprise) if len(enterprise) > 1 else "({})".
            format(enterprise[0]) if enterprise else "(null)")
    if keyword:
        sql += """
          and (a.name like '%{}%' or b.number like '%{}%'
           or b.addr like "%{}%" ) limit {},{}
        """.format(keyword, keyword, keyword, (int(page) - 1) * int(page_size),
                   int(page_size) * int(page))

    else:
        sql += """
        limit {},{}
        """.format((int(page) - 1) * int(page_size),
                   int(page_size) * int(page))
    data = conn.query(sql)

    return data


def get_customer_info(customer_id, ele_user_id):
    conn = BaseConnection()
    sql = """
    select
     a.id,a.name,a.type,b.nickname,b.phone,a.service_staff_id
    from customer a left join users b on a.service_staff_id=b.id
    where a.id={}
    """.format(customer_id)
    data = conn.query(sql)
    if not data:
        return data
    customer_data = data[0]
    ele_data = []
    if ele_user_id:
        sql = """
        select
         number,transformer_capacity,real_capacity,voltage_level,addr
        from electricity_user where id={}
        """.format(ele_user_id)
        ele_data = conn.query(sql)
    customer_data.update({"electricity_user": ele_data})
    team_data = []
    if customer_data.get("service_staff_id"):
        sql = """
        select
         a.id,a.name,b.nickname,b.phone
        from team a left join users b on a.team_headman_id=b.id
        where a.leader_id={}
        """.format(customer_data.get("service_staff_id"))
        team_data = conn.query(sql)
    customer_data.update({"team": team_data})
    sql = """
    select * from contract where customer_id={}
    """.format(customer_id)
    contract_data = conn.query(sql)
    customer_data.update({"contract": contract_data})
    sql = """
    select
     a.*,c.name as tag
    from contact a
    left join contact_tags b on a.id=b.contact_id
    left join  tags c on c.id=b.tag_id
    where a.customer_id={}
    """.format(customer_id)
    contact_data = conn.query(sql)
    customer_data.update({"contacts": contact_data})
    return customer_data


def task_data_filter(queryset, user):
    if user.is_manager:
        return queryset
    team = Team.objects.filter(Q(team_headman=user) | Q(member=user),
                               type=0).first()
    # 调度组成员，获取全部数据
    if team:
        return queryset
    # customer = Customer.objects.filter(service_staff=user)
    queryset = queryset.filter(customer__service_staff=user)
    return queryset


def task_create_calling():
    teams = Team.objects.filter(deleted=False, type=0)
    phone_list = [team.team_headman.phone for team in teams]
    member = []
    for team in teams:
        member += list(team.member.all())
    phones = [user.phone for user in member]
    phone_list += phones
    phone_list = list(filter(None, phone_list)) if phone_list else []
    for phone in phone_list:
        Sample.main(phone)
