const xss = require('xss')
const { exec } = require('../db/mysql')
const fs = require('fs');
var request = require('request');

const getList = () => {
    let sql = `select * from bloglist where 1=1 `
    sql += `order by ID desc;`

    // 返回 promise
    return exec(sql)
}

// 获取留言内容
const getLiveList = () => {
    let sql = `select * from livemessage where 1=1 `
    sql += `order by ID desc;`

    // 返回 promise
    return exec(sql)
}

// 获取评论信息
const getcommentList = (id) => {
    let sql = `select * from firstblogcontent where BlogID=${id} `
    sql += `order by ID desc;`

    // 返回 promise
    return exec(sql)
}

// 获取评论回复信息
const getcommentBackList = (id) => {
    let sql = `select * from secondblogcontent where FirstId=${id} `
    sql += `order by ID desc;`

    // 返回 promise
    return exec(sql)
}

// 获取留言回复内容
const getLive2List = (id) => {
    let sql = `select * from secondlivemessage where 1=1 && FirstId=${id}`

    // 返回 promise
    return exec(sql)
}

// 查询点赞IP
const getDianzan = (id) => {
    var IPList = []
    var interfaces = require('os').networkInterfaces();
    for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                IPList.push(alias.address)
            }
        }
    }
    let sql = `select * from dianzan where 1=1 && arcticleId=${id} && IP='${IPList[0]}'`

    // 返回 promise
    return exec(sql)
}

// 获取日记信息
const getDiaryList = () => {
    let sql = `select * from diary where 1=1 `
    sql += `order by ID desc;`
        // 返回 promise
    return exec(sql)
}

// 获取友情链接信息
const getlinkList = (id) => {
    let sql = `select * from url where 1=1 `
        // 返回 promise
    return exec(sql)
}

// 实现单篇博客浏览量加一
const browseAdd = (id) => {
    let sql = `
      update bloglist set BrowseNumber=BrowseNumber+1 where ID=${id}
    `
        // 返回 promise
    return exec(sql)
}

// 获取博客类别
const classFicList = () => {
    let sql = `
       select * from classfic where 1=1
    `
        // 返回 promise
    return exec(sql)
}

// 根据浏览量获取排名前8的博客
const HotARC = () => {
    let sql = `
       select ID,Title from bloglist order by BrowseNumber desc limit 0,8
    `
        // 返回 promise
    return exec(sql)
}

// 获取置顶博客ID
const topBlog = () => {
    let sql = `
       select * from zdtop where 1=1 limit 0,3
    `
        // 返回 promise
    return exec(sql)
}


// 根据博客ID查找博客
const getBlog = (id) => {
    let sql = `
       select * from bloglist where ID=${id}
    `
        // 返回 promise
    return exec(sql)
}

// 根据类别查找博客
const getBlogClass = (id) => {
    let sql = `
       select * from bloglist where CLSM='${id}' 
    `
    sql += `order by ID desc;`
        // 返回 promise
    return exec(sql)
}

// 获取最近访客数据
const getVistor = () => {
    let sql = `select * from lookweb where 1=1 `
    sql += `order by ID desc;`

    // 返回 promise
    return exec(sql)
}

// 搜索功能模糊查询
const getBlogSearch = (id) => {
    let sql = `
       select * from bloglist where Title LIKE '%${id}%' 
    `
    sql += `order by ID desc;`
        // 返回 promise
    return exec(sql)
}
const newBlog = (blogData = {}) => {
    // blogData 是一个博客对象，包含 title content author 属性
    const Title = xss(blogData.Title)
    const CLSM = xss(blogData.CLSM)
        // console.log('title is', title)
    var Content = xss(blogData.Content)
    const HeadImg = blogData.HeadImg
    const Original = blogData.Original
    const ZDF = blogData.ZDF
    const Address = blogData.Address
    const video = blogData.video||'0'
    const file = blogData.file||'0'
    const CreateTime = Date.now()
    var Content = Content.replace(/&gt;/g, ">")

    const writeFileRecursive = function(path, buffer, callback) {
        let lastPath = path.substring(0, path.lastIndexOf("/"));
        fs.mkdir(lastPath, { recursive: true }, (err) => {
            if (err) return callback(err);
            fs.writeFile(path, buffer, function(err) {
                if (err) return callback(err);
                return callback(null);
            });
        });
    }

    const buffer = Content;

    writeFileRecursive('../public/blogFile/' + CreateTime + ".md", buffer, (err) => {
        if (err) console.error(err);
        console.info("write success");
    });

    const sql = `
        insert into bloglist (Title, Content, CreateTime, Original, HeadImg, ZDF, CLSM, BrowseNumber, dianzan, video, file)
        values ('${Title}', '${CreateTime}.md', ${CreateTime}, ${Original}, '${HeadImg}', 0, '${CLSM}', 0, 0, '${video}', '${file}');
    `




    return exec(sql).then(insertData => {
        // console.log('insertData is ', insertData)
        return {
            id: insertData.insertId
        }
    })
}


const updateBlog = (id, blogData = {}) => {
    // id 就是要更新博客的 id
    // blogData 是一个博客对象，包含 title content 属性

    const Title = xss(blogData.Title)
    const Content = xss(blogData.Content)
    const sql = `
        update bloglist set Title='${Title}', Content='${Content}' where ID=${id}
    `

    return exec(sql).then(updateData => {
        // console.log('updateData is ', updateData)
        if (updateData.affectedRows > 0) {
            return true
        }
        return false
    })
}

// 更新博客点赞量
const updateZan = (id) => {
    const sql = `
        update bloglist set dianzan=dianzan+1 where ID=${id}
    `

    return exec(sql).then(updateData => {
        // console.log('updateData is ', updateData)
        if (updateData.affectedRows > 0) {
            return true
        }
        return false
    })
}


// 博客增加点赞
const Blogzan = (blogData) => {
    const arcticleId = blogData.ID
    var IPList = []
    var interfaces = require('os').networkInterfaces();
    for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                IPList.push(alias.address)
            }
        }
    }
    const sql = `
        insert into dianzan (arcticleId, IP)
        values (${arcticleId} , '${IPList[0]}');
        `
    return exec(sql).then(delData => {
        // console.log('delData is ', delData)
        if (delData.affectedRows > 0) {
            return true
        }
        return false
    })
}

const delBlog = (id) => {
    // id 就是要删除博客的 id
    const sql = `delete from bloglist where ID='${id}';`
    return exec(sql).then(delData => {
        // console.log('delData is ', delData)
        if (delData.affectedRows > 0) {
            return true
        }
        return false
    })
}

// 删除分类
const delClassFic = (id) => {
    // id 就是要删除博客的 id
    const sql = `delete from classfic where ID='${id}';`
    return exec(sql).then(delData => {
        // console.log('delData is ', delData)
        if (delData.affectedRows > 0) {
            return true
        }
        return false
    })
}

// 对博客进行评论
const comment1 = (id, blogData = {}) => {
    const BlogContent = xss(blogData.BlogContent)
    const Address = blogData.Address
    const Name = blogData.Name
    const Email = blogData.Email
    const CreateTime = Date.now()
    const qg = blogData.qg

    const sql = `
        insert into firstblogcontent (BlogID, BlogContent, CreateTime, Address, Name, Email, qg)
        values (${id}, '${BlogContent}', ${CreateTime}, '${Address}', '${Name}', '${Email}', '${qg}');
    `

    return exec(sql).then(insertData => {
        // console.log('insertData is ', insertData)
        return {
            id: insertData.insertId
        }
    })
}

// 对评论内容进行回复
const comment2 = (blogData = {}) => {
    const Content = xss(blogData.Content)
    const Address = blogData.Address
    const Name = blogData.Name
    const ToName = blogData.ToName
    const FirstId = blogData.FirstId
    const email = blogData.email
    const CreateTime = Date.now()
    const qg = blogData.qg
    const sql = `
        insert into secondblogcontent (Name, ToName, CreateTime, Address, FirstId, Content, Email, qg)
        values ('${Name}', '${ToName}', ${CreateTime}, '${Address}', ${FirstId}, '${Content}', '${email}', '${qg}');
    `

    return exec(sql).then(insertData => {
        // console.log('insertData is ', insertData)
        return {
            id: insertData.insertId
        }
    })
}

// 置顶博客
const ZDF = (blogData = {}) => {
    const ZDF = blogData.ZDF
    const sql = `
        insert into zdtop (ZDF)
        values (${ZDF});
    `
    return exec(sql).then(insertData => {
        // console.log('insertData is ', insertData)
        return {
            id: insertData.insertId
        }
    })
}

// 新建博客分类
const classFic = (blogData = {}) => {
    const classFic = blogData.classFic
    const CLSM = blogData.CLSM
    const sql = `
        insert into classfic (ClassFic, CLSM)
        values ('${classFic}', '${CLSM}');
    `
    return exec(sql).then(insertData => {
        // console.log('insertData is ', insertData)
        return {
            id: insertData.insertId
        }
    })
}

// 新建留言
const LiveMessage = (blogData = {}) => {
    const LiveMessage = xss(blogData.LiveMessage)
    const CreateTime = Date.now()
    const Address = blogData.Address
    const Name = blogData.Name
    const Email = blogData.Email
    const sql = `
        insert into livemessage (LiveMessage, CreateTime, Address, Name, Email)
        values ('${LiveMessage}', ${CreateTime}, '${Address}', '${Name}', '${Email}');
    `
    return exec(sql).then(insertData => {
        // console.log('insertData is ', insertData)
        return {
            id: insertData.insertId
        }
    })
}


// 新建留言回复
const LiveMessageBack = (blogData = {}) => {
    const FirstId = blogData.FirstId
    const CreateTime = Date.now()
    const ToName = blogData.ToName
    const Address = blogData.Address
    const Name = blogData.Name
    const Content = blogData.Content
    const sql = `
        insert into secondlivemessage (FirstId, ToName, CreateTime, Address, Name, Content)
        values (${FirstId},'${ToName}', ${CreateTime}, '${Address}', '${Name}', '${Content}');
    `
    return exec(sql).then(insertData => {
        // console.log('insertData is ', insertData)
        return {
            id: insertData.insertId
        }
    })
}

// 新建日记表
const diary = (blogData = {}) => {
    const DiaryContent = blogData.DiaryContent
    const CreateTime = Date.now()
    const sql = `
        insert into diary (createTime, DiaryContent)
        values (${CreateTime}, '${DiaryContent}');
    `
    return exec(sql).then(insertData => {
        // console.log('insertData is ', insertData)
        return {
            id: insertData.insertId
        }
    })
}

// 新建友情链接表
const URLList = (blogData = {}) => {
        const URL = blogData.URL
        const Name = blogData.Name
        const Title = blogData.Title
        const Detail = blogData.Detail
        const sql = `
        insert into url (URL, Name, Title, Detail)
        values ('${URL}', '${Name}', '${Title}', '${Detail}');
    `
        return exec(sql).then(insertData => {
            // console.log('insertData is ', insertData)
            return {
                id: insertData.insertId
            }
        })
    }
    // 新建最新访问博客人员列表
const PeopleList = (blogData = {}) => {
    const CreateTime = Date.now()
    const Name = blogData.Name
    const sql = `
        insert into lookweb (CreateTime, Name)
        values (${CreateTime}, '${Name}');
    `
    return exec(sql).then(insertData => {
        // console.log('insertData is ', insertData)
        return {
            id: insertData.insertId
        }
    })
}

module.exports = {
    getList,
    newBlog,
    updateBlog,
    delBlog,
    comment1, // 对博客进行评论
    comment2, // 对评论进行回复
    ZDF, // 对博客进行置顶处理
    classFic, // 新建博客分类
    delClassFic, // 删除博客分类
    LiveMessage, // 新建留言
    LiveMessageBack, // 新建留言回复
    diary, //新建日记表,
    URLList, // 新建友情链接表
    PeopleList, // 新建访问人员列表
    getLiveList, // 获取留言内容
    getLive2List, // 获取二级留言内容
    getDiaryList, // 获取日记内容
    getlinkList, // 获取友情链接信息
    browseAdd, // 实现单篇博客的浏览量加一
    classFicList, // 获取博客类别
    HotARC, // 根据浏览量获取排名前8的文章
    getBlog, // 根据博客ID获取相应博客信息
    topBlog, // 获取置顶博客ID
    getcommentList, // 获取评论信息
    getcommentBackList, // 获取评论回复信息
    getBlogClass, // 根据类别查找博客
    getBlogSearch, // 模糊搜索接口
    getVistor, // 获取最近访客数据
    Blogzan, // 用户IP
    getDianzan, // 查询点赞IP
    updateZan, // 点赞量加一
}