<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 :span="2">
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    供应商名称
                                                </template>
                                                <el-form-item prop="supplierName">
                                                    {{ addEditForm.supplierName || '-' }}
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item :span="2">
                                                <template #label>
                                                    <!-- <span class="required-asterisk">*</span> -->
                                                    变更描述(变更前)
                                                </template>
                                                <el-form-item prop="beforeChangeContent">
                                                    <el-input
                                                        v-model="addEditForm.beforeChangeContent"
                                                        placeholder="请输入"
                                                        type="textarea"
                                                        :autosize="{ minRows: 4, maxRows: 6 }"
                                                        clearable
                                                    />
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item :span="2">
                                                <template #label>
                                                    <!-- <span class="required-asterisk">*</span> -->
                                                    变更描述(变更后)
                                                </template>
                                                <el-form-item prop="afterChangeContent">
                                                    <el-input
                                                        v-model="addEditForm.afterChangeContent"
                                                        placeholder="请输入"
                                                        type="textarea"
                                                        :autosize="{ minRows: 4, maxRows: 6 }"
                                                        clearable
                                                    />
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item :span="2">
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    变更原因
                                                </template>
                                                <el-form-item prop="changeReason">
                                                    <el-input
                                                        v-model="addEditForm.changeReason"
                                                        placeholder="请输入"
                                                        type="textarea"
                                                        :autosize="{ minRows: 4, maxRows: 6 }"
                                                        clearable
                                                    />
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <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-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
                                            :data="addEditForm.changeDetailData"
                                            border
                                            stripe
                                        >
                                            <el-table-column label="序号" width="60" align="center">
                                                <template #default="{ $index }">
                                                    {{ $index + 1 }}
                                                </template>
                                            </el-table-column>

                                            <el-table-column
                                                label="变更类型"
                                                align="center"
                                                width="120"
                                            >
                                                <template #default="{ row }">
                                                    <el-select
                                                        v-model="row.changeType"
                                                        placeholder="请选择"
                                                        clearable
                                                    >
                                                        <el-option
                                                            v-for="item in changeTypeList"
                                                            :key="item.id"
                                                            :label="item.name"
                                                            :value="item.id"
                                                        />
                                                    </el-select>
                                                </template>
                                            </el-table-column>

                                            <el-table-column
                                                label="资质名称"
                                                align="center"
                                                width="120"
                                            >
                                                <template #default="{ row }">
                                                    <el-select
                                                        v-model="row.name"
                                                        placeholder="请选择"
                                                        @change="changeQualificationName(row)"
                                                        clearable
                                                    >
                                                        <el-option
                                                            v-for="item in ownershipCategoryOptions"
                                                            :key="item.code"
                                                            :label="item.name"
                                                            :value="item.code"
                                                        >
                                                        </el-option>
                                                    </el-select>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                label="资质编号"
                                                align="center"
                                                width="120"
                                            >
                                                <template #default="{ row }">
                                                    <el-input
                                                        v-model="row.code"
                                                        placeholder="请输入"
                                                        clearable
                                                    />
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                label="资质类型名称"
                                                align="center"
                                                width="120"
                                            >
                                                <template #default="{ row }">
                                                    <el-input
                                                        v-model="row.qualificationCategoryName"
                                                        placeholder="请输入"
                                                        clearable
                                                    />
                                                </template>
                                            </el-table-column>
                                            <!-- 
                                            <el-table-column
                                                label="所属权分类"
                                                align="center"
                                                width="120"
                                            >
                                                <template #default="{ row }">
                                                    <el-select
                                                        v-model="row.ownershipCategory"
                                                        placeholder="请选择"
                                                        clearable
                                                    >
                                                        <el-option
                                                            v-for="item in ownershipCategoryOptions"
                                                            :key="item.value"
                                                            :label="item.label"
                                                            :value="item.value"
                                                        />
                                                    </el-select>
                                                </template>
                                            </el-table-column> -->

                                            <el-table-column
                                                label="资质所属权"
                                                align="center"
                                                width="120"
                                            >
                                                <template #default="{ row }">
                                                    <el-select
                                                        v-model="row.qualificationAttribution"
                                                        placeholder="请选择"
                                                        clearable
                                                    >
                                                        <el-option
                                                            v-for="item in getDictionaryByCode(
                                                                'zzss'
                                                            )"
                                                            :key="item.value"
                                                            :label="item.name"
                                                            :value="item.value"
                                                        />
                                                    </el-select>
                                                </template>
                                            </el-table-column>

                                            <el-table-column
                                                label="有效开始期"
                                                align="center"
                                                width="120"
                                            >
                                                <template #default="{ row }">
                                                    <el-date-picker
                                                        v-model="row.issueDate"
                                                        placeholder="请选择"
                                                        type="date"
                                                        style="width: 100%"
                                                        value-format="YYYY-MM-DD"
                                                    />
                                                </template>
                                            </el-table-column>

                                            <el-table-column
                                                label="有效截止期"
                                                align="center"
                                                width="120"
                                            >
                                                <template #default="{ row }">
                                                    <el-date-picker
                                                        v-model="row.validUntil"
                                                        placeholder="请选择"
                                                        type="date"
                                                        style="width: 100%"
                                                        value-format="YYYY-MM-DD"
                                                    />
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                label="附件"
                                                align="center"
                                                width="200"
                                            >
                                                <template #default="{ row }"
                                                    ><CustomUploader
                                                        :fileList="fileList"
                                                        :previewAndDownload="false"
                                                        :typeRegularArr="typeRegularArr"
                                                        @change="handleFileChange"
                                                        @startUpload="handleStartUpload"
                                                    >
                                                    </CustomUploader>
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                label="操作"
                                                align="center"
                                                width="120"
                                                fixed="right"
                                            >
                                                <template #default="{ row, $index }">
                                                    <div class="operation-buttons">
                                                        <el-link
                                                            type="primary"
                                                            :underline="false"
                                                            @click="addQualification()"
                                                        >
                                                            添加
                                                        </el-link>
                                                        <el-link
                                                            type="danger"
                                                            v-if="
                                                                addEditForm.changeDetailData &&
                                                                addEditForm.changeDetailData
                                                                    .length > 1
                                                            "
                                                            :underline="false"
                                                            @click="deleteQualification($index)"
                                                        >
                                                            删除
                                                        </el-link>
                                                    </div>
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                    </div>
                                </el-collapse-item>

                                <el-collapse-item name="material-items">
                                    <template #title>
                                        <div class="section-title">
                                            <el-icon><Document /></el-icon>
                                            <span>受影响的物料</span>
                                        </div>
                                    </template>
                                    <div class="section-content">
                                        <el-table :data="addEditForm.category" border stripe>
                                            <el-table-column label="序号" width="60" align="center">
                                                <template #default="{ $index }">
                                                    {{ $index + 1 }}
                                                </template>
                                            </el-table-column>
                                            <el-table-column label="物料分类名称" align="center">
                                                <template #default="{ row }">
                                                    <el-select
                                                        v-model="row.categoryPlatcode"
                                                        placeholder="请选择"
                                                        clearable
                                                    >
                                                        <el-option
                                                            v-for="item in matClassList"
                                                            :key="item.catNo"
                                                            :label="item.catName"
                                                            :value="item.catNo"
                                                        />
                                                    </el-select>
                                                </template>
                                            </el-table-column>
                                            <el-table-column label="物料名称" align="center">
                                                <template #default="{ row }">
                                                    <el-input
                                                        v-model="row.materialName"
                                                        placeholder="请输入"
                                                        clearable
                                                    />
                                                </template>
                                            </el-table-column>
                                            <el-table-column label="类型" align="center">
                                                <template #default="{ row }"> - </template>
                                            </el-table-column>

                                            <el-table-column
                                                label="操作"
                                                align="center"
                                                width="120"
                                            >
                                                <template #default="{ row, $index }">
                                                    <div class="operation-buttons">
                                                        <el-link
                                                            type="primary"
                                                            :underline="false"
                                                            @click="addMaterial()"
                                                        >
                                                            添加
                                                        </el-link>
                                                        <el-link
                                                            type="danger"
                                                            v-if="
                                                                addEditForm.category &&
                                                                addEditForm.category.length > 1
                                                            "
                                                            :underline="false"
                                                            @click="deleteMaterial($index)"
                                                        >
                                                            删除
                                                        </el-link>
                                                    </div>
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                    </div>
                                </el-collapse-item>
                            </el-collapse>
                        </el-form>
                    </div>
                </div>
            </div>
        </div>

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

<script setup lang="ts">
import { onMounted, reactive, ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { type FormRules } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import CustomUploader from '@/components/CustomUploader/index.vue'
import { dictionaryEscape, getDictionaryByCode } from '@/utils/dictionary'
import { dataTable } from '@/api/supplierMonitor/PersonalInfoManage/QualificationManage'
import { getClassification } from '@/api/supplierMonitor/PersonalInfoManage/QualificationChangeApplication'
import { getCompanyInfo,dataAdd, dataDetail} from '@/api/supplierMonitor/PersonalInfoManage/BasicInfoChangeApplication'
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 {
    [key: string]: any
}

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

// 表单相关
const submitLoading = ref(false)
const currentStep = ref(0)
const addEditFormRef = ref()
const detailLoading = ref(false)
const activeCollapse = ref(['basic-info', 'score-items', 'material-items'])
const matClassList = ref([])
// 编辑相关
const isEdit = computed(() => route.name === 'edit')
const editId = computed(() => route.params.id as string)

// 表单数据
const details = ref<any>({})
const userDetail = ref<any>({})
const addEditForm = reactive<AddEditForm>({
    tctcrq: '',
    supplierName: '',
    supplierCode: '',
    supplierId: '',
    beforeChangeContent: '',
    afterChangeContent:'',
    changeReason:'',
    changeType:'2',
    changeDetailData: [
        {
            id: '1',
            changeType: '1',
            name: '',
            qualificationCategoryName: '',
            qualificationCategoryCode: '',
            ownershipCategory: '',
            code: '',
            qualificationAttribution: '',
            issueDate: '',
            validUntil: ''
        }
    ],
    category: [
        {
            id: '1',
            materialName: '',
            categoryPlatcode: '',
            type: ''
        }
    ]
})

// 表单验证规则
const addEditFormRules = reactive<FormRules>({
    changeReason: [{ required: true, message: '请输入变更原因', trigger: 'blur' }]
})

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

//变更类型
const changeTypeList = ref([
    {
        id: '1',
        name: '变更'
    },
    {
        id: '2',
        name: '新增'
    }
])
// 选择资质名称获取信息
const changeQualificationName = (row: ScoreItem) => {
    const selectedOption = ownershipCategoryOptions.value.find((item) => item.code === row.name)
    if (selectedOption) {
        Object.assign(row, {
            name: selectedOption.name,
            code: selectedOption.code,
            qualificationCategoryName: selectedOption.qualificationCategoryName,
            qualificationCategoryCode: selectedOption.qualificationCategoryCode,
            ownershipCategory: selectedOption.category,
            qualificationAttribution: selectedOption.qualificationAttribution,
            issueDate: selectedOption.issueDate,
            validUntil: selectedOption.validUntil
        })
    }
}
// 获取物料分类
const getMaterialCategory = async () => {
    try {
        const params = {
            pageBean: {
                page: -1,
                pageSize: -1
            },
            querys: []
        }
        const data = await getClassification(params)
        matClassList.value = data.value
    } finally {
    }
}
// 获取资质信息
const getQuilificationInfo = async () => {
    try {
        const params = {
            pageBean: {
                page: -1,
                pageSize: -1
            },
            querys: [{ operation: 'EQUAL', property: 'status', value: '1' }]
        }
        const { total = 0, rows = [] }: { total: number; rows: TableRow[] } =
            await dataTable(params)
        ownershipCategoryOptions.value = rows
    } finally {
    }
}

// 企业资质相关方法
const addQualification = () => {
    addEditForm.changeDetailData.push({
        id: '',
        changeType: '',
        name: '',
        code: '',
        qualificationCategoryName: '',
        qualificationCategoryCode: '',
        ownershipCategory: '',
        qualificationAttribution: '',
        issueDate: '',
        validUntil: ''
    })
}

const deleteQualification = (index: number) => {
    ElMessageBox.confirm('确定要删除这条资质信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(() => {
            addEditForm.changeDetailData.splice(index, 1)
            ElMessage.success('删除成功')
        })
        .catch(() => {
            ElMessage.info('已取消删除')
        })
}

//受影响的物料
const addMaterial = () => {
    addEditForm.category.push({
        id: '',
        materialName: '',
        categoryPlatcode: '',
        type: ''
    })
}

const deleteMaterial = (index: number) => {
    ElMessageBox.confirm('确定要删除这条物料信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(() => {
            addEditForm.category.splice(index, 1)
            ElMessage.success('删除成功')
        })
        .catch(() => {
            ElMessage.info('已取消删除')
        })
}
//附件上传
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 addGetBasicInfo = async (orgId: string) => {
    detailLoading.value = true
    const { ...rest } = (await getCompanyInfo(orgId)) as AddEditForm
    if (rest.state) {
        detailLoading.value = false
        Object.assign(details, {
            ...rest.value
        })
    } else {
        detailLoading.value = false
    }
}
// 数据获取
const getDetail = async (id: string) => {
    // 获取详情逻辑
    const { ...rest } = (await dataDetail(id)) as AddEditForm
    Object.assign(details, {
        ...rest.value.information
    })
    addEditForm.id = route.query.id
    addEditForm.afterChangeContent = rest.value.afterChangeContent
    addEditForm.beforeChangeContent = rest.value.beforeChangeContent
    addEditForm.changeReason = rest.value.changeReason
    addEditForm.supplierName = rest.value.supplierName
    addEditForm.changeDetailData = rest.value.information.qualification
    addEditForm.category = rest.value.information.category
}
// 取消
const handleCancel = () => {
    router.push({ name: 'QualificationChangeApplication' })
}

// 提交
const handleSubmit = () => {
    addEditFormRef.value?.validate(async (valid: boolean, object: any) => {
        if (valid) {
            // 更新当前激活菜单项的保存状态
            try {
                let form = {
                    beforeChangeDataId: '',
                    beforeChangeDataVersion: '',
                    changeInitiatorName: '',
                    changeInitiatorStartDate: '',
                    changeType: '2',
                    changeReason: '',
                    information: {},
                    supplierCode: '',
                    supplierId: '',
                    supplierName: '',
                    changeInitiatorId: '',
                    changeInitiatorAccount: '',
                    status: '0',
                    afterChangeContent:'',
                    beforeChangeContent: '',
                }
                form.afterChangeContent = addEditForm.afterChangeContent
                form.beforeChangeContent = addEditForm.beforeChangeContent
                form.beforeChangeDataId = addEditForm.id
                form.beforeChangeDataVersion = addEditForm.version
                form.changeInitiatorName = addEditForm.changeInitiatorName
                form.changeInitiatorStartDate = addEditForm.changeInitiatorStartDate
                form.changeType = addEditForm.changeType
                form.changeReason = addEditForm.changeReason
                form.information = details
                form.supplierCode = addEditForm.supplierCode
                form.supplierId = addEditForm.supplierId
                form.supplierName = userDetail.value.userDetail.org[0].orgName
                form.changeInitiatorId = userDetail.value.userInfo.userId
                form.changeInitiatorName = userDetail.value.userInfo.username
                form.changeInitiatorAccount = userDetail.value.userInfo.account
                form.information.qualification = addEditForm.changeDetailData
                form.information.category = addEditForm.category
                if(route.query.id){
                    form.id = route.query.id
                }
                submitLoading.value = true
                const value = await dataAdd(form)
                if (value.state) {
                    ElMessage.success('保存成功')
                    handleCancel()
                }
            } finally {
                submitLoading.value = false // 无论成功或失败，都关闭加载状态
            }
        } else {
            ElMessage.warning(
                `有${Object.keys(object || {}).length}个字段未通过校验，请正确填写表单内容。`
            )
        }
    })
}

onMounted(() => {
    const storedData = sessionStorage.getItem('user')
    if (storedData) {
        userDetail.value = JSON.parse(storedData)
    }
    addEditForm.supplierCode = userDetail.value.userDetail.org[0].orgCode
    addEditForm.supplierId = userDetail.value.userDetail.org[0].orgId
    addEditForm.supplierName = userDetail.value.userDetail.org[0].orgName
    getQuilificationInfo()
    getMaterialCategory()
    readyToUpload.value = true
    // 如果是编辑模式，获取详情数据
    if (route.query.id) {
        getDetail(route.query.id)
    } else {
        addGetBasicInfo(userDetail.value.userDetail.org[0].orgId)
    }
})
</script>

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

    .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>
