/**
 * 工时表
 */

import { mysqlDB } from "../../db/mysqlInit";
const Sequelize =require('sequelize')
//创建StudentModel模型，该模型对应的表名是student

let workinglogModel;
export async function initModel() {
    var model = mysqlDB.define('workinglog',{
        id:{
            type:Sequelize.STRING(100), //表示属性的数据类型
            primaryKey:true,  //表示主键
            allowNull:false,   //表示当前列是否允许为空，false表示该列不能为空
            unique:true    //表示该列的值必须唯一
        },
        projectId:{ type:Sequelize.STRING(100), allowNull:false }, //项目号
        userId:{ type:Sequelize.INTEGER, allowNull: false },//填报人
        time:{ type:Sequelize.INTEGER, allowNull:false },//工时
        dateKey:{ type:Sequelize.DATE, allowNull:false },//填报时间
        isOutside:{ type:Sequelize.INTEGER },//是否外出 0=否 1=是
        workLog:{ type:Sequelize.STRING(200)}, //工作内容
    },{
        freezeTableName:true, //true表示使用给定的表名，false表示模型名后加s作为表名
        timestamps:false  //true表示给模型加上时间戳属性(createAt、updateAt),false表示不带时间戳属性
    });
    // //同步数据库，force的值为false，表若存在则先删除后创建，force的值为true表示表若存在则不创建
    workinglogModel = await model.sync({});
}

//获取今日时长
export async function findWorkingLogLengthByDateKey(userId:number, dateKey:string) {
    
    let count = 0;
    let dataList = await workinglogModel.findAll({
        where:{userId:userId, dateKey:dateKey}
    });
    dataList.forEach(info => {
        count += info.time;
    });
    return count;
}


//获取本周工时记录
export async function findThisWeekWorkingLog(userId:number, startTime:string, endTime:string) {
    let sql = `select workinglog.workLog, workinglog.id as id,workinglog.projectId as projectId, project.name as projectName, workinglog.time, workinglog.dateKey, `;
    sql += `workinglog.isOutside from workinglog INNER JOIN project on project.id = workinglog.projectId where userId = ${userId} and dateKey > "${startTime}" and dateKey < "${endTime}" `
    let res = await mysqlDB.query(sql, { type: mysqlDB.QueryTypes.SELECT } );
    let dataList = [];
    res.forEach(info => {
        dataList.push(info);
    });
    return dataList;
}




/**
 * 获取所有工时记录  按时间分
 * 带分页
 * @param startIndex 
 * @param startTime 
 * @param endTime 
 * @returns 
 */
export async function findAllWorkingLogToPage(startIndex:number, startTime:string, endTime:string) {
    let sql = `SELECT workinglog.workLog, workinglog.projectId AS projectId, project.NAME AS projectName, workinglog.time, workinglog.dateKey, workinglog.isOutside, users.name, users.departmentId `;
    sql += `FROM workinglog INNER JOIN project ON project.id = workinglog.projectId inner JOIN users on users.userId = workinglog.userId `;
    if (startTime && endTime) {
        sql += ` where workinglog.dateKey > "${startTime}" and workinglog.dateKey < "${endTime}"`;
    }
    sql += `LIMIT ${startIndex},10`;
    let res = await mysqlDB.query(sql, { type: mysqlDB.QueryTypes.SELECT } );
    let dataList = [];
    res.forEach(info => {
        dataList.push(info);
    });
    let countSql = `SELECT workinglog.workLog, workinglog.projectId AS projectId, project.NAME AS projectName, workinglog.time, workinglog.dateKey, workinglog.isOutside, users.name, users.departmentId `;
    countSql += `FROM workinglog INNER JOIN project ON project.id = workinglog.projectId inner JOIN users on users.userId = workinglog.userId`
    if (startTime && endTime) {
        countSql += ` where dateKey > "${startTime}" and dateKey < "${endTime}"`;
    }
    let countRes = await mysqlDB.query(countSql, { type: mysqlDB.QueryTypes.SELECT } );
    return {dataList, count:countRes.length};
}


/**
 * 获取所有工时记录  按时间分
 * 不带分页
 * @param startTime 
 * @param endTime 
 * @returns 
 */
export async function findAllWorkingLog( startTime:string, endTime:string) {
    let sql = `SELECT workinglog.workLog, workinglog.projectId AS projectId, project.NAME AS projectName, workinglog.time, workinglog.dateKey, workinglog.isOutside, users.name, users.departmentId `;
    sql += `FROM workinglog INNER JOIN project ON project.id = workinglog.projectId inner JOIN users on users.userId = workinglog.userId `
    if (startTime && endTime) {
        sql += ` where workinglog.dateKey > "${startTime}" and workinglog.dateKey < "${endTime}"`;
    }
    let res = await mysqlDB.query(sql, { type: mysqlDB.QueryTypes.SELECT } );
    return res;
}

/**
 * 获取所有工时记录 按项目分
 * @param startTime 
 * @param endTime 
 * @returns 
 */
export async function findAllWorkingLogToProject(startTime:string, endTime:string) {
    let sql = `SELECT workinglog.projectId AS projectId, project.NAME AS projectName, workinglog.time `;
    sql += `FROM workinglog INNER JOIN project ON project.id = workinglog.projectId `;
    if (startTime && endTime) {
        sql += ` where workinglog.dateKey > "${startTime}" and workinglog.dateKey < "${endTime}"`;
    }
    return await mysqlDB.query(sql, { type: mysqlDB.QueryTypes.SELECT } );
}

//添加工时
export async function addWorkingLog(id:string, projectId:string, userId:number, time:number, dateKey:string, isOutside:number, workLog:string) {
    await workinglogModel.create({id, projectId, userId, time, dateKey, isOutside, workLog});
}

//修改工时信息
export async function updateWorkinglog(id:string, projectId:string, time:number, isOutside:number, workLog:string) {
    await workinglogModel.update({projectId, time, isOutside, workLog}, {where:{id}});
}


export async function findWorkingLogById(id:string) {
    let dataList = await workinglogModel.findAll({
        where:{id}
    });
    return dataList[0] || {};
}


export async function deleteWorkingLogById(id:string) {
    return await workinglogModel.destroy({where:{id}});
}