/**
 * @name: createTask
 * @author: alan
 * @date: 2022-09-14 13:24
 * @description：createTask
 * @update: 2022-09-14 13:24
 */
const dayjs = require('dayjs');
const axios = require('axios');
const {v4: uuidv4} = require("uuid");
const {pica_db, pica_message_db} = require("./connectionMysql");

class TaskServer {
  constructor() {

  }

  computedMonth(frequency) {
    frequency = Number(frequency);
    const minute = new Date().getMinutes();
    let totalMinute = minute + frequency;
    let propMinute = minute - frequency;
    let minuteList = [];
    while (propMinute > 0) {
      minuteList.push(propMinute);
      propMinute -= frequency;
    }
    minuteList = minuteList.reverse();

    while (totalMinute < 60) {
      minuteList.push(totalMinute);
      totalMinute += frequency;
    }
    return minuteList;
  }

  setSelectSql(frequency, conditionsField, sql) {
    let sqlList = sql.split('where');
    const startTime = dayjs(new Date()).add(-frequency, 'minute').format('YYYY-MM-DD HH:mm:ss');
    const endTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss');
    if (sqlList.length > 1) {
      sqlList[1] += ` and ${conditionsField} >= '${startTime}' and ${conditionsField} <= '${endTime}'`;
      sql = sqlList.join('where');
    } else {
      sql += ` where ${conditionsField} >= '${startTime}' and ${conditionsField} <= '${endTime}'`;
    }
    return sql;
  }

  sendMessage(messageText, robotUrl) {
    const data = {
      "text": {
        "content": messageText
      },
      "msgtype": "text"
    };
    let result = axios(robotUrl, {
      method: "POST",
      headers: {//自定义header
        "Accept": "*/*",
        "Content-Type": "application/json;charset=utf-8"
      },
      data: data,
      dataType: 'json',
    }).then(result => {
      return res.send(result.data);
    });
  }

  // 新增job
  insert(taskInfo) {
    const {uuid, title, name, sql_content, frequency, conditions_field, robot_url, key_list, search_sql} = taskInfo;
    const insertSql = `insert into p_push_task_message
        (uuid, title, name, frequency, conditions_field, robot_url, sql_content, status, key_list, search_sql)
        values('${uuid}', '${title || ''}', '${name || ''}',
        "${frequency}", "${conditions_field}" , "${robot_url}",
        "${sql_content}", 1, '${JSON.stringify(key_list)}', ${JSON.stringify(search_sql)})`;
    return new Promise((resolve, reject) => {
      pica_message_db.query(insertSql, (err, result) => {
        if (err) {
          return;
        }
        resolve(true);
      });
    });
  }

  // 更新job
  update(taskInfo) {
    const {uuid, title, name, sql_content, frequency, conditions_field, robot_url, key_list, search_sql} = taskInfo;
    const updateSql = `update p_push_task_message set
      title="${title}",name="${name}",sql_content="${sql_content}",frequency="${frequency}",
      conditions_field="${conditions_field}",robot_url="${robot_url}",
      key_list='${JSON.stringify(key_list)}',search_sql="${search_sql}"
      where uuid="${uuid}"`;
    return new Promise((resolve, reject) => {
      pica_message_db.query(updateSql, (err, result) => {
        if (err) {
          resolve(false);
        }
        resolve(result);
      });

    });
  }

  // 根据Id查对应的任务数据
  searchTaskById(uuid) {
    return new Promise((resolve, reject) => {
      const selectSql = `select * from p_push_task_message where uuid='${uuid}'`;
      pica_message_db.query(selectSql, (err, result) => {
        if (err) {
          resolve([]);
        }
        resolve(result);
      })
    });
  }

  // 查所有任务
  getTaskList() {
    return new Promise((resolve, reject) => {
      const selectSql = `select * from p_push_task_message;`;
      pica_message_db.query(selectSql, (err, result) => {
        if (err) {
          resolve([]);
        }
        resolve(result);
      })
    })
  }

  // 根据id删除job
  delTaskById(uuid) {
    return new Promise((resolve, reject) => {
      const delSql = `delete from p_push_task_message where uuid='${uuid}'`;
      pica_message_db.query(delSql, (err, result) => {
        if (err) {
          resolve(false);
        }
        resolve(true);
      });
    });
  }

  // 新增数据库配置
  createConfig(connection_url, port, root, password, db_name) {
    const create_sql = `insert into p_push_mysql_config
        (connection_url, port, root, password, db_name)
        values('${connection_url || ''}', '${port || ''}', '${root || ''}', '${password || ''}', '${db_name || ''}')`;
    return new Promise((resolve, reject) => {
      pica_message_db.query(create_sql, (err, result) => {
        if (err) {
          resolve(false)
        }
        resolve(result);
      })
    })

  }

}

module.exports = new TaskServer();
