import config from '~src/config/index'
import router from '~src/router/index'
import { hcAlert } from 'hc-vue3-ui'

//跳转页面
export const toPage = ({ page, query }) => {
    router.push({
        path: '/jump',
        query: {
            page: page ?? '/home',
            query: query ? JSON.stringify(query) : '',
        },
    })
}

//操作确认
export const actionConfirm = (cbk) => {
    hcAlert({
        title:'操作确认',
        content: '请确认要执行此操作吗?',
        cbk: (res) => {
            if (cbk && res) cbk(res)
        },
    })
}

//删除提醒
export const delMessage = (cbk) => {
    hcAlert({
        title:'删除提醒',
        content: '请谨慎考虑后，确认是否需要删除？',
        confirm: '确认删除',
        cbk: (res) => {
            if (cbk && res) cbk(res)
        },
    })
}

//显示打开文件对话框
export const openExternal = (url) => {
    window.electron.ipcRenderer.invoke('openExternal', { url })
}

//显示打开文件对话框
export const showOpenDialog = async (options) => {
    return await window.electron.ipcRenderer.invoke('showOpenDialog', options)
}

//判断文件或目录是否存在
export const exists_file = (file) => {
    if (file) {
        return window.api.fs.existsSync(file)
    } else {
        return false
    }
}

//读取本地文件
export const read_file = (file) => {
    if (!exists_file(file)) {
        return ''
    } else {
        try {
            return window.api.fs.readFileSync(file, 'utf-8')
        } catch (e) {
            return ''
        }
    }
}

//写入本地文件
export const write_file = (file, value) => {
    try {
        window.api.fs.writeFileSync(file, value, 'utf-8')
        return true
    } catch (e) {
        return false
    }
}

//读取配置文件
export const read_config_file = () => {
    const configFile = read_file(config.configPath)
    if (configFile) {
        let content = {}
        try {
            content = JSON.parse(configFile)
        } catch (e) {
            content = {}
        }
        return content
    } else {
        return {}
    }
}

//写入配置文件
export const write_config_file = (data) => {
    data = data || {}
    //先创建一个目录
    if (!exists_file(config.homePath)) {
        window.api.fs.mkdirSync(config.homePath, { recursive: true })
    }
    //写入配置文件
    return write_file(config.configPath, JSON.stringify(data))
}
