import datetime
import time

from common.utils.models import BaseConnection

from console.inspection.models import InspectionPlan, InspectionTask

from etc.celery import app


@app.task
def create_plan():
    conn = BaseConnection()
    sql = "select a.user_id from user_tags a left join tags b on " + \
          "a.tag_id=b.id where b.name like '%区块链经理%'"
    leader_ids = conn.query(sql)
    for item in leader_ids:
        sql = "select id from customer where service_staff_id={}".format(
            item.get("user_id"))
        customer_ids = conn.query(sql)
        if customer_ids:
            ids = [customer.get("id") for customer in customer_ids]
            ids = tuple(ids) if len(ids) > 2 else "(%s)" % ids[0]
            # 获取这些客户的所有户号id
            sql = "select id from electricity_user where" + \
                  " customer_id in {}".format(
                      ids)
            ele_users = conn.query(sql)
            ele_ids = [ele_user.get("id") for ele_user in ele_users]
            if ele_ids:
                ele_ids = tuple(
                    ele_ids) if len(ele_ids) > 2 else "(%s)" % ele_ids[0]
                sql = "select id,inspections_number from " + \
                      "power_station where " + \
                      "customer_id in %s or electricity_user_id in %s" % (
                          ids, ele_ids)
            else:
                sql = "select a.id,a.inspections_number " + \
                      "from power_station a " + \
                      "left join customer b on a.customer_id=b.id " + \
                      "where b.id in {}".format(ids)
            # 拿到电站的信息，包含电站id，每月巡检次数
            power_stations = conn.query(sql)
            for data in power_stations:
                # 查询当前电站本月已巡检数量
                year = datetime.datetime.now().year
                month = datetime.datetime.now().month
                sql = "select count(id) as count from inspection_plan  " + \
                      " where year(plan_date)={} and".format(year) + \
                      " month(plan_date)={} ".format(month) + \
                      " and station_id={}".format(data.get("id"))
                planed_count = conn.query(sql)
                # 巡检次数平均分配，以每月4周计算
                multiple_number = (data.get("inspections_number") -
                                   planed_count[0].get("count")) // 4
                # 整除4次的情况
                for i in range(multiple_number):
                    for j in range(4):
                        plan_date = (datetime.datetime.now() +
                                     datetime.timedelta(3 + j * 7)).date()
                        # 检查计划日期是否可以排计划
                        plan_date = check_plan_date(plan_date, conn,
                                                    item.get("user_id"))
                        plan = InspectionPlan.objects.create(
                            station_id=data.get("id"),
                            plan_date=plan_date,
                            leader_id=item.get("user_id"))
                        InspectionTask.objects.create(
                            plan=plan,
                            name="IST-" + str(int(time.time())),
                            status="waiting_dispatch",
                            work_date=plan.plan_date)
                remainder_number = (data.get("inspections_number") -
                                    planed_count[0].get("count")) % 4
                # 剩余不足4次的情况
                for n in range(remainder_number):
                    plan_date = (datetime.datetime.now() +
                                 datetime.timedelta(n + 3)).date()
                    # 检查计划日期是否可以排计划
                    plan_date = check_plan_date(plan_date, conn,
                                                item.get("user_id"))
                    plan = InspectionPlan.objects.create(
                        station_id=data.get("id"),
                        plan_date=plan_date,
                        leader_id=item.get("user_id"))
                    InspectionTask.objects.create(plan=plan,
                                                  name="IST-" +
                                                  str(int(time.time())),
                                                  status="waiting_dispatch",
                                                  work_date=plan.plan_date)


def check_plan_date(date, conn, leader):
    # 获取计划日期当天已存在的巡检计划数量
    sql = "select count(id) as count from inspection_plan" + \
          " where plan_date='{}' and leader_id={}".format(
              date, leader)
    data = conn.query(sql)
    # 判断计划日期巡检计划是否已达到最大值
    if data[0].get("count") < 10:
        return date
    # 计划日期已达到最大值，计划日期往后延一天
    date = date + datetime.timedelta(1)
    # 如果已经往后延到下个月，则从1号开始
    month_now = datetime.datetime.now().month
    month_plan = date.month
    if month_now != month_plan:
        year, month = datetime.datetime.now().year, datetime.datetime.now(
        ).month
        date_str = "{}-{}-01".format(year, month)
        date = datetime.datetime.strptime(date_str, "%Y-%m-%d")
    check_plan_date(date, conn, leader)
