<template>
    <div class="nav_detail">
        <Table
            ref="resourceTable"
            :tableParams="tableParams"
            :btnRole="btnRole"
            :rightBtn="[]"
            @selectionChange="handleSelectionChange"
        >
            <template #left>
                <el-button v-hasPermi="[`${perPrefix}:detail:tab_xgfj_tj`]" type="primary" @click="addResource()">+ 添加</el-button>
                <el-button v-hasPermi="[`${perPrefix}:detail:tab_xgfj_xz`]" @click="batchDownload()">下载</el-button>
<!--                <el-button v-hasPermi="[`${perPrefix}:detail:tab_xgfj_sc`]" type="danger" @click="batchDel()">删除</el-button>-->
            </template>
        </Table>
    </div>

    <el-dialog title="上传附件" destroy-on-close v-model="visible" width="550px" append-to-body>
        <el-form ref="resourceRef" :model="form" :rules="rules" label-width="95px">
            <el-form-item label="选择附件：" class="form-item" prop="idList">
                <Upload v-model="form.idList" @uploadStatus="changeUpStatus" :resourceList="fileList" />
			</el-form-item>
            <el-form-item label="备注信息：" prop="remark">
				<el-input
                    v-model="form.remark"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入备注信息"
                    :maxlength="300"
                    resize="none"
                    show-word-limit
                />
			</el-form-item>
        </el-form>
        <template #footer>
			<div class="dialog-footer">
				<el-button :loading="buttonLoading" type="primary" @click="submitForm">提交</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</template>
    </el-dialog>
</template>

<script setup lang="ts">
import { listResource, delResource, resourceQuery, resourceVO, bindResource, batchDelResource } from '@/api/public';
import { downloadZip } from '@/api/emails';
import Table from '@/components/Table/index.vue'
import { tableTypes } from '@/components/Table/types'
import Upload from '../FileUpload/upload.vue';
import auth from '@/plugins/auth'
import downloadPlugins from '@/plugins/download'

const props = defineProps({
    resourceType: {
        type: String
    },
    resourceTypeId: {
        type: String
    },
    perPrefix:{
        type: String
    },
    customerId: {
        type: String || Number
    }
})

const btnRole = ref([
    // { type: 'remove', hasPermi: `${ props.perPrefix }:detail:tab_xgfj_sc` },
])

const tableParams = reactive<tableTypes<resourceQuery, resourceVO>>({
    tableColumn: [
        { show: true, label: '附件名称', prop: 'resourceName', sortable: true },
        { show: true, label: '附件格式', prop: 'resourceFormat', render: ({ column }: { column: resourceVO }) => {
            return column.resourceName?.split(".")[1]
        } },
        { show: true, label: '文件大小', prop: 'resourceSize' },
        { show: true, label: '上传时间', prop: 'createTime', sortable: true },
        { show: true, label: '上传人员', prop: 'createByName' },
        { show: true, label: '备注', prop: 'remark', sortable: true },
        {
            show: true, label: '操作', width: 150, prop: 'operation', render: ({ column }: { column: resourceVO }) => {
                let button = auth.hasPermi(`${props.perPrefix}:detail:tab_xgfj_xz`) ? h('a', {
                        href: column.resourceUrl,
                        download: column.resourceName,
                        target: "_blank",
                        style: { color: '#1874FF', 'vertical-align': 'middle', 'margin-right': '12px' }
                    }, '下载') : ''
                return [
                    button
                ]
            }
        },
    ],
	queryParams: {
        resourceType: ['10', '11'].includes(props.resourceType) ? undefined : props.resourceType,
        resourceTypeId: ['10', '11'].includes(props.resourceType) ? undefined : props.resourceTypeId,
        customerId: props.customerId
	},
	listFn: listResource,
    delFn: delResource,
    keyId: 'id',
    commonQueryOrderBy: 'createTime'
})

/** 多选框选中数据 */
const selectedData = ref<resourceVO[]>([])
const handleSelectionChange = (selection: resourceVO[]) => {
    selectedData.value = selection
}

const resourceTable = ref()
const batchDel = () => {
    let ids = selectedData.value.map(item => item.id)
    if(ids.length == 0) {
        ElMessage.error('请选择要删除的附件')
        return false
    }
    ElMessageBox.confirm(
        '是否确认删除当前附件？',
        '确认提示',
        { type: 'warning', confirmButtonText: '提交' }
    ).then(() => {
        batchDelResource(ids).then(res => {
            if(res.success) {
                ElMessage.success('删除成功')
                resourceTable.value.getData()
            }else{
                ElMessage.error('删除失败')
            }
        })
    }).catch(() => { })
}

const batchDownload = () => {
    if(selectedData.value.length == 0) {
        ElMessage.error('请选择要下载的附件')
        return false
    }
    for(let i = 0; i < selectedData.value.length; i++) {
        downloadFile(selectedData.value[i].resourceUrl, selectedData.value[i].resourceName)
    }
}

const downloadFile = (url: string, fileName: string) => {
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = fileName;
    a.target = '_blank'
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}

const fileStatus = ref()
const changeUpStatus = (v)=>{

    fileStatus.value = v
}

const visible = ref(false)
const fileList = ref([])
const addResource = () => {
    fileList.value = []
    visible.value = true
}
const form = ref({
    idList: [],
    remark: '',
    resourceType: props.resourceType,
    resourceTypeId: props.resourceTypeId,
    customerId: props.customerId
})
const buttonLoading = ref(false)
const rules = {
    idList: [
        { type: 'array', required: true, message: "请选择附件", trigger: "blur" }
    ]
}

const resourceRef = ref()
const submitForm = () => {
    if(fileStatus.value == 'loading') {
        ElMessage.success('附件上传中，请稍等')
        return
    }
    resourceRef.value?.validate(async (valid: boolean) => {
        if(valid) {
            buttonLoading.value = true
            bindResource(form.value).then(res => {
                if(res.success) {
                    ElMessage.success('上传成功')
                    resourceTable.value.getData()
                    visible.value = false
                    buttonLoading.value = false
                    resourceRef.value?.resetFields()
                }
            })
        }
    })
}

const cancel = () => {
    visible.value = false
}
</script>
