<template>
    <div class="edit-add-detail">
        <div v-loading="detailLoading" class="form-content" element-loading-text="加载中...">
            <div class="page-form">
                <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="qualificationCategoryName">
                                            <el-select
                                                v-model="addEditForm.qualificationCategoryName"
                                                placeholder="请选择"
                                                clearable
                                                @change="changeQualification"
                                            >
                                                <el-option
                                                    v-for="item in qualificationTypeList"
                                                    :key="item.id"
                                                    :label="item.qualificationCategoryName"
                                                    :value="item.qualificationCategoryCode"
                                                ></el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item>
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            资质名称
                                        </template>
                                        <el-form-item prop="name">
                                            <el-input
                                                v-model="addEditForm.name"
                                                placeholder="请输入"
                                                clearable
                                            />
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item>
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            资质编码
                                        </template>
                                        <el-form-item prop="code">
                                            <el-input
                                                v-model="addEditForm.code"
                                                placeholder="请输入"
                                                clearable
                                            />
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item>
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            资质所属
                                        </template>
                                        <el-form-item prop="qualificationAttribution">
                                            <el-select
                                                v-model="addEditForm.qualificationAttribution"
                                                placeholder="请选择"
                                            >
                                                <el-option
                                                    v-for="(item, i) in getDictionaryByCode('zzss')"
                                                    :key="i"
                                                    :label="item.name"
                                                    :value="item.value"
                                                >
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item
                                        v-if="addEditForm.qualificationAttribution == 0"
                                    >
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            企业名称
                                        </template>
                                        <el-form-item prop="enterpriseName">
                                            <el-input v-model="addEditForm.enterpriseName" placeholder="" disabled></el-input>
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item
                                        v-if="addEditForm.qualificationAttribution == 1"
                                    >
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            姓名
                                        </template>
                                        <el-form-item prop="fullName">
                                            <el-input
                                                v-model="addEditForm.fullName"
                                                placeholder="请输入"
                                                clearable
                                            />
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item>
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            行业分类
                                        </template>
                                        <el-form-item prop="industry">
                                            <el-select
                                                v-model="addEditForm.industry"
                                                placeholder="请选择"
                                            >
                                                <el-option
                                                    v-for="(item, i) in getDictionaryByCode('hyfl')"
                                                    :key="i"
                                                    :label="item.name"
                                                    :value="item.value"
                                                >
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item>
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            发证机构
                                        </template>
                                        <el-form-item prop="issuingAuthority">
                                            <el-input
                                                v-model="addEditForm.issuingAuthority"
                                                placeholder="请输入"
                                                clearable
                                            />
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item>
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            时间期限
                                        </template>
                                        <el-form-item prop="timeLimit">
                                            <el-select
                                                v-model="addEditForm.timeLimit"
                                                placeholder="请选择"
                                                @change="changeTimeLimit"
                                            >
                                                <el-option
                                                    v-for="(item, i) in getDictionaryByCode('sjqx')"
                                                    :key="i"
                                                    :label="item.name"
                                                    :value="item.value"
                                                >
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item>
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            有效开始期
                                        </template>
                                        <el-form-item prop="issueDate">
                                            <el-date-picker
                                                v-model="addEditForm.issueDate"
                                                placeholder="请选择有效开始期"
                                                type="date"
                                                value-format="YYYY-MM-DD"
                                                format="YYYY-MM-DD"
                                                clearable
                                            />
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item v-if="addEditForm.timeLimit == 0">
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            有效截止期
                                        </template>
                                        <el-form-item prop="validUntil">
                                            <el-date-picker
                                                value-format="YYYY-MM-DD"
                                                format="YYYY-MM-DD"
                                                type="date"
                                                v-model="addEditForm.validUntil"
                                                clearable
                                                placeholder="请选择有效期至"
                                            ></el-date-picker>
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item :span="2">
                                        <template #label>
                                            <span class="required-asterisk">*</span>
                                            状态
                                        </template>
                                        <el-form-item prop="industry">
                                            <el-select
                                                v-model="addEditForm.status"
                                                placeholder="请选择"
                                            >
                                                <el-option
                                                    v-for="(item, i) in getDictionaryByCode(
                                                        'qyzzkzt'
                                                    )"
                                                    :key="i"
                                                    :label="item.name"
                                                    :value="item.value"
                                                >
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-descriptions-item>
                                    <el-descriptions-item :span="2">
                                        <template #label> 备注 </template>
                                        <el-form-item prop="remarks">
                                            <el-input
                                                v-model="addEditForm.remarks"
                                                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="files">
                                            <ChunkFileUploader
                                                type="button"
                                                :maxFileCount="1"
                                                :fileList="addEditForm.files"
                                                :previewAndDownload="false"
                                                :typeRegularArr="typeRegularArr"
                                                @change="handleFileChange"
                                                @startUpload="handleStartUpload"
                                            >
                                            </ChunkFileUploader>
                                        </el-form-item>
                                    </el-descriptions-item>
                                </el-descriptions>
                            </div>
                        </el-collapse-item>
                    </el-collapse>
                </el-form>
            </div>
        </div>

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

<script setup lang="ts">
import ChunkFileUploader from '@/components/ChunkFileUploader/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { dictionaryEscape, getDictionaryByCode } from '@/utils/dictionary'
import { type FormRules } from 'element-plus'
import { reactive, ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
    dataAdd,
    dataUpdate,
    dataDetail,
    dataQualificationList,
    dataEnterpriseList
} from '@/api/supplierMonitor/BasicManagement/EnterpriseLibrary'
interface AddEditForm {
    [key: string]: string | number | undefined | null | any
}
interface FileItem {
    id?: string
    fileId?: string
    status: string

    [key: string]: any
}
const route = useRoute()
const router = useRouter()
const options = reactive([{ id: 1, name: '永久', value: 1 }])
const userDetail = ref<any>({})
// 表单相关
const addEditFormRef = ref()
const supplierLoading = ref(false)
const detailLoading = ref(false)
const activeCollapse = ref(['basic-info'])
const qualificationTypeList = ref([])
const btnLoading = ref(false)
const enterpriseList = ref([])
// 编辑相关
const isEdit = computed(() => route.name === 'edit')
const editId = computed(() => route.params.id as string)

// 表单数据
const addEditForm = reactive<AddEditForm>({
    name: '',
    code: '',
    issueDate: '',
    validUntil: '',
    remarks: '',
    enterpriseName:'',
    enterpriseCode:'',
    enterpriseId:'',
    industry: '',
    qualificationAttribution: '0',
    fullName: '',
    issuingAuthority: '',
    qualificationCategoryName: '',
    qualificationCategoryCode: '',
    timeLimit: '0',
    status: '1',
    files: []
})

// 表单验证规则
const addEditFormRules = reactive<FormRules>({
    name: [{ required: true, message: '请输入资质名称', trigger: 'blur' }],
    code: [{ required: true, message: '请输入资质编码', trigger: 'blur' }],
    issueDate: [{ required: true, message: '请选择有效开始期', trigger: 'change' }],
    qualificationCategoryName: [{ required: true, message: '请选择资质类型', trigger: 'change' }],
    industry: [{ required: true, message: '请选择所属行业', trigger: 'change' }],
    validUntil: [{ required: true, message: '请选择有效截止期', trigger: 'change' }],
    fullName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    enterpriseCode: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
    issuingAuthority: [{ required: true, message: '请输入发证机构', trigger: 'blur' }],
    qualificationAttribution: [{ required: true, message: '请选择资质所属', trigger: 'change' }],
    files: [{ required: true, message: '请上传附件', trigger: 'change' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }]
})
// 附件上传
const typeRegularArr = [
    'doc',
    'docx',
    'xls',
    'xlsx',
    'ppt',
    'pptx',
    'txt',
    'pdf', // 文档格式
    'jpg',
    'png',
    'gif' // 图像文件
]
const handleStartUpload = () => {
    btnLoading.value = true
}

const handleFileChange = (file: [FileItem]) => {
    addEditForm.files = file.map((item) => item as FileItem)
    btnLoading.value = !file.every((item: FileItem) => item.status === 'success')
}
// 取消
const handleCancel = () => {
    router.push({ name: 'QualificationManage' })
}
getDictionaryByCode

// 获取详情数据
const getDetail = async (id: string | number) => {
    try {
        detailLoading.value = true
        const value = await dataDetail(id)
        Object.assign(addEditForm, value)
        // 确保timeLimit为字符串类型
        if (value.timeLimit !== undefined && value.timeLimit !== null) {
            addEditForm.timeLimit = String(value.timeLimit)
        }
        addEditForm.files = value.files.map((item: any) => {
            return {
                ...item,
                status: 'success',
                fileId: item.id
            }
        })
    } finally {
        detailLoading.value = false // 无论成功或失败，都关闭加载状态
    }
}
// 选择资质类型名称
const changeQualification = (value: any) => {
    addEditForm.qualificationCategoryCode = value
    qualificationTypeList.value.forEach((item: any) => {
        if (item.qualificationCategoryCode === value) {
            addEditForm.qualificationCategoryName = item.qualificationCategoryName
        }
    })
}

// 选择时间期限
const changeTimeLimit = (value: any) => {
    if (value == 1) {
        addEditForm.validUntil = ''
    }
}
// 获取资质类型列表
const getQualificationList = async () => {
    let params = {
        pageBean: {
            page: -1,
            pageSize: -1
        },
        querys: [
            { group: 'main', operation: 'EQUAL', property: 'status', relation: 'AND', value: '1' }
        ]
    }
    const { total = 0, rows = [] } = await dataQualificationList(params)
    qualificationTypeList.value = rows
}

onMounted(() => {
    const storedData = localStorage.getItem('user')
    if (storedData) {
        userDetail.value = JSON.parse(storedData)
    }
    addEditForm.enterpriseCode = userDetail.value.userDetail.org[0].orgCode
    addEditForm.enterpriseId = userDetail.value.userDetail.org[0].orgId
    addEditForm.enterpriseName = userDetail.value.userDetail.org[0].orgName
    getQualificationList()
    // 如果是编辑模式，获取详情数据
    if (route.query.id) {
        getDetail(route.query.id)
    }
})
</script>

<style lang="scss" scoped></style>
