<template>
    <hc-card class="hc-project-collect-gist-list">
        <template #header>
            <hc-date-year v-model="searchForm.startYear" v-model:end="searchForm.endYear" />
            <div class="relative ml-3 w-[300px]">
                <hc-search-input v-model="searchForm.targetPlan" text="搜索" color="#151921" @search="searchClick" />
            </div>
        </template>
        <template #extra>
            <div class="w-[120px]">
                <el-select v-model="searchForm.workFocusStage" filterable clearable block placeholder="项目阶段" @change="searchClick">
                    <el-option v-for="item in projectStage" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </div>
            <el-button v-del-com:[delTableItem] type="danger" class="ml-2" :disabled="tableCheckKeys.length <= 0">批量删除</el-button>
            <el-button type="warning" class="ml-2" @click="importClick">导入</el-button>
            <el-button v-yes-com:[deriveTableItem] type="primary" class="ml-2" :disabled="tableCheckKeys.length <= 0">批量导出</el-button>
        </template>
        <HcTableList :datas="tableData" :loading="tableLoading" is-admin @tap="rowNameClick" @check="tableCheck" @change="searchClick" />
        <template #action>
            <hc-pages :pages="searchForm" @change="pageChange" />
        </template>

        <!-- 导入 -->
        <hc-dialog v-model="isImportShow" widths="24rem" title="项目数据导入" :footer="false" @close="modalImportClose">
            <hc-form-upload
                v-model="importFile" class="hc-form-drop-upload"
                :options="{ num: 1, type: 'list', drop: true }"
                :upload="{ options: uploadOptions }" @success="uploadSuccess"
            />
            <div class="hc-flex mt-5">
                <span class="mr-2">模板下载:</span>
                <el-button color="#20C98B" size="small" class="text-white" :loading="downloadTemplateLoading" @click="downloadTemplate">点击下载</el-button>
            </div>
        </hc-dialog>
    </hc-card>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useClick } from 'hc-vue3-ui'
import HcTableList from '../modules/gist-list.vue'
import { getDictionaryData } from '~src/utils/tools'
import { arrToId, getArrValue, newDownBlob } from 'js-fast-way'
import mainApi from '~api/project/gist'

//事件
const emit = defineEmits(['edit'])

onMounted(() => {
    getDataApi()
})

//获取接口数据
const getDataApi = async () => {
    projectStage.value = await getDictionaryData('workFocusStage', true)
    searchClick()
}

//项目阶段
const projectStage = ref([])

//搜索条件
const searchForm = ref({
    targetPlan: '', workFocusStage: null,
    current: 1, size: 20, total: 0,
})
const searchClick = () => {
    searchForm.value.current = 1
    getTableData()
}

//分页
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}

//表格数据
const tableData = ref([])
const tableLoading = ref(false)
const getTableData = async () => {
    tableData.value = []
    tableLoading.value = true
    const { error, code, data } = await mainApi.page(searchForm.value)
    //处理数据
    tableLoading.value = false
    if (!error && code === 200) {
        tableData.value = getArrValue(data['records'])
        searchForm.value.total = data.total || 0
    } else {
        tableData.value = []
        searchForm.value.total = 0
    }
}

//表格被选择
const tableCheckKeys = ref([])
const tableCheck = (row) => {
    tableCheckKeys.value = row
}

//项目名称被点击
const rowNameClick = (row) => {
    emit('edit', row)
}

//批量删除
const delTableItem = async (_, resolve) => {
    const ids = arrToId(tableCheckKeys.value)
    const { error, code, msg } = await mainApi.del(ids)
    if (!error && code === 200) {
        window.$message.success('删除成功')
        resolve()
        searchClick()
    } else {
        window.$message.error(msg ?? '删除失败')
    }
}

//批量导出
const deriveTableItem = async (_, resolve) => {
    const ids = arrToId(tableCheckKeys.value)
    const { error, val } = await mainApi.exportWorkfocus(ids)
    if (error) {
        window.$message?.error('数据异常')
        resolve()
        return
    }
    await newDownBlob(val)
    resolve()
}

//项目数据导入
const isImportShow = ref(false)
const importFile = ref('')
const uploadOptions = {
    url: '/api/blade-attach/workfocus/import-workfocus',
    size: 120,
    accept: '.xls,.xlsx',
    accept_tip: '请选择Excel文件',
}
const importClick = () => {
    isImportShow.value = true
}

//下载模板
const downloadTemplateLoading = ref(false)
const downloadTemplate = async () => {
    await useClick() //这里要使用 await 来等待
    downloadTemplateLoading.value = true
    const { error, val } = await mainApi.exportTemplate()
    downloadTemplateLoading.value = false
    if (error) {
        window.$message?.error('数据异常')
        return
    }
    await newDownBlob(val)
}

//关闭项目数据导入弹窗
const modalImportClose = () => {
    isImportShow.value = false
}

//上传完成
const uploadSuccess = () => {
    setTimeout(() => {
        getTableData()
        modalImportClose()
    }, 1000)
}
</script>
