var express = require('express');
const util = require('util');
var router = express.Router();
const schedule = require('node-schedule');
const TaskServer = require('../src/taskServer');
const {v4: uuidv4} = require('uuid');
const client = require('../src/connectionRedis');
const {pica_db} = require('../src/connectionMysql');
const taskServer = require('../src/taskServer');
const dayjs = require("dayjs");
const Util = require('../src/util');


/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});


router.post('/getTcmPayList', async (req, res) => {
  let {beginDate, endDate} = req.body;
  const hasDate = beginDate ? `where timestamp(created_time) between ${beginDate} and ${endDate}` : '';
  const tcmOrderQuery = `select * from pica.w_reward_pay_record ${hasDate}`
  pica_db.query(tcmOrderQuery, (err, result) => {
    console.log('err---', err);
    console.log('result', result);
    if (result == null || result.length === 0) {
      return;
    }
    // res.send({message: 'success'});
    res.json({
      code: 200,
      message: "操作成功",
      data: result
    });
  });

});

router.post('/createTask', async (req, res) => {
  let {uuid, frequency, conditions_field, robot_url, sql_content, key_list} = req.body;
  frequency = Number(frequency);
  const minuteList = taskServer.computedMonth(frequency);
  var rule = new schedule.RecurrenceRule();
  rule.second = 0;
  rule.minute = minuteList;

  if (uuid) {
    // 更新任务
    let search_sql = taskServer.setSelectSql(frequency, conditions_field, sql_content);
    const updateResult = await taskServer.update({...req.body, uuid, search_sql});
  } else {
    let uuid = uuidv4();
    // 创建任务
    let search_sql = taskServer.setSelectSql(frequency, conditions_field, sql_content);
    const insertResult = await taskServer.insert({...req.body, uuid, search_sql});
    // 创建job
    schedule.scheduleJob(uuid, rule, async () => {
      // 查询job是否还有效，若失效，则取消job
      const statusResult = await taskServer.searchTaskById(uuid);
      if (statusResult.length > 0) {
        // job的查询，若有数据，则推送消息
        // sql_content = taskServer.setSelectSql(frequency, conditions_field, sql_content);
        pica_db.query(search_sql, (err, result) => {
          if (result == null || result.length === 0) {
            return;
          }
          let message = '';
          // 拼接数据，每条数据推送一次
          result.forEach(resultItem => {
            key_list.forEach(item => {
              if (item.key.indexOf(',') >= 0) {
                const fieldList = item.key.split(',');
                message += `${item.value}:`
                fieldList.forEach(field => {
                  message += ` ${resultItem[field]}`
                });
                message += '\n';
              } else {
                let resultValue = resultItem[item.key];
                if (util.isDate(resultValue)) {
                  resultValue = dayjs(resultValue).format('YYYY-MM-DD HH:mm:ss');
                }
                message += `${item.value}: ${resultValue}\n`
              }
            });
            taskServer.sendMessage(message, robot_url);
          });
        });
      } else {
        schedule.cancelJob(uuid);
      }
    });
    res.send(Util.sendAction(insertResult));
  }

  /*const query = `select id, name, province_name, city_name, hospital, creat_time, (CASE WHEN status = 1 THEN '未认证' WHEN status = 2 THEN '认证中' WHEN status = 3 THEN '认证通过' WHEN status = 4 THEN '认证不通过' ELSE '重新认证失败' END)AS status from pica.p_doctor where creat_time <= '2017-03-14 00:00:00'`;
  db.query(query, (err, result) => {
    console.log(result);
    result.forEach(item => {
      const creatTime = util.isDate(item.creat_time);
      const id = util.isDate(item.id);
      const str = util.isDate(item.name);
      console.log(creatTime, id, str);
    })
  });*/
});

router.get('/getTaskList', async (req, res) => {
  const result = await taskServer.getTaskList();
  if (result.length > 0) {
    res.send(Util.sendModule(result));
  } else {
    res.send(Util.sendModule([]));
  }
});

router.post('/delTaskById', async (req, res) => {
  const {uuid} = req.body;
  if (uuid) {
    const result = await taskServer.delTaskById(uuid);
    res.send(Util.sendAction(result));
  }
});

router.post('/addConfig', async (req, res) => {
  const {connection_url, port, root, password, db_name} = req.body;
  const configResult = await taskServer.createConfig({connection_url, port, root, password, db_name});

});

router.get('/healthPing', function (req, res) {
  res.send({message: '成功'});
});

router.get('/setData', function (req, res) {
  client.hSet('testing:alan', 'name', 'alan').then(result => {
    res.send({message: 'success'});
  }).catch(e => {
    console.log(e);
  })
})

router.get('/getData', function (req, res) {
  client.hGet('testing:alan', 'name').then(result => {
    res.send({message: 'success'});
  })
})

module.exports = router;
