<template>
    <div class="edit-add-detail">
        <div v-loading="detailLoading" class="form-content" element-loading-text="加载中...">
            <div class="page-form">
                <div class="main-content">
                    <!-- 步骤条 -->
                    <div class="step-container">
                        <el-steps
                            :active="currentStep"
                            align-center
                            finish-status="success"
                            process-status="finish"
                        >
                            <el-step title="1 供应商退出申请"></el-step>
                            <el-step title="2 退出审核"></el-step>
                            <el-step title="3 完成"></el-step>
                        </el-steps>
                    </div>
                    <div class="content-area">
                        <el-form
                            ref="addEditFormRef"
                            :model="addEditForm"
                            :rules="addEditFormRules"
                            size="large"
                            label-position="left"
                            label-suffix="："
                        >
                            <el-collapse v-model="activeCollapse">
                                <el-collapse-item name="basic-info">
                                    <template #title>
                                        <div class="section-title">
                                            <el-icon><Document /></el-icon>
                                            <span>供应商退出申请单</span>
                                        </div>
                                    </template>
                                    <div class="section-content">
                                        <el-descriptions :column="2" border>
                                            <el-descriptions-item>
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    供应商名称
                                                </template>
                                                <el-form-item prop="gyqyName">
                                                    {{ detailForm.gyqyName || '-' }}
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item>
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    供应商地址
                                                </template>
                                                <el-form-item prop="gysdz">
                                                    {{ detailForm.gysdz || '-' }}
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item>
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    供应商联系人
                                                </template>
                                                <el-form-item prop="gyslxr">
                                                    {{ detailForm.gyslxr || '-' }}
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item>
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    联系电话
                                                </template>
                                                <el-form-item prop="gyslxdh">
                                                    {{ detailForm.gyslxdh || '-' }}
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item>
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    开始合作日期
                                                </template>
                                                <el-form-item prop="kshzrq">
                                                    {{ detailForm.kshzrq || '-' }}
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item>
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    退出提出日期
                                                </template>
                                                <el-form-item prop="tctcrq">
                                                    <el-date-picker
                                                        v-model="addEditForm.tctcrq"
                                                        placeholder="请选择"
                                                        type="date"
                                                        style="width: 100%"
                                                        value-format="YYYY-MM-DD"
                                                    />
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item :span="2">
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    退出类型
                                                </template>
                                                <el-form-item prop="exitType"
                                                    ><el-checkbox-group
                                                        v-model="addEditForm.exitType"
                                                    >
                                                        <el-checkbox
                                                            v-for="item in exitTypeList"
                                                            :key="item.id"
                                                            :label="item.name"
                                                            :value="item.id"
                                                        ></el-checkbox>
                                                    </el-checkbox-group>
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item :span="2">
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    详细原因
                                                </template>
                                                <el-form-item prop="detailedReason">
                                                    <el-input
                                                        v-model="addEditForm.detailedReason"
                                                        placeholder="请输入"
                                                        type="textarea"
                                                        :autosize="{ minRows: 4, maxRows: 6 }"
                                                        clearable
                                                    />
                                                </el-form-item>
                                            </el-descriptions-item>
                                        </el-descriptions>
                                    </div>
                                </el-collapse-item>

                                <el-collapse-item name="score-items">
                                    <template #title>
                                        <div class="section-title">
                                            <el-icon><Document /></el-icon>
                                            <span>供货简历栏</span>
                                        </div>
                                    </template>
                                    <div class="section-content">
                                        <el-table
                                            ref="scoreTableRef"
                                            :data="addEditForm.supplyResumeData"
                                            row-key="id"
                                            @selection-change="handleSelectionChange"
                                        >
                                            <el-table-column label="序号" width="60" align="center">
                                                <template #default="{ $index }">
                                                    {{ $index + 1 }}
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="productName"
                                                label="主要产品名称"
                                                width="180"
                                                align="center"
                                            >
                                                <template #default="{ row }">
                                                    <el-input
                                                        v-model="row.productName"
                                                        placeholder="请输入"
                                                        clearable
                                                    />
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="subProductName"
                                                label="子件品名"
                                                width="180"
                                                align="center"
                                            >
                                                <template #default="{ row }">
                                                    <el-input
                                                        v-model="row.subProductName"
                                                        placeholder="请输入"
                                                        clearable
                                                    />
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="backupSupplierName"
                                                label="备份供应商名称"
                                                width="180"
                                                align="center"
                                            >
                                                <template #default="{ row }">
                                                    <el-input
                                                        v-model="row.backupSupplierName"
                                                        placeholder="请输入"
                                                        clearable
                                                    />
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="noBackupReason"
                                                label="未备份原因"
                                                width="180"
                                                align="center"
                                            >
                                                <template #default="{ row }">
                                                    <el-input
                                                        v-model="row.noBackupReason"
                                                        placeholder="请输入"
                                                        clearable
                                                    />
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                prop="remark"
                                                label="对策方案"
                                                width="180"
                                                align="center"
                                            >
                                                <template #default="{ row }">
                                                    <el-input
                                                        v-model="row.remark"
                                                        placeholder="请输入"
                                                        clearable
                                                    />
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                label="操作"
                                                width="120"
                                                fixed="right"
                                                align="center"
                                            >
                                                <template #default="{ row }">
                                                    <div class="operation-buttons">
                                                        <el-link
                                                            type="primary"
                                                            underline="never"
                                                            @click="handleAdd(row)"
                                                        >
                                                            添加
                                                        </el-link>
                                                        <el-link
                                                            type="danger"
                                                            underline="never"
                                                            @click="deleteItem(row)"
                                                        >
                                                            删除
                                                        </el-link>
                                                    </div>
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                        <el-descriptions :column="2" border>
                                            <el-descriptions-item :span="2">
                                                <template #label> 附件 </template>
                                                <el-form-item prop="b">
                                                    <CustomUploader
                                                        type="button"
                                                        :fileList="fileList"
                                                        :previewAndDownload="false"
                                                        :typeRegularArr="typeRegularArr"
                                                        @change="handleFileChange"
                                                        @startUpload="handleStartUpload"
                                                    >
                                                    </CustomUploader>
                                                </el-form-item>
                                            </el-descriptions-item>
                                        </el-descriptions>
                                    </div>
                                </el-collapse-item>
                            </el-collapse>
                        </el-form>
                    </div>
                </div>
            </div>
        </div>

        <!-- 底部按钮 -->
        <div class="footer">
            <el-button type="primary" @click="handleSubmit">确定</el-button>
            <el-button @click="handleCancel">取消</el-button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { Document, List, Plus, Upload, Delete, Download } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { type FormRules } from 'element-plus'
import ChunkFileUploader from '@/components/ChunkFileUploader/index.vue'

interface AddEditForm {
    [key: string]: string | number | undefined | null | any
}

interface FileItem {
    id?: number | string
    fileName: string
    ignored: boolean
    status?: string
    paused?: boolean
    _prevProgress?: number
    timeRemaining?: () => number
    currentSpeed?: number
    extensionName?: string
    fileId?: string
    [key: string]: any
}

interface ScoreItem {
    id: string
    productName: string
    subProductName: string
    backupSupplierName: string
    noBackupReason: string
    remark: string
}

const route = useRoute()
const router = useRouter()

// 表单相关
const currentStep = ref(0)
const addEditFormRef = ref()
const detailLoading = ref(false)
const activeCollapse = ref(['basic-info', 'score-items'])

// 编辑相关
const isEdit = computed(() => route.name === 'edit')
const editId = computed(() => route.params.id as string)

// 表单数据
const detailForm = reactive<AddEditForm>({})
const addEditForm = reactive<AddEditForm>({
    tctcrq: '',
    exitType: [],
    detailedReason: '',
    supplyResumeData: [
        {
            id: '1',
            productName: '',
            subProductName: '',
            backupSupplierName: '',
            noBackupReason: '',
            remark: ''
        }
    ]
})

// 表单验证规则
const addEditFormRules = reactive<FormRules>({
    tctcrq: [{ required: true, message: '请选择退出提出日期', trigger: 'change' }],
    exitType: [{ required: true, message: '请选择退出类型', trigger: 'change' }],
    detailedReason: [{ required: true, message: '请输入详细原因', trigger: 'blur' }]
})

// 表格相关
const scoreTableRef = ref()
const selectedRows = ref<ScoreItem[]>([])

//退出类型
const exitTypeList = ref([
    {
        id: '1',
        name: '技术薄弱'
    },
    {
        id: '2',
        name: '质量管控不达标'
    },
    {
        id: '3',
        name: '绩效不达标'
    },
    {
        id: '4',
        name: '私自变更'
    },
    {
        id: '5',
        name: '其他'
    }
])

// 表格选择变化
const handleSelectionChange = (selection: ScoreItem[]) => {
    selectedRows.value = selection
}

// 新增简历栏
const handleAdd = () => {
    const newItem: ScoreItem = {
        id: `${Date.now()}`,
        productName: '',
        subProductName: '',
        backupSupplierName: '',
        noBackupReason: '',
        remark: ''
    }
    addEditForm.supplyResumeData.push(newItem)
}

// 删除项（单个删除，带确认）
const deleteItem = (item: ScoreItem) => {
    ElMessageBox.confirm('确定要删除此项吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(() => {
            // 从数组中删除该项
            const index = addEditForm.supplyResumeData.findIndex((row: any) => row.id === item.id)
            if (index !== -1) {
                addEditForm.supplyResumeData.splice(index, 1)
                ElMessage.success('删除成功')
            }
        })
        .catch(() => {
            // 用户取消删除
        })
}

//附件上传
const btnLoading = ref<Boolean>(false)
const readyToUpload = ref<Boolean>(false)
const fileList = ref<FileItem[]>([])
const typeRegularArr = [
    'mp4',
    'mov',
    'avi',
    'mkv',
    'wmv',
    'flv',
    'mpeg',
    'mpg',
    '3gp',
    'webm', // 视频格式
    'doc',
    'docx',
    'xls',
    'xlsx',
    'ppt',
    'pptx',
    'txt',
    'rtf',
    'pdf', // 文档格式
    'jpg',
    'png',
    'bmp',
    'gif' // 图像文件
]
const handleStartUpload = () => {
    btnLoading.value = true
}

const handleFileChange = (files: FileItem[]) => {
    fileList.value = files.map((item) => item as FileItem)
    btnLoading.value = !files.every((item: FileItem) => item.status === 'success')
}

// 取消
const handleCancel = () => {
    router.push({ name: 'SupplierQualified' })
}

// 提交
const handleSubmit = () => {
    addEditFormRef.value?.validate(async (valid: boolean, object: any) => {
        if (valid) {
            ElMessage.success('提交成功')
            // 这里可以添加提交逻辑
        } else {
            ElMessage.warning(
                `有${Object.keys(object || {}).length}个字段未通过校验，请正确填写表单内容。`
            )
        }
    })
}

onMounted(() => {
    readyToUpload.value = true
    // 如果是编辑模式，获取详情数据
    if (isEdit.value) {
        // getDetail(editId.value)
    }
})
</script>

<style lang="scss" scoped>
.form-content {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;

    .page-form {
        overflow-y: hidden;
        overflow-y: auto;
        padding: 0 20px;

        /* 隐藏滚动条样式 */
        &::-webkit-scrollbar {
            width: 0;
            height: 0;
        }

        &::-webkit-scrollbar-track {
            background: transparent;
        }

        &::-webkit-scrollbar-thumb {
            background: transparent;
        }

        /* Firefox 隐藏滚动条 */
        scrollbar-width: none;
        -ms-overflow-style: none;
    }
}
.step-container {
    width: 100%;
    margin-bottom: 20px;
}
.table-actions {
    margin: 16px 0 16px 16px;
}

.content-area {
    /* 确保容器的高度计算正确 */
    box-sizing: border-box;

    :deep(.el-collapse) {
        /* 通过添加 1px 来补偿 border 导致的 1px 高度差 */
        margin-bottom: 1px;
    }
}
</style>
