import pinia from '../store/init'
import { useAppStore } from '../store/index'
import { getArrValue, isNullES } from 'js-fast-way'
const store = useAppStore(pinia)

export const exec_sql = async (sql, path) => {
    path = getDataPath(path) //获取数据存储路径
    if (!isNullES(path)) {
        const { code, data } = await window.electron.ipcRenderer.invoke('dbSql', {
            path,
            sql,
            type: 'exec',
        })
        if (code !== 200 || data.length <= 0) {
            return { code, data }
        }
        return { code, data }
    } else {
        return { code: 400, data: '' }
    }
}

const getDataPath = (path) => {
    if (isNullES(path)) {
        const pid = store.projectInfo?.key ?? '', dataPath = store.dataPath ?? ''
        if (isNullES(pid) || isNullES(dataPath)) {
            path = ''
        } else {
            //数据库文件本地存储路径
            path = `${dataPath}/${pid}/data`
        }
    }
    return path
}

export const sql_table = async (sql, path) => {
    const { code, data } = await exec_sql(sql, path)
    if (code !== 200 || data.length <= 0) {
        return { code, data }
    }
    //返回处理后的数据
    const columns = getArrValue(data[0].columns)
    const values = getArrValue(data[0].values)
    let newRowData = []
    for (let i = 0; i < values.length; i++) {
        let obj = {}
        if (values[i].length >= 0) {
            for (let j = 0; j < values[i].length; j++) {
                let val = values[i][j]
                //处理布尔类型
                if (val === 'true' || val === 'false') {
                    val = val === 'true'
                }
                //组装数据
                obj[columns[j]] = val
            }
        } else {
            newRowData = []
        }
        newRowData.push(obj)
    }
    return { code, data: newRowData }
}

//单个记录查询
export const sql_find = async (sql, path) => {
    const { code, data } = await sql_table(sql, path)
    if (code !== 200 || data.length <= 0) {
        return { code, data: {} }
    }
    return { code, data: data[0] }
}

//查询统计
export const sql_count = async (sql, path) => {
    const { code, data } = await exec_sql(sql, path)
    if (code !== 200 || data.length <= 0) {
        return { code, data }
    }
    try {
        return { code, data: data[0].values[0][0] }
    } catch (e) {
        return { code: 200, data: 0 }
    }
}

