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

router.get('/queryType', (req, res) => {
    const SQL = 'SELECT * FROM type'
    Mysql.query(SQL, (err, result) => {
        if (err) {
            res.send({
                success: false,
                err
            })
        }
        res.send({
            success: true,
            data: result
        })
    })
});

router.get('/queryChildType', (req, res) => {
    const {type_id} = req.query
    const SQL = 'SELECT child_type.child_type_id, child_type.child_type_name, child_type.type_id FROM child_type INNER JOIN type ON child_type.type_id = type.type_id WHERE type.type_id = ?'
    Mysql.query(SQL,[type_id], (err, result) => {
        if (err) {
            res.send({
                success: false,
                err
            })
        }
        res.send({
            success: true,
            data: result
        })
    })
});


router.get('/queryToolBox', (req, res) => {
    let {isFollow, type_id} = req.query
    let SQL = `SELECT toolbox.*, type_childtype_toolbox.child_type_id FROM type_childtype_toolbox INNER JOIN toolbox ON type_childtype_toolbox.toolbox_id = toolbox.toolbox_id WHERE type_childtype_toolbox.type_id = ?`
    if (!isFollow && !type_id){
        SQL = `SELECT * FROM toolbox`
    }
    if (isFollow) {
        type_id = JSON.parse(type_id)
        SQL = 'SELECT * FROM toolbox WHERE toolbox_id IN (?)'
    }
    Mysql.query(SQL, [type_id], (err, result) => {
        if (err) {
            res.send({
                success: false,
                err
            })
            throw err
        }

        res.send({
            success: true,
            data: result
        })
    })
});

// router.get('/queryToolBoxSortId', (req, res) => {
//     const SQL = 'SELECT sortId FROM toolbox'
//     Mysql.query(SQL, (err, result) => {
//         if (err) {
//             res.send({
//                 success: false,
//                 err
//             })
//             throw err
//         }
//         const _result = []
//         result.map(v => _result.push(v["sortId"]))
//         res.send({
//             success: true,
//             data: _result.sort((a, b) => a - b)
//         })
//     })
// })

module.exports = router
