<!--上传暂降数据-->
<template>
    <el-dialog
        draggable
        class="cn-operate-dialog"
        v-model="eventDataUploadVisible"
        :title="title"
        style="width: 415px;"
        top="25vh"
    >
        <el-scrollbar>
            <el-form :inline="false" :model="form" label-width="120px" ref="formRef">
                <el-form-item label="业务用户">
                    <el-select v-model="form.userId" filterable @change="changeUser">
                        <el-option
                            v-for="item in userListData"
                            :key="item.id"
                            :label="item.userName"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="生产线">
                    <el-select v-model="form.productLineId" filterable @change="changeProductLine">
                        <el-option v-for="item in productLineData" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="进线">
                    <el-input v-model="form.incomingLineName" readonly />
                </el-form-item>
                <el-form-item label="暂降数据文件">
                    <el-upload
                        v-model:file-list="fileList"
                        ref="uploadEventData"
                        action=""
                        :limit="1"
                        :on-exceed="handleExceed"
                        :auto-upload="false"
                        :on-change="choose"
                    >
                        <template #trigger>
                            <el-button type="primary">选择数据文件</el-button>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-form>
        </el-scrollbar>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="eventDataUploadVisible = false">取消</el-button>
                <el-button type="primary" @click="submit">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, inject } from 'vue'
import TableStore from '@/utils/tableStore'
import { ElMessage } from 'element-plus'
import { sgUserList } from '@/api/advance-boot/sgGroven/sgUser'
import { querySgProductLineByUserId } from '@/api/advance-boot/sgGroven/sgProductLine'
import type { UploadInstance, UploadProps, UploadRawFile, UploadUserFile } from 'element-plus'
import { genFileId } from 'element-plus'
import { importEventData } from '@/api/advance-boot/sgGroven/sgEvent'

const fileList = ref<UploadUserFile[]>([])

const formRef = ref()
const tableStore = inject('tableStore') as TableStore
const eventDataUploadVisible = ref(false)
const title = ref('')
const userListData: any = ref([])
const productLineData: any = ref([])
const uploadEventData = ref<UploadInstance>()

// 注意不要和表单ref的命名冲突
const form = reactive({
    userId: '',
    productLineId: '',
    incomingLineName: '',
    incomingLineId: '',
    file: null
})

//弹出界面，默认选择用户的第一个生产线的第一条进线进行数据导入
const open = async (text: string, userId: string) => {
    title.value = text
    resetForm()
    form.file = null
    fileList.value = []
    // 在此处恢复默认表单
    for (let key in form) {
        form[key] = ''
    }
    //获取用户数据
    await sgUserList().then(res => {
        if (res.data && res.data.length > 0) {
            userListData.value = res.data
        } else {
            ElMessage.error('请先创建用户')
        }
    })
    if (userId) {
        form.userId = userId
    } else {
        form.userId = userListData.value[0].id
    }
    //根据用户id获取所有生产线，并默认选中第一个
    await querySgProductLineByUserId(form.userId).then(res => {
        if (res.data && res.data.length > 0) {
            productLineData.value = res.data
            //并且默认选中第一个生产线
            const productLineObj = productLineData.value[0]
            form.productLineId = productLineObj.id
            //判断赋值进线信息
            if (productLineObj.incomingLineId && productLineObj.incomingLineName) {
                form.incomingLineId = productLineObj.incomingLineId
                form.incomingLineName = productLineObj.incomingLineName
            } else {
                ElMessage.error('请先关联进线')
            }
        } else {
            form.productLineId = ''
            form.incomingLineId = ''
            form.incomingLineName = ''
            productLineData.value = []
            ElMessage.error('请先创建生产线')
        }
    })
    eventDataUploadVisible.value = true
}

//重置表单内容
const resetForm = () => {
    if (formRef.value) {
        formRef.value.resetFields()
    }
}

/**
 * 用户下拉框发生更新
 */
const changeUser = async () => {
    await querySgProductLineByUserId(form.userId).then(res => {
        if (res.data && res.data.length > 0) {
            productLineData.value = res.data
            //并且默认选中第一个生产线
            const productLineObj = productLineData.value[0]
            form.productLineId = productLineObj.id
            //判断赋值进线信息
            if (productLineObj.incomingLineId && productLineObj.incomingLineName) {
                form.incomingLineId = productLineObj.incomingLineId
                form.incomingLineName = productLineObj.incomingLineName
            } else {
                form.incomingLineId = ''
                form.incomingLineName = ''
                ElMessage.error('请先关联进线')
            }
        } else {
            form.productLineId = ''
            form.incomingLineId = ''
            form.incomingLineName = ''
            productLineData.value = []
            ElMessage.error('请先创建生产线')
        }
    })
}

/**
 * 生产线下拉框发生更新
 */
const changeProductLine = () => {
    //根据产线id获取到产线实体
    const tempProductData = productLineData.value.filter((obj: any) => obj.id === form.productLineId)
    //判断赋值进线信息
    if (tempProductData[0].incomingLineId && tempProductData[0].incomingLineName) {
        form.incomingLineId = tempProductData[0].incomingLineId
        form.incomingLineName = tempProductData[0].incomingLineName
    } else {
        ElMessage.error('请先关联进线')
    }
}

/**
 * 选择待上传文件
 */
const choose = (e: any, fileList: UploadUserFile[]) => {
    const file = e.raw
    if (file.type === 'text/csv' || file.name.endsWith('.csv')) {
        form.file = file
    } else {
        ElMessage.error('请选择CSV文件')
        fileList.pop() // 移除无效文件
        form.file = null
    }
}

const handleExceed: UploadProps['onExceed'] = files => {
    uploadEventData.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    uploadEventData.value!.handleStart(file)
    fileList.value = [{ name: file.name, url: '' }]
}

/**
 * 提交用户表单数据
 */
const submit = async () => {
    if (form.file) {
        formRef.value.validate(async (valid: any) => {
            if (valid) {
                if (!form.incomingLineId) {
                    ElMessage.error('请先关联进线')
                } else {
                    let data = new FormData()
                    data.append('file', form.file)
                    data.append('incomingLineId', form.incomingLineId)
                    data.append('productLineId', form.productLineId)
                    await importEventData(data).then((res: any) => {
                        if (res.code == 'A0000') {
                            ElMessage.success('导入成功')
                            tableStore.index()
                            eventDataUploadVisible.value = false
                        } else {
                            ElMessage.error('导入失败，请检查表格文件')
                        }
                    })
                }
            }
        })
    } else {
        ElMessage.error('请选择数据文件')
    }
}

defineExpose({ open })
</script>

<style scoped>
.el-form-item__content div {
    width: 100% !important;
}
</style>
