const express = require('express')
const request = require("request");
const Mysql = require("../SQLPool");
const router = express.Router()

router.get('/addToolBox', (req, res) => {
    const {toolbox_name, toolbox_icon, toolbox_desc, toolbox_url, type_id, child_type_id} = req.query
    const SQL = 'INSERT INTO toolbox (toolbox_name, toolbox_icon, toolbox_desc, toolbox_url,sort_id) VALUES (?,?,?,?,?)'

    Mysql.query(SQL, [toolbox_name, toolbox_desc, toolbox_icon, toolbox_url, 0], (err, result) => {
        if (err) {
            res.send({
                success: false,
                err
            })
            return
        }
        request(domain + '/query/queryToolBox', {}, (error, response, body) => {
            console.log(domain + '/query/queryToolBox')
            console.log('body:',body)
            const data = JSON.parse(body).data
            const lastToolBoxId = data[data.length - 1].toolbox_id
            const SQL = 'INSERT INTO type_childtype_toolbox (toolbox_id,type_id,child_type_id) VALUES (?,?,?)'
            Mysql.query(SQL, [lastToolBoxId,type_id,child_type_id], (err, result) => {
                if (err) {
                    res.send({
                        success: false,
                        err
                    })
                    return
                }
                res.send({
                    success: true
                })
            })
        })
    })
})

router.get('/addType', (req, res) => {
    const {type_name, child_type_name, type_id} = req.query
    console.log(req.query)
    let SQL = 'INSERT INTO type (type_name) VALUES (?)'
    const values = []
    if (child_type_name && type_id) {
        SQL = 'INSERT INTO child_type (child_type_name, type_id) VALUES (?,?)'
        values.push(child_type_name)
        values.push(type_id)
    } else {
        values.push(type_name)
    }
    console.log(values)
    try {
        Mysql.query(SQL, values, (err, result) => {
            if (err) {
                res.send({
                    success: false,
                    err
                })
                throw err
            }
            res.send({
                success: true,
                data: result
            })
        })
    } catch (e) {
        console.error(e)
    }
})


module.exports = router
