import { IService, Context, logger, OpResult } from "mslib"
import { UserInfo } from "user/UserInfo"
import { ModelUtil, TableUtil } from 'model-util'
import { v4 } from 'uuid'

/**
 * DAO 工具类
 * @date 2021-05-27 09:47:22
 * @author 吴锋霖
 */
class DaoUtils {

    static initId(items: []) {
        for (let i = 0; i < items.length; i++) {
            let item: { id: string } = items[i];
            if (DaoUtils.isEmpty(item.id)) {
                item.id = this.uuid();
            }
        }
    }

    /**
     * 初始化系统字段
     */
    static initSystemField(items: any[], isAddNew: boolean) {
        console.log(`initSystemField before -> ${JSON.stringify(items)}`)
        let currUser: UserInfo = Context.getCurrentUser() || {}
        currUser.userId = currUser.userId || ''
        for (let i = 0; i < items.length; i++) {
            let item: { id: string, createTime: any, updateTime: any, bizStatus: number } = items[i];
            if (DaoUtils.isEmpty(item.id)) {
                item.id = this.uuid();
            }
            if (isAddNew && DaoUtils.isEmpty(item.createTime)) {
                item.createTime = new Date();
            }
            item.updateTime = new Date();
        }
        console.log(`initSystemField after -> ${JSON.stringify(items)}`)
    }

    static isEmpty(value: any): boolean {
        if (value === 0) {
            return false;
        }
        return (!value || value == null || value == undefined || value == '')
    }

    static getIdArr(items: any[]): string[] {
        let result: string[] = [];
        for (let i = 0; i < items.length; i++) {
            let id: string = items[i]["id"];
            result.push(id)
        }
        return result
    }

    /**
     * 检查指定字段值是否重复
     */
    static async repeatCheck(mu: TableUtil<any, any>, field: string, fieldValue: string, message: string, currId?: string): Promise<OpResult<any>> {
        let sql = `select count(1) as value from ${mu.tableName} where deleted = '0' and ${field} = '${fieldValue}'`
        if(currId){
            sql = `${sql} and id <> '${currId}'`
        }
        let rows = await mu.queryRaw(sql)
        console.log(`执行sql -> ${sql} \n执行结果 -> ${JSON.stringify(rows)}`)
        if (rows && rows.length > 0 && Number(rows[0].value) > 0) {
            return OpResult.error(`${message}->${fieldValue}`)
        }
        return OpResult.success("ok");
    }

    /**
     * 空值判断
     */
    static emptyCheck(obj: any, fields: string[], fieldLabels: string[]): OpResult<any> {
        if (!obj) {
            return OpResult.success("")
        }
        for (let i = 0; i < fields.length; i++) {
            if (DaoUtils.isEmpty(obj[fields[i]])) {
                return OpResult.error(`${fieldLabels[i]}值为空!`)
            }
        }
        return OpResult.success("")
    }

    static uuid() {
        const id = v4();
        return id.replace(/-/g, '')
    }

}

export { DaoUtils }

