<template>
    <hc-new-dialog ui="hc-order-batch-import-file-box" widths="1000px" :show="isShow" title="材料计量单导入" @close="modalClose">
        <div class="hc-upload-box">
            <el-upload
                ref="uploadRef" :headers="getHeader()" drag accept=".xls,.xlsx,.doc,.docx,.pdf,.jpg,.png,.jpeg"
                action="/api/blade-resource/oss/endpoint/upload-file" multiple
                :on-success="handleSuccess" :on-error="handleError"
            >
                <div class="text-80px text-gray">
                    <i class="ri-upload-cloud-line" />
                </div>
                <div class="mt-24px text-black">将文件拖动到此处，或点击上传</div>
                <div class="mt-8px text-12px">支持的文件格式：Excel(xls、xlsx)、word(doc、docx)、pdf、图片(jpg、png、jpeg)</div>
            </el-upload>
        </div>
        <hc-card-item class="hc-upload-card-item">
            <template #header>
                <span class="mr-10px">选择材料</span>
                <span class="text-12px" style="color: #FF7D43">温馨提示：可多选材料进行批量上传附件</span>
            </template>
            <hc-table
                ref="tableRef" :column="tableColumn" :datas="tableData" :is-current-row="false"
                is-check :check-style="{ width: 29 }" :index-style="{ width: 60 }"
                @selection-change="tableCheckChange"
            />
        </hc-card-item>
        <template #footer>
            <el-button @click="modalClose">取消</el-button>
            <el-button type="primary" :loading="confirmLoading" @click="confirmTap">确认并继续</el-button>
            <el-button type="primary" :loading="confirmLoading" @click="confirmClick">确认并退出</el-button>
        </template>
    </hc-new-dialog>
</template>

<script setup>
import { nextTick, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import { getHeader } from 'hc-vue3-ui'
import { arrToId, getArrValue, getObjValue, isNullES } from 'js-fast-way'
import mainApi from '~api/debit-pay/material/order'

const props = defineProps({
    ids: {
        type: [String, Number],
        default: '',
    },
})

//事件
const emit = defineEmits(['finish', 'close'])
const store = useAppStore()

//监听数据
const contractId = ref(store.getContractId)
const projectId = ref(store.getProjectId)
watch(() => [store.getContractId, store.getProjectId], ([cid, pid]) => {
    contractId.value = cid
    projectId.value = pid
}, { immediate: true, deep: true })

//监听
const ids = ref(props.ids)
watch(() => props.ids, (id) => {
    ids.value = id
}, { immediate: true, deep: true })

//双向绑定
// eslint-disable-next-line no-undef
const isShow = defineModel('modelValue', {
    default: false,
})

//监听是否显示
watch(() =>isShow.value, (val) => {
    if (val) getTableData()
}, { deep: true })

//上传文件
const uploadRef = ref(null)

//上传成功
const formDataFiles = ref([])
const handleSuccess = (res) => {
    confirmLoading.value = false
    if (res.code === 200) {
        const data = getObjValue(res.data)
        formDataFiles.value.push(data)
    } else {
        window.$message.error(res.msg || '上传失败')
    }
}

//上传失败
const handleError = (error) => {
    confirmLoading.value = false
    const { msg } = !isNullES(error.message) ? JSON.parse(error.message) : {}
    if (isNullES(msg)) {
        window.$message.error('上传失败')
    } else {
        window.$message.error(msg)
    }
}

//选择材料
const tableRef = ref(null)
const tableColumn = [
    { key: 'contractMaterialName', name: '合同材料' },
    { key: 'materialArriveNumber', name: '材料到场编号' },
    { key: 'businessDate', name: '业务日期' },
    { key: 'meterMoney', name: '计量金额' },
]
const tableData = ref([])

//获取表格数据
const tableLoading = ref(true)
const getTableData = async () => {
    tableLoading.value = true
    const { data } = await mainApi.getPage({
        projectId: projectId.value,
        contractId: contractId.value,
        meterPeriodId: ids.value,
        current: 1,
        size: 99999,
        total: 0,
    })
    tableData.value = getArrValue(data?.records)
    tableLoading.value = false
}

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

//验证并组装数据
const validateData = async () => {
    const table = tableKeys.value
    if (table.length <= 0) {
        window.$message.warning('请先勾选材料')
        return false
    }
    const files = formDataFiles.value
    if (files.length <= 0) {
        window.$message.warning('请先上传文件')
        return false
    }
    const ids = arrToId(table)
    const { isRes } = await mainApi.batchImportFile({
        files: files,
        materialMeterFormIds: ids,
        projectId: projectId.value,
        contractId: contractId.value,
    })
    return isRes
}

//确认并继续
const confirmLoading = ref(false)
const confirmTap = async () => {
    confirmLoading.value = true
    const isRes = await validateData()
    confirmLoading.value = false
    if (!isRes) return
    window.$message.success('批量导入成功')
    clearData()
}

//确认并退出
const confirmClick = async () => {
    confirmLoading.value = true
    const isRes = await validateData()
    confirmLoading.value = false
    if (!isRes) return
    window.$message.success('批量导入成功')
    modalClose()
    emit('finish')
}

//清空数据
const clearData = async () => {
    uploadRef.value?.clearFiles()
    tableRef.value?.clearSelection()
    await nextTick()
    tableKeys.value = []
    formDataFiles.value = []
}

//关闭弹窗
const modalClose = () => {
    isShow.value = false
    clearData()
    emit('close')
}
</script>

<style scoped lang="scss">
.hc-upload-box :deep(.el-upload) {
    --el-upload-dragger-padding-horizontal: 20px;
}
.hc-upload-text-tip {
    color: #FF7D43;
}
</style>

<style lang="scss">
.el-overlay-dialog .el-dialog.hc-new-dialog.hc-order-batch-import-file-box .el-dialog__body {
    padding: 14px 4px;
}
.hc-card-item-box.hc-upload-card-item {
    padding: 10px;
    margin-top: 24px;
    .hc-card-item-header {
        color: unset;
    }
}
</style>
