const express = require('express');
const router = express.Router();
const rt = require('../ResTool');
const config = require('../../config.json');
const mysql = require('../../libs/mysql_cls');
const tool = require('../../includes/apiTool');

router
    .get('/', (req, res) => {
        res.send({ name: 'WebIO IOGroup API' });
    })
    .post(['/getiogrouplist', '/getiogroup'], (req, res, n) => {
        if (!config.permission.iogroup) return n('ERR9000');
        let s = false;
        let arr = req.body;
        if (req.url == '/getiogroup') {
            s = true;
            if (!arr.data) return n('ERR0000');
            if (!arr.data.id) return n('ERR0028');
        }

        res.db = new mysql();
        res.db.user = config.db.user;
        res.db.password = config.db.pass;
        res.db.host = config.db.host;
        res.db.port = config.db.port;
        res.db.database = config.db.db1;
        res.db.connect();

        let query = "select * from ??.?? ";
        let order = " order by `iogroupuid` desc ";
        let param = [config.db.db1, 'iogroup'];
        if (s) {
            query += " where `iogroupuid` = ? ";
            param.push(arr.data.id);
        }

        res.db.query(query + order, param, (err, row) => {
            if (err) return n('ERR8000');

            let dos = [];
            let les = [];
            for (var i in row) {
                let str = row[i].iogroupid;
                let tmp = str.split(',');
                if (tmp.length == 0) continue;
                for (var j in tmp) {
                    if (/^do([0-9]+)$/.test(tmp[j])) {
                        let n = tmp[j].replace(/^do([0-9]+)$/, '$1');
                        dos.push(n);
                    } else if (/^le([0-9]+)$/.test(tmp[j])) {
                        let n = tmp[j].replace(/^le([0-9]+)$/, '$1');
                        les.push(n);
                    }
                }
            }

            let doarr = [];
            let leonearr = [];

            let pros = [];

            if (dos.length > 0) {
                let query = "select * from ??.?? where `douid` in (?)";
                let param = [config.db.db1, 'dolist', dos];
                pros.push(tool.promiseQuery(res, query, param, 'do'));
            }
            if (les.length > 0) {
                let query = "select * from ??.?? where `leonelistuid` in (?)";
                let param = [config.db.db1, 'leonelist', les];
                pros.push(tool.promiseQuery(res, query, param, 'leone'));
            }

            Promise.all(pros)
                .then(r => {
                    for (var i in r) {
                        if (r[i].key == 'do') doarr = r[i].data;
                        else if (r[i].key == 'leone') leonearr = r[i].data;
                    }

                    let data = {};
                    data.record = tool.checkArray(row);
                    data.rt = {};
                    data.rt.do = tool.checkArray(doarr);
                    data.rt.leone = tool.checkArray(leonearr);
                    res.api_res = data;
                    return n();
                })
                .catch(err => {
                    if (err) return n('ERR8000');
                });
        });
    })
    .post('/addiogroup', (req, res, n) => {
        if (!config.permission.iogroup) return n('ERR9000');
        if (!tool.checkPermission(req)) return n('ERR9000');
        let arr = req.body;
        if (!arr.data) return n('ERR0000');
        if (!arr.data.name) return n('ERR0026');
        if (!arr.data.devs) return n('ERR0029');

        res.db = new mysql();
        res.db.user = config.db.user;
        res.db.password = config.db.pass;
        res.db.host = config.db.host;
        res.db.port = config.db.port;
        res.db.database = config.db.db1;
        res.db.connect();

        let query = "insert into ??.?? (`iogroupname`,`iogroupid`,`iogroup_add_date`) values (?, ?, unix_timestamp())";
        let param = [config.db.db1, 'iogroup', arr.data.name, arr.data.devs];

        res.db.query(query, param, (err, row) => {
            if (err) return n('ERR8001');

            let data = {};
            data.record = [];
            res.api_res = data;
            return n();
        });
    })
    .post('/editiogroup', (req, res, n) => {
        if (!config.permission.iogroup) return n('ERR9000');
        if (!tool.checkPermission(req)) return n('ERR9000');
        let arr = req.body;
        if (!arr.data) return n('ERR0000');
        if (!arr.data.id) return n('ERR0028');
        if (!arr.data.name) return n('ERR0026');
        if (!arr.data.devs) return n('ERR0029');

        res.db = new mysql();
        res.db.user = config.db.user;
        res.db.password = config.db.pass;
        res.db.host = config.db.host;
        res.db.port = config.db.port;
        res.db.database = config.db.db1;
        res.db.connect();

        let query = "update ??.?? set \
			`iogroupname` = ?, \
			`iogroupid` = ?, \
			`iogroup_modify_date` = unix_timestamp() \
			where \
			`iogroupuid` = ?";
        let param = [config.db.db1, 'iogroup', arr.data.name, arr.data.devs, arr.data.id];
        res.db.query(query, param, (err, row) => {
            if (err) return n('ERR8002');

            let data = {};
            data.record = [];
            res.api_res = data;
            return n();
        });
    })
    .post('/deliogroup', (req, res, n) => {
        if (!config.permission.iogroup) return n('ERR9000');
        if (!tool.checkPermission(req)) return n('ERR9000');
        let arr = req.body;
        if (!arr.data) return n('ERR0000');
        if (!arr.data.id) return n('ERR0028');

        res.db = new mysql();
        res.db.user = config.db.user;
        res.db.password = config.db.pass;
        res.db.host = config.db.host;
        res.db.port = config.db.port;
        res.db.database = config.db.db1;
        res.db.connect();

        let query = "delete from ??.?? where `iogroupuid` = ? ";
        let param = [config.db.db1, 'iogroup', arr.data.id];
        res.db.query(query, param, (err, row) => {
            if (err) return n('ERR8003');

            let data = {};
            data.record = [];
            res.api_res = data;
            return n();
        });
    })
    .all('*', rt.send);

module.exports = router;