<template>
    <hc-new-card>
        <template #header>
            <div class="w-32">
                <el-select v-model="searchType" placeholder="选择搜索类型" filterable block>
                    <el-option label="附件域名" value="domainUrl" />
                    <el-option label="附件名称" value="name" />
                    <el-option label="附件原名" value="originalName" />
                </el-select>
            </div>
            <div class="ml-2 w-60">
                <hc-search-input v-model="searchName" placeholder="请输入关键词" @search="searchClick" />
            </div>
        </template>
        <template #extra>
            <el-button hc-btn type="primary" @click="addUploadClick">
                <hc-icon name="upload" />
                <span>上传</span>
            </el-button>
            <el-button hc-btn type="danger" @click="delClick">
                <hc-icon name="delete-bin" />
                <span>删除</span>
            </el-button>
        </template>
        <hc-table
            :column="tableColumn" :datas="tableData" :loading="tableLoading"
            :is-index="false" is-new is-check :check-style="{ width: 29 }"
            @selection-change="tableCheckChange"
        >
            <template #attachSize="{ row }">{{ getRowFilterSize(row) }}</template>
            <template #action="{ row }">
                <el-link type="primary" :href="row.link">下载</el-link>
                <el-link v-del-com:[delRowClick]="row" type="danger">删除</el-link>
            </template>
        </hc-table>
        <template #action>
            <hc-pages :pages="searchForm" @change="pageChange" />
        </template>

        <!-- 上传文件 -->
        <hc-new-dialog v-model="isUploadShow" widths="460px" :footer="false" title="上传文件" @close="uploadClose">
            <hc-form-upload type="list" :src="uploadFileSrc" @upload="uploadItemUpload" @change="uploadItemChange" />
        </hc-new-dialog>

        <!-- 上传文件组件 -->
        <hc-upload-file ref="uploadFileRef" :options="uploadFileConfig" @success="uploadFileSuccess" @error="uploadFileError" />
    </hc-new-card>
</template>

<script setup>
import { onActivated, ref } from 'vue'
import { HcDelMsg, getHeader } from 'hc-vue3-ui'
import { arrToId, filterSize, getArrValue } from 'js-fast-way'
import mainApi from '~api/resource/attach'

defineOptions({
    name: 'Attach',
})

//激活
onActivated(() => {
    searchClick()
})

//搜索表单
const searchType = ref('originalName')
const searchName = ref('')
const searchForm = ref({ current: 1, size: 30, total: 0 })

//搜索
const searchClick = () => {
    searchForm.value.current = 1
    getTableData()
}

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

//表格数据
const tableColumn = ref([
    { key: 'originalName', name: '原名', width: 240 },
    { key: 'extension', name: '拓展名', width: 80 },
    { key: 'attachSize', name: '大小', width: 100 },
    { key: 'link', name: '资源地址' },
    { key: 'updateTime', name: '上传日期', width: 160 },
    { key: 'action', name: '操作', width: 90, align: 'center' },
])

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

//获取过滤后的大小
const getRowFilterSize = ({ attachSize }) => {
    return attachSize ? filterSize(attachSize) : attachSize + 'B'
}

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

//上传文件
const uploadFileRef = ref(null)
const uploadFileSrc = ref('')
const uploadFileConfig = {
    url: '/api/blade-resource/oss/endpoint/put-file-attach',
    headers: getHeader(),
    accept: '*',
    accept_tip: '不限制',
    size: 1024,
    multiple: true,
}

//新增
const isUploadShow = ref(false)
const addUploadClick = () => {
    isUploadShow.value = true
}
const uploadItemUpload = () => {
    uploadFileRef.value?.selectFile()
}
const uploadItemChange = (src) => {
    uploadFileSrc.value = src
}

//文件上传成功
const uploadFileSuccess = () => {
    window.$message.success('上传成功')
    getTableData()
}
//文件上传失败
const uploadFileError = () => {
    window.$message.error('上传失败')
}

//关闭上传
const uploadClose = () => {
    isUploadShow.value = false
}


//删除
const delRowClick = async ({ item }, resolve)=> {
    const { code, msg } = await mainApi.del(item.id)
    if (code === 200) {
        resolve()
        window.$message.success('删除成功')
        getTableData().then()
    } else {
        resolve()
        window.$message.error(msg ?? '删除失败')
    }
}

//批量删除
const delClick = () => {
    const rows = tableCheckKeys.value
    if (rows.length <= 0) {
        window.$message.warning('请选择要删除的数据')
        return false
    }
    //确认删除菜单
    HcDelMsg({}, async (instance, resolve) => {
        instance.confirmButtonLoading = true
        instance.confirmButtonText = '删除中...'
        //发起请求
        const ids = arrToId(rows)
        const { code, msg } = await mainApi.del(ids)
        //关闭弹窗的回调
        resolve()
        instance.confirmButtonLoading = false
        //处理结果
        if (code === 200) {
            window.$message.success('删除成功')
            getTableData().then()
        } else {
            window.$message.error(msg ?? '删除失败')
        }
    })
}
</script>
