/**
 * 工时逻辑
 * 作者:lxm
 * 包括工时填报
 */

import moment = require("moment");
import { ERRORENUM } from "../config/errorEnum";
import * as projectData from "../data/admin/project";
import * as workinglogData from "../data/admin/workinglog";
import { BizError } from "../util/bizError";
import * as tools from "../util/tools";
import { findDepartmentMap } from "../data/admin/department";
import { count } from "console";


/**
 * 填报工时
 * @param userId 
 * @param dataList 
 */
export async function addWorking(userId:number, time:number, projectId:string, isOutside:boolean, date:string, workLog:string ) {

    const DateKey = tools.getWorkingDateKey(date);
    let selectKey = moment(date).format("YYYY-MM-DD")+ ' 18:00:00'
    let timeCount = await workinglogData.findWorkingLogLengthByDateKey(userId, selectKey);
    if (timeCount + time >= 24) throw new BizError(ERRORENUM.工时填报时长出错, `${timeCount + time } >= 24`);
    // if (logCount>0) throw new BizError(ERRORENUM.重复提交, `${DateKey}工时填报重复提交`);

    //查找项目编号
    let projectInfo = await projectData.findOnceProjectById(projectId);
    if ( !projectInfo ) throw new BizError(ERRORENUM.不存在该项目, `${userId} 填报 ${projectId}`);

    let id = tools.getWorkingLogId(userId);

    let outside = isOutside ? 1 : 0;
    await workinglogData.addWorkingLog(id, projectId, userId, time, selectKey, outside, workLog);

    return {isSuccess:true, message:"添加成功"};
}


/**
 * 查看本周填报的工时
 * 本周的规则是:周一到周日
 * @param userId 
 * @returns 
 */
export async function workinglogList(userId:number) {
    //获取这周开始时间
    // let s = moment(new Date()).weekday(0).format("YYYY-MM-DD") + ' 00:00:00';
    // let e = moment(new Date()).weekday(6).format("YYYY-MM-DD") + ' 23:59:59';
    let weekofday = parseInt(moment().format('d')) // 计算今天是这周第几天 周日为一周中的第一天
    if (weekofday == 0) weekofday = 7;
    let s = moment().subtract(weekofday,'days').format('YYYY-MM-DD') + ' 00:00:00';// 周-日期
    let e = moment().add(7 - weekofday, 'days').format('YYYY-MM-DD') + ' 23:59:59';// 周日期

    let thisWeekLog = await workinglogData.findThisWeekWorkingLog(userId, s, e);

    let timeCount = 0;
    thisWeekLog.forEach(info => {
        info.dateKey = moment(info.dateKey).format("YYYY-MM-DD");
        timeCount += info.time;
        info.isOutside = info.isOutside == 1;
    })
    //获取这周结束时间
    return { dataList:thisWeekLog, timeCount };
}


export async function updateWorkinglog(userId:number, id:string, time:number, projectId:string, isOutside:boolean, workLog:string) {
    let s = moment().weekday(1).format("YYYY-MM-DD") + ' 00:00:00';
    let e = moment().weekday(7).format("YYYY-MM-DD") + ' 23:59:59';
    let thisWeekLog = await workinglogData.findThisWeekWorkingLog(userId, s, e);

    let checkDateKey = 0;
    thisWeekLog.forEach(info => {
        if (info.id == id) {
            checkDateKey = new Date(info.dateKey).getDate();
        }
    });
    if (!checkDateKey) throw new BizError(ERRORENUM.未找到该数据, id);

    let count = time;
    thisWeekLog.forEach(info => {
        if (new Date(info.dateKey).getDate() == checkDateKey && info.id != id ) {
            count += info.time;
        }
    });
    if (count >= 24) throw new BizError(ERRORENUM.工时填报时长出错, `${ count } >= 24`);

    let outside = isOutside ? 1 : 0;
    await workinglogData.updateWorkinglog(id, projectId, time, outside, workLog);

    return { isSuccess:true, message:"修改成功" };
}


export async function delWorkinglog(userId:number, id:string,) {

    let dataInfo = await workinglogData.findWorkingLogById(id);
    if (!dataInfo) throw new BizError(ERRORENUM.未找到该数据, id);

    await workinglogData.deleteWorkingLogById(id);

    return { isSuccess:true, message:"删除成功" };
}


/**
 * 工时管理列表 按时间分
 * @param page 
 * @param startMs
 * @param endMs
 * @returns 
 */
export async function adminWorkLogForTime(page:number, startMs:string, endMs:string) {
    let s = null;
    let e = null;
    if (startMs && endMs) {
        s = moment(startMs).format("YYYY-MM-DD") + ' 00:00:00';
        e = moment(endMs).format("YYYY-MM-DD") + ' 23:59:59';
    }
    

    let {dataList, count} = await workinglogData.findAllWorkingLogToPage((page-1 )*10, s, e);

    const DepartmentMap = await findDepartmentMap();

    let result = [];

    dataList.forEach(info => {
        let year = moment(info.dateKey).year();
        let month = moment(info.dateKey).month()+1;
        let day = moment(info.dateKey).date();
        result.push({
            year,
            month,
            day,
            name:info.name,
            departmentName : DepartmentMap[info.departmentId],
            projectName:info.projectName,
            projectId:info.projectId,
            workLog:info.workLog,
            time: info.time
        });
    });

    return {dataList:result, total:count };
}


/**
 * 工时管理列表 按项目分
 * @param page 
 * @param startMs 
 * @param endMs 
 * @returns 
 */
export async function adminWorkLogForProject(page:number, startMs:string, endMs:string) {
    let s = null;
    let e = null;
    if (startMs && endMs) {
        s = moment(startMs).format("YYYY-MM-DD") + ' 00:00:00';
        e = moment(endMs).format("YYYY-MM-DD") + ' 23:59:59';
    }
    
    let workingLog = await workinglogData.findAllWorkingLogToProject(s, e);

    let distinctMap = {};// => {name:{id:"", count:0}}

    workingLog.forEach(info => {
        if (!distinctMap[info.projectName]) distinctMap[info.projectName] = {id:info.projectId, count:0 }
        distinctMap[info.projectName].count += info.time;
    });

    let result = [];
    for (let name in distinctMap) {
        let {id, count} = distinctMap[name];
        let dayCount = Math.ceil(count/8 * 100)/100
        result.push({
            name,
            id,
            hostCount:count,
            dayCount
        });
    }

    return {dataList:result.splice((page-1)*10, 10 ), total:result.length };
}


/**
 * 导出按时间分的工时管理列表
 * @param startMs 
 * @param endMs 
 * @returns 
 */
export async function outPutAdminWorkingLogListForTime(startMs:string, endMs:string) {
    let s = null;
    let e = null;
    if (startMs && endMs) {
        s = moment(startMs).format("YYYY-MM-DD") + ' 00:00:00';
        e = moment(endMs).format("YYYY-MM-DD") + ' 23:59:59';
    }
    
    let workingLog = await workinglogData.findAllWorkingLog(s, e);

    const DepartmentMap = await findDepartmentMap();

    let result = [
        ["日期年","日期月","日期日","部门","姓名","项目名称","项目编号","时长/小时","工作内容"]
    ];

    workingLog.forEach(info => {
        let year = moment(info.dateKey).year();
        let month = moment(info.dateKey).month()+1;
        let day = moment(info.dateKey).date();
        let departmentName = DepartmentMap[info.departmentId];
        let subList = [
            year,
            month,
            day,
            departmentName,
            info.name,
            info.projectName,
            info.projectId,
            info.time,
            info.workLog
        ]
        result.push(subList);
    });


    return {dataList:result, name:`【按时间分工时】.xlsx`};
}


/**
 * 导出按项目分的工时管理列表
 * @param startMs 
 * @param endMs 
 * @returns 
 */
export async function outPutAdminWorkingLogListForProject(startMs:string, endMs:string) {
    let s = null;
    let e = null;
    if (startMs && endMs) {
        s = moment(startMs).format("YYYY-MM-DD") + ' 00:00:00';
        e = moment(endMs).format("YYYY-MM-DD") + ' 23:59:59';
    }
    let workingLog = await workinglogData.findAllWorkingLogToProject(s, e);

    let distinctMap = {};// => {name:{id:"", count:0}}

    workingLog.forEach(info => {
        if (!distinctMap[info.projectName]) distinctMap[info.projectName] = {id:info.projectId, count:0 }
        distinctMap[info.projectName].count += info.time;
    });

    let result = [
        ["项目名称","项目编号","时长/小时","时长/人天"]
    ];
    for (let name in distinctMap) {
        let {id, count} = distinctMap[name];
        let dayCount = Math.ceil(count/8 * 100)/100;
        
        result.push([name, id, count, dayCount]);
    }
    
    return {dataList:result, name:`【按项目分工时】.xlsx`};
}