<template>
    <el-dialog
        v-model="importDialog"
        destroy-on-close
        center
        width="880"
        class="list-dialog"
        title="批量导入"
    >
        <el-steps :active="activeSteps" finish-status="success">
            <el-step title="上传文件" />
            <el-step title="数据预览" />
            <el-step title="导入数据" />
        </el-steps>
        <div class="step-1" v-if="activeSteps == 0">
            <template v-if="!uploadFail">
                <div class="file-div">
                    <p class="bold">填写导入数据信息</p>
                    <div class="file">
                        <p class="tips">请按照数据模版的格式准备导入数据，模版中的表头名称不可更改，表头行不能删除</p>
                        <el-button plain type="primary" @click="download">下载模板</el-button>
                    </div>
                </div>
                <div class="file-div">
                    <p class="bold">上传填好的信息表</p>
                    <div class="file">
                        <p class="tips">文件后缀名必须为xls或xlsx（即excel格式），文件大小不得大于10m，最多支持导入3000条数据</p>
                        <el-upload
                            ref="uploadRef"
                            :action="action"
                            :data="{ templateCode: importCode, importType, resourceType }"
                            :headers="{ token }"
                            :auto-upload="false"
                            :on-success="uploadSuccess"
                            :on-error="uploadError"
                            v-model:file-list="fileList"
                        >
                            <el-button plain type="primary">上传文件</el-button>
                        </el-upload>
                    </div>
                </div>
                <div class="prompt flex">
                    <i-ep-warning style="margin-top: 1px" />
                    <div style="margin-left: 8px">
                        <p class="bold">特别提示</p>
                        <p style="color: #898989">导入过程中如发现同组织层级部门，且对该数据有更新权限，则更新部门数据</p>
                    </div>
                </div>
            </template>
            <template v-else>
                <div class="fail-header flex">
                    <div class="left"></div>
                    <div class="right flex-center">
                        <div class="flex-center right-content">
                            <div>
                                <p style="margin-bottom: 5px;">正常数量条数: {{ failMsg.successNum }}条</p>
                                <p>异常数量条数: {{ failMsg.errorNum }}条</p>
                            </div>
                            <el-button type="primary" @click="downloadFail">下载异常文件</el-button>
                        </div>
                    </div>
                </div>
                <div class="fail-msg">
                    <p>异常提示：</p>
                    <p v-for="item in failMsg.errorMsg">{{ item }}</p>
                </div>
            </template>
        </div>
        <div v-if="activeSteps == 1">
            <el-table
                :data="pageData"
                :height="376"
            >
                <template v-for="item in tableColumn">
                    <el-table-column
                        :label="item.label"
                        :prop="item.prop"
                    >
                    </el-table-column>
                </template>
            </el-table>
        </div>
        <div class="finish" v-if="activeSteps == 2">
            <h2 class="bold">批量导入完成</h2>
            <p>您已成功导入{{ pageData.length }}条数据</p>
        </div>
        <template #footer>
            <div class="dialog-footer" v-if="activeSteps != 2">
                <template v-if="!uploadFail">
                    <el-button @click="cancel">{{ activeSteps == 0 ? '取消' : '上一步' }}</el-button>
                    <el-button type="primary" @click="handleImport" :loading="loading">下一步</el-button>
                </template>
                <template v-else>
                    <el-button @click="uploadFail = false">重新上传</el-button>
                </template>
            </div>
            <div class="dialog-footer" v-else>
                <el-button type="primary" @click="importDialog = false">完成</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
    import { downloadTemplate, listImport, downloadFailTemplate } from '@/api/public'
    import downloadPlugins from '@/plugins/download'
    import { getToken } from '@/utils/auth';
    import { AxiosResponse } from 'axios';

    const emits = defineEmits(['refresh'])

    const activeSteps = ref(0)
    const loading = ref(false)

    const token = getToken()
    const importDialog = ref(false)
    const importCode = ref('')
    const importType = ref('')
    const resourceType = ref<number | null>(null)
    const open = (code: string, type?: string) => {
        importType.value = type || null
        importCode.value = code
        if(importCode.value == 'IMPORT_CUSTOM_EXCEL') {
            resourceType.value = 10
        }
        if(importCode.value == 'IMPORT_CLUE_EXCEL') {
            resourceType.value = 11
        }
        activeSteps.value = 0
        uploadFail.value = false
        fileList.value = []
        importDialog.value = true
    }

    const download = () => {
        downloadTemplate(importCode.value, importType.value).then(res => {
            downloadPlugins.download('download', res)
        })
    }

    const action = import.meta.env.VITE_APP_BASE_API + '/excel/import_excel'

    const uploadRef = ref()
    const fileList = ref([])
    const handleImport = () => {
        loading.value = true
        if(activeSteps.value == 0) {
            if(fileList.value.length == 0) {
                ElMessage.error('请上传文件')
                loading.value = false
                return false
            }
            uploadRef.value!.submit()
        }else {
            listImport(tempCode.value, importType.value, resourceType.value).then(res => {
                if(res.success) {
                    activeSteps.value = 2
                    emits('refresh')
                }
            }).finally(() => {
                loading.value = false
            })
        }
    }

    const pageData = ref<any[]>([])
    const tableColumn = ref<{ label: string; prop: string }[]>([])
    const tempCode = ref('')
    const uploadFail = ref(false)
    const failMsg = ref()
    const uploadSuccess = (res: AxiosResponse) => {
        loading.value = false
        pageData.value = []
        if(res.success) {
            let result = res.result
            tempCode.value = result.tempCode
            if(result.isSuccess) {
                activeSteps.value = 1
                result.datas.map((item: { rowData: { columnDes: string; columnName: string; columnData: string }[] }, index: number) => {
                    let dataObj: any = {}
                    item.rowData.map(detail => {
                        if(index == 0) {
                            let columnObj = { label: detail.columnDes, prop: detail.columnName }
                            tableColumn.value.push(columnObj)
                        }
                        dataObj[detail.columnName] = detail.columnData
                    })
                    pageData.value.push(dataObj)
                })
            }else {
                uploadFail.value = true
                failMsg.value = result
            }
        }else{
            ElMessage.error('导入失败，请稍后再试')
        }
        fileList.value = []
    }

    const uploadError = () => {
        loading.value = false
        ElMessage.error('上传失败，请稍后再试')
    }

    const downloadFail = () => {
        downloadFailTemplate(tempCode.value, importType.value).then(res => {
            downloadPlugins.download('download', res)
        })
    }

    const cancel = () => {
        if(activeSteps.value == 0) {
            importDialog.value = false
        }else{
            activeSteps.value = 0
        }
    }

    defineExpose({
        open
    })
</script>

<style scoped lang="scss">
    .el-steps{
        margin-bottom: 24px;
        :deep(.el-step__head){
            left: 16px;
        }
        :deep(.el-step__main){
            .el-step__title{
                font-size: 14px;
            }
        }
    }
    .file-div{
        margin-bottom: 16px;
        .file{
            border-radius: 2px;
            border: 1px solid #D9D9D9;
            padding: 15px 10px;
            margin-top: 8px;
            p{
                color: #898989;
                margin-bottom: 10px
            }
            .tips{
                font-size: 12px;
            }
        }
    }
    .prompt{
        padding: 11px;
        background: #F3F4F6;
        border-radius: 2px;
    }
    .el-table{
        border: var(--el-table-border);
        border-bottom: 0;
        margin-top: 15px;
        :deep(.el-table__header){
            th{
                background-color: #F8FAFC;
                color: #262626;
            }
        }
    }
    .finish{
        height: 433px;
        text-align: center;
        padding-top: 100px;
    }
    .fail-header{
        height: 80px;
        border: 1px solid #D9D9D9;
        .left{
            width: 80px;
            border-right: 1px solid #D9D9D9;
        }
        .right{
            padding: 0 24px;
            flex: 1;
            .right-content{
                justify-content: space-between;
                width: 100%;
            }
        }
    }
    .fail-msg{
        margin-top: 15px;
        padding: 15px;
        border: 1px solid #D9D9D9;
        height: 290px;
        overflow: auto;
        p{
            line-height: 2;
        }
    }
</style>
