var express = require('express');
var router = express.Router();
var doSQL = require('../mysql/index').doSQL;
const fs = require("fs");
var path = require("path");

router.get('/', function(request, response, next) {
  let page = request.query.page;
  let limit = request.query.limit;
  let formName = request.query.formName;
  let sql = `
    select id,form_name formName,original_type originalType,form_desc formDesc,form_path formPath,DATE_FORMAT(workflow_form.create_time,'%Y-%m-%d') createTime,create_user createUser,sys_user.nick_name createUserName
    from workflow_form
    left join sys_user on workflow_form.create_user = sys_user.user_id
    `;
    const params = [];
    if (formName) {
        sql += ` where form_name like ?`;
        params.push(`%${formName}%`);
    }
    if (page) {
        sql += ` limit ?, ?`;
        params.push(+(page - 1) * limit, +limit);
    }
    getCount(sql, params).then(count => {
        doSQL(sql, params).then(res => {
          if(!res.error){
              response.send(JSON.stringify({
                  code: 200,
                  data: {
                    list: res.data,
                    count: count
                  }
              }));
              
          }else{
              response.send(JSON.stringify({
                  code: 600,
                  message: res.error
              }));
          }
      })
  })

});

// router.get('/fields', function(request, response, next) {
//     let formPath = request.query.path;
//     //读取文件
//     try {
//         let form = require(path.join(__dirname, '../' + formPath));
//         response.send(JSON.stringify({
//             code: 200,
//             data: form.formFields
//         }));
//       } catch (error) {
//         response.send(JSON.stringify({
//             code: 500,
//             msg: `未找到文件${formPath}`
//         }));
//       }
//     // fs.readFile( path.join(__dirname, '../' + formPath), 'utf-8', function(err, data) {
//     //     if (err) {
//     //         response.send(JSON.stringify({
//     //             code: 500,
//     //             msg: `未找到文件${formPath}`
//     //         }));
//     //     } else {
//     //         let json = JSON.stringify(eval(data));
//     //         response.send(JSON.stringify({
//     //             code: 200,
//     //             data: json
//     //         }));
//     //     }
//     // });
  
//   });

router.get('/:id', function(request, response, next) {
    let id = request.params.id;
    let sql = `
      select id,form_name formName,original_type originalType,form_desc formDesc,form_path formPath,DATE_FORMAT(workflow_form.create_time,'%Y-%m-%d') createTime,create_user createUser,sys_user.nick_name createUserName
      from workflow_form
      left join sys_user on workflow_form.create_user = sys_user.user_id
      where id = ?
    `;
    const params = [id];
    doSQL(sql, params).then(res=>{
        if(!res.error){
            let data = res.data[0] || {};
            let formPath = data.formPath;
            //读取文件
            const fullPath = path.join(__dirname, '../' + formPath);
            fs.readFile(fullPath, 'utf8',function(err,res){
                if (err) {
                    data.content = [];
                } else {
                    data.content = JSON.parse(res);
                }
                response.send(JSON.stringify({
                    code: 200,
                    data
                }));
            });
        }else{
            response.send(JSON.stringify({
                code: 600,
                message: res.error
            }));
        }
    })
});


function addForm(fileName, content){
    return new Promise((resolve, reject) => {
        //检测文件是否存在
        let isExist = fs.existsSync(path.join(__dirname, '../form', fileName + '.js'));
        if(isExist){
            reject('文件已存在');
        }else{
        fileName = fileName.indexOf('.js') > -1 ? fileName : fileName + '.js';
        const filePath = path.join(__dirname, '../form', fileName );
    
        fs.writeFile(filePath, content, 'utf8', (err) => {
            if (err) {
                reject(err);
            }else{
                resolve();
            }
        });
        }
    });
}


router.post('/', async function(request, response, next) {
    let { formName, formDesc, userId,formPath = '',fileName,content,type = 1 }  = request.body;
    fileName = fileName || formName;
    let errMsg = '';
    if(!userId){
        errMsg = '创建人不能为空'
    }else if(!formName){
        errMsg = '表单名称不能为空'
    }else if(!formPath && (  !fileName || !content)){
        errMsg = '文件名和表单内容不能为空'
    }
    if(errMsg){
        response.send(JSON.stringify({
            code: 600,
            message: errMsg
        }));
        return;
    }
    
    if( !formPath ){
        type = 2;
        try {
            await addForm(fileName, content)
            formPath = `/form/${fileName}.js`;
        } catch (err) {
            response.send(JSON.stringify({
                code: 600,
                message: err
            }));
            return;
        }
    }
    let sql = `
    insert into workflow_form (form_name, form_desc, form_path, create_time, create_user, original_type)
    values (?, ?, ?, now(), ?, ?)
    `;
    const params = [formName, formDesc, formPath, userId,type];

    doSQL(sql, params).then(res=>{
        if(!res.error){
            response.send(JSON.stringify({
                code: 200,
                message: '新增成功'
            }));
        }else{
            response.send(JSON.stringify({
                code: 600,
                message: res.error
            }));
        }
    })
});

router.delete('/:id', function(request, response, next) {
    let id = request.params.id;
    let sql = `delete from workflow_form where id in (?)`;
    const params = [id];
    doSQL(sql, params).then(res=>{
        if(!res.error){
            response.send(JSON.stringify({
                code: 200,
                message: '删除成功'
            }));
        }else{
            response.send(JSON.stringify({
                code: 600,
                message: res.error
            }));
        }
    })
});

// router.put('/', function(request, response, next) {
//     let { id, formName, formDesc, formPath, userId,content } = request.body;
//     let sql = `
//     update workflow_form 
//     set form_name = ?, form_desc = ?, form_path = ?
//     where id = ?
//     `;
//     const params = [formName, formDesc, formPath, id];
//     doSQL(sql, params).then(res => {
//         if(!res.error) {
//             response.send(JSON.stringify({
//                 code: 200,
//                 message: '修改成功'
//             }));
//         } else {
//             response.send(JSON.stringify({
//                 code: 600, 
//                 message: res.error
//             }));
//         }
//     })
// });
router.put('/', async function(request, response, next) {
    let { id, formName, formDesc, userId, content ,formPath} = request.body;
    let errMsg = '';
    if (!id) {
        errMsg = 'ID 不能为空';
    } else if (!userId) {
        errMsg = '修改人不能为空';
    } else if (!formName) {
        errMsg = '表单名称不能为空';
    }
    if (errMsg) {
        return response.status(400).send({
            code: 400,
            message: errMsg
        });
    }

    try {
        // 根据 id 查询原数据
        const originalData = await doSQL('SELECT * FROM workflow_form WHERE id = ?', [id]);
        if (originalData.data.length === 0) {
            return response.status(404).send({
                code: 404,
                message: '未找到对应的表单'
            });
        }
        const originalFormPath = originalData.data[0].form_path;
        let newFormPath;
        if( content && content.length > 0){
            newFormPath = `/form/${formName}.js`;
            if (originalFormPath !== newFormPath) {
                // 检查新文件是否存在
                const newFilePath = path.join(__dirname, '../', newFormPath);
                if (fs.existsSync(newFilePath)) {
                    return response.status(400).send({
                        code: 400,
                        message: '表单名已存在'
                    });
                }
            }
            // 删除原文件
            if (originalFormPath) {
                const filePath = path.join(__dirname, '../', originalFormPath);
                fs.unlinkSync(filePath);
            }
            try {
                await addForm(formName, content)
            } catch (err) {
                response.send(JSON.stringify({
                    code: 600,
                    message: err
                }));
                return;
            }
        }else{
            newFormPath = formPath || originalFormPath;
        }
        // 更新数据库中的记录
        const sql = `
            update workflow_form 
            set form_name = ?, form_desc = ?, form_path = ?, create_time = ?, create_user = ?
            where id = ?
        `;
        const params = [formName, formDesc, newFormPath, new Date(), userId, id];
        const res = await doSQL(sql, params);

        if (!res.error) {
            response.send({
                code: 200,
                message: '修改成功'
            });
        } else {
            response.send({
                code: 600,
                message: res.error
            });
        }
    } catch (error) {
        console.error('Failed to update form:', error);
        response.status(500).send({
            code: 500,
            message: 'Failed to update form'
        });
    }
});







function getCount(sql, params) {
    let countSql = `select count(1) count from (${sql.split('limit')[0]}) a`;
    return new Promise((resolve, reject) => {
      doSQL(countSql, params).then(res => {
        resolve(res.data[0].count);
      }).catch(err => {
        reject(err);
      });
    });
}

module.exports = router;
