var mysql = require('mysql');
var fs=require('fs')
var path=require('path')
var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "imeetu"
});



con.connect(function(err) {
    for(var i=1;i<=93;i++){
        if (err) throw err;
        con.query(`SELECT MEETING_TITLE FROM meeting_records where MEETING_ID=${i}`, function (err, result, fields) {
        if (err) throw err;
            //console.log(result);
            var string=JSON.stringify(result);
            //console.log(string)
            var json =  JSON.parse(string);
            var SQLtitle=json[0].MEETING_TITLE
            SQLtitle=SQLtitle.replace(/\s*/g,"");
            readfile(SQLtitle)
        });
    }
});



function updateSQL(MEETING_ATTACH_NAME,TITLE){
    var mysql = require('mysql');
    var fs=require('fs')
    var path=require('path')
    var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "imeetu"
    });


    console.log(MEETING_ATTACH_NAME+'-----'+TITLE)
    con.connect(function(err) {
        if (err) throw err;
        var sql = `UPDATE meeting_records SET MEETING_ATTACH_NAME = "${MEETING_ATTACH_NAME}" WHERE MEETING_TITLE = "${TITLE}"`;
        console.log(sql)
        con.query(sql, function (err, result) {
          if (err) throw err;
          console.log(result.affectedRows + " record(s) updated");
        });
      });
}

//  updateSQL(`222`,'1')

function readfile(title) {
    var filename=''
    fs.readdir(
        path.resolve(`C:/Users/yangjiaxiang/Desktop/imeetu-柏勳/minutesFiles/${title}/附件`, ''),
        (err, files) => {
            if (err) throw err;
            for (let file of files) {
                //console.log(file);
                if(filename==''){
                    filename=`['${file}'`
                    //console.log('undefined')
                }else{
                    file=`,'${file}'`
                    filename=filename+file
                }
            }
            filename=filename+']'           
            if(filename==']'){
                filename =''
            }else{
                
            }
            console.log(title)
            console.log(filename)
            console.log('================')
            updateSQL(filename,title)
        });
    
}
