<template>
    <div v-loading="isLoading" class="relative h-full w-full p-5" :element-loading-text="loadingText">
        <hc-new-card title="项目管理" :scrollbar="projectData.length > 0">
            <template #extra>
                <el-button hc-btn type="primary" @click="importProject">导入项目</el-button>
                <el-button v-if="pageSource" hc-btn @click="toBackPage">返回</el-button>
            </template>
            <hc-no-data v-if="projectData.length <= 0" tip="暂无项目数据，请先导入项目数据" />
            <template v-for="item in projectData" v-else :key="item.key">
                <div class="hc-project-item hc-flex">
                    <div class="name" @click="itemClick(item)">{{ item.name }}</div>
                    <div class="extra hc-flex">
                        <el-link v-if="item.key === projectInfo.key" disabled>已为默认</el-link>
                        <el-link v-else type="primary">设为默认</el-link>
                        <el-link type="danger" @click="delClick(item)">删除</el-link>
                    </div>
                </div>
            </template>
        </hc-new-card>
        <div class="open-dev-tools" @dblclick="openDevTools" />
    </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { useAppStore } from '../store'
import { useRoute } from 'vue-router'
import { getProjectInfo } from '../store/app'
import { getArrValue, getObjValue, isArrIndex, isNullES } from 'js-fast-way'
import { delMessage, exists_file, showOpenDialog, toPage, write_file } from '../utils/tools'

//初始组合式
const useRoutes = useRoute()
const store = useAppStore()

defineOptions({
    name: 'HcProject',
})

//加载中
const isLoading = ref(false)
const loadingText = ref('加载中...')

//项目信息
const projectInfo = ref(store.projectInfo)
const dataPath = ref(store.dataPath)

//监听
watch(() => store.projectInfo, (val) => {
    projectInfo.value = val
})

//渲染完成
const pageSource = ref('')
const isImportPath = ref('')
onMounted(async () => {
    await getProjectData()
    //判断是否有导入项目
    const { path, source } = getObjValue(useRoutes.query)
    console.log('导入项目：', path)
    if (!isNullES(path) && isImportPath.value !== path) {
        setImportProject(path)
        isImportPath.value = path
    }
    pageSource.value = source
})

//获取项目信息
const projectData = ref([])
const getProjectData = async () => {
    projectData.value = []
    loadingText.value = '获取项目信息中...'
    isLoading.value = true
    const { data } = await getProjectInfo()
    projectData.value = getArrValue(data)
    isLoading.value = false
}

//导入项目
const importProject = async () => {
    const { code, paths } = await showOpenDialog({
        title: '导入项目数据',
        buttonLabel: '确认选择',
        multiSelections: false,
        properties: ['openFile'],
        message: '请选择下载的脱机文件',
        filters: [
            { name: '档案数据文件', extensions: ['hczc'] },
        ],
    })
    if (code !== 200) return
    setImportProject(paths[0])
}

const setImportProject = (paths) => {
    loadingText.value = '导入数据文件中...'
    isLoading.value = true
    //创建一个临时目录
    window.api.fs.mkdirSync(dataPath.value + '/temp', { recursive: true })
    //解压数据文件
    window.api.compressing.zip.uncompress(paths, dataPath.value + '/temp').then(() => {
        setFileData()
    }).catch(err => {
        console.error(err)
        isLoading.value = false
        window.$message.error('导入数据文件失败，请重新下载导入')
    })
}

//设置文件数据
const setFileData = async () => {
    //读取当前数据文件的配置文件
    const content1 = window.api.fs.readFileSync(dataPath.value + '/temp/config.json', 'utf-8')
    const { key, name } = JSON.parse(content1)
    //读取项目配置文件
    const content2 = window.api.fs.readFileSync(dataPath.value + '/project.json', 'utf-8')
    const project = JSON.parse(content2)
    //判断当前项目文件是否存在
    if (exists_file(dataPath.value + '/' + key)) {
        window.api.fsExtra.remove(dataPath.value + '/' + key).then(() => {
            isLoading.value = false
            setFileData2(project, key, name)
        }).catch(err => {
            console.error(err)
            isLoading.value = false
            window.$message.error('导入失败')
        })
    } else {
        setFileData2(project, key, name).then()
    }
}

const setFileData2 = async (project, key, name) => {
    //移动文件(重命名)
    window.api.fs.renameSync(dataPath.value + '/temp', `${dataPath.value}/${key}`)
    //判断当前项目是否已经存在
    if (!isArrIndex(project.data, 'key', key)) {
        project.data.push({ key, name })
    }
    //判断默认项目是否存在
    if (isNullES(project.value)) {
        project.current = { key, name }
    }
    //写入项目配置文件
    write_file(dataPath.value + '/project.json', JSON.stringify(project))
    isLoading.value = false
    window.$message.success('导入数据文件成功')
    //重新获取项目信息
    await getProjectData()
}

//切换项目
const itemClick = (item) => {
    loadingText.value = '切换项目中...'
    isLoading.value = true
    store.setProjectInfo(item)
    setTimeout(() => {
        window.$message.success('项目切换成功')
        isLoading.value = false
        toPage({
            page: 'home',
        })
    }, 500)
}

//删除项目
const delClick = async (item) => {
    delMessage(() => {
        loadingText.value = '删除项目中...'
        isLoading.value = true
        window.api.fsExtra.remove(dataPath.value + '/' + item.key).then(() => {
            isLoading.value = false
            window.$message.success('删除成功')
            getProjectData()
        }).catch(err => {
            console.error(err)
            isLoading.value = false
            window.$message.error('删除失败')
        })
    })
}

//返回
const toBackPage = () => {
    const source = pageSource.value
    if (!isNullES(source)) {
        toPage({
            page: source,
        })
    }
}

//打开开发者工具
const openDevTools = () => {
    window.electron.ipcRenderer.invoke('openDevTools')
}
</script>

<style scoped lang="scss">
.hc-project-item {
    height: 38px;
    border-bottom: 1px solid #ebeef5;
    transition: background-color .1s;
    .name {
        position: relative;
        padding-right: 14px;
        cursor: pointer;
        flex: 1;
    }
    .extra {
        position: relative;
        height: 100%;
        a  + a{
            margin-left: 10px;
        }
    }
    &:hover {
        background-color: #f5f7fa;
    }
}
</style>
