<template>
    <div class="edit-add-detail">
        <div v-loading="detailLoading" class="form-content" element-loading-text="加载中...">
            <div class="page-form">
                <!-- 主要内容区域 -->
                <div class="main-content">
                    <!-- 右侧内容区域 -->
                    <el-form
                        ref="addEditFormRef"
                        :model="addEditForm"
                        :rules="addEditFormRules"
                        size="large"
                        label-position="left"
                        label-suffix="："
                    >
                        <el-collapse v-model="activeCollapse">
                            <!-- 基本情况 -->
                            <div class="content-section" id="basic-info">
                                <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="enterpriseName">
                                                    {{ addEditForm.enterpriseName }}
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item>
                                                <template #label>
                                                    <span class="required-asterisk">*</span>类型
                                                </template>
                                                <el-form-item prop="enterpriseType">
                                                    <el-select
                                                        v-model="addEditForm.enterpriseType"
                                                        placeholder="请选择"
                                                        clearable
                                                        filterable
                                                    >
                                                        <el-option
                                                            v-for="item in getDictionaryByCode(
                                                                'gysgl-gslx'
                                                            )"
                                                            :key="item.value"
                                                            :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="registeredAmount">
                                                    <el-input
                                                        v-model="addEditForm.registeredAmount"
                                                        placeholder="请输入"
                                                    >
                                                        <template #append>万元（RMB）</template>
                                                    </el-input>
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item>
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    法定代表人
                                                </template>
                                                <el-form-item prop="legalRepresentative">
                                                    <el-input
                                                        v-model="addEditForm.legalRepresentative"
                                                        clearable
                                                        placeholder="请输入"
                                                    />
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item>
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    统一社会信用代码
                                                </template>
                                                <el-form-item prop="creditCode">
                                                    <el-input
                                                        v-model="addEditForm.creditCode"
                                                        clearable
                                                        placeholder="请输入"
                                                    />
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item>
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    成立日期
                                                </template>
                                                <el-form-item prop="establishmentTime">
                                                    <el-date-picker
                                                        v-model="addEditForm.establishmentTime"
                                                        placeholder="请选择"
                                                        type="date"
                                                        value-format="YYYY-MM-DD"
                                                    />
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item>
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    有效期至
                                                </template>
                                                <el-form-item prop="endBusinessTerm">
                                                    <el-select
                                                        style="width: 100%"
                                                        clearable
                                                        @change="changeData"
                                                        v-model="addEditForm.endBusinessTerm"
                                                        placeholder="请选择有效期至"
                                                    >
                                                        <el-option
                                                            v-for="item in options"
                                                            :key="item.value"
                                                            :label="item.name"
                                                            :value="item.value"
                                                        >
                                                        </el-option>
                                                        <el-date-picker
                                                            value-format="YYYY-MM-DD"
                                                            format="YYYY-MM-DD"
                                                            v-model="addEditForm.endBusinessTerm"
                                                            @change="changeDate"
                                                            style="width: 100%"
                                                            clearable
                                                            placeholder="请选择有效期至"
                                                        ></el-date-picker>
                                                    </el-select>
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item :span="2">
                                                <template #label>
                                                    <span class="required-asterisk">*</span
                                                    >住所</template
                                                >
                                                <el-form-item prop="address">
                                                    <el-input
                                                        v-model="addEditForm.address"
                                                        type="textarea"
                                                        clearable
                                                        placeholder="请输入"
                                                    />
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item>
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    经营范围
                                                </template>
                                                <el-form-item prop="businessScope">
                                                    <el-input
                                                        v-model="addEditForm.businessScope"
                                                        clearable
                                                        type="textarea"
                                                        placeholder="请输入"
                                                    />
                                                </el-form-item>
                                            </el-descriptions-item>
                                        </el-descriptions>
                                    </div>
                                </el-collapse-item>
                            </div>
                        </el-collapse>
                    </el-form>
                </div>
            </div>
        </div>
        <div class="footer">
            <el-button @click="handleCancel">关 闭</el-button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { dictionaryEscape, getDictionaryByCode } from '@/utils/dictionary'
import { useRoute, useRouter } from 'vue-router'
import {
    dataUpdate,
    dataAdd,
    dataDetail
} from '@/api/supplierMonitor/PersonalInfoManage/MyRegistrationInfo'
import CustomUploader from '@/components/CustomUploader/index.vue'
import { add } from 'lodash'

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 userDetail = ref<any>({})
const editId = ref((route.query.id as string) || '')
const isEdit = computed(() => !!editId.value)
const detailLoading = ref(false) // 详情加载状态
const btnLoading = ref<Boolean>(false)
// 表单相关
const options = ref([{ id: 1, name: '长期', value: 1 }])
const activeCollapse = ref('basic-info') // 当前激活的折叠面板
const addEditFormRef = ref<FormInstance>()
const addEditFormRules = reactive<FormRules>({
    enterpriseType: [{ required: true, message: '请选择企业类型', trigger: 'change' }],
    registeredAmount: [{ required: true, message: '请输入注册资本', trigger: 'blur' }],
    legalRepresentative: [{ required: true, message: '请输入法定代表人', trigger: 'blur' }],
    creditCode: [{ required: true, message: '请输入统一社会信用代码', trigger: 'blur' }],
    establishmentTime: [{ required: true, message: '请选择成立日期', trigger: 'change' }],
    endBusinessTerm: [{ required: true, message: '请选择有效期至', trigger: 'change' }],
    address: [{ required: true, message: '请输入住所', trigger: 'blur' }],
    businessScope: [{ required: true, message: '请输入经营范围', trigger: 'blur' }]
})
const addEditForm = reactive<AddEditForm>({
    enterpriseCode: '',
    enterpriseId: '',
    enterpriseName: '',
    enterpriseType: '',
    registeredAmount: '',
    legalRepresentative: '',
    creditCode: '',
    establishmentTime: '',
    endBusinessTerm: '',
    address: '',
    businessScope: '',
    timeLimit: ''
})

// 数据获取
const getDetail = async (id: string) => {
    detailLoading.value = true
    try {
        const { ...rest } = (await dataDetail(id)) as AddEditForm
        Object.assign(addEditForm, {
            ...rest
        })
        if (addEditForm.timeLimit == 1) {
            addEditForm.endBusinessTerm = 1
        }
    } finally {
        detailLoading.value = false
    }
}

const handleSubmit = () => {
    addEditFormRef.value?.validate(async (valid, object) => {
        if (valid) {
            try {
                btnLoading.value = true
                const value = addEditForm.id
                    ? await dataUpdate({ ...addEditForm })
                    : await dataAdd({ ...addEditForm })
                if (value.state) {
                    ElMessage.success('保存成功')
                    router.push({ name: 'MyRegistrationInfo' })
                }
            } finally {
                btnLoading.value = false // 无论成功或失败，都关闭加载状态
            }
        } else {
            ElMessage.warning(
                `有${Object.keys(object || {}).length}个字段未通过校验，请正确填写表单内容。`
            )
        }
    })
}
const changeData = (data: string) => {
    if (data == 1) {
        addEditForm.timeLimit = 1
    }
}
const changeDate = (date: string) => {
    addEditForm.endBusinessTerm = date
    addEditForm.timeLimit = 0
}
const handleCancel = () => {
    router.push({ name: 'MyRegistrationInfo' })
}
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
    if (route.query.id) {
        getDetail(route.query.id)
    }
})

onUnmounted(() => {})
</script>

<style lang="scss" scoped>
.edit-add-detail {
    .form-content {
        display: flex;
        flex-direction: column;
        align-items: center;

        .page-form {
            width: 80%;
            overflow-x: hidden;
            overflow-y: auto;
            max-height: 100%;
            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;
            padding: 20px;
            border-radius: 8px;
        }

        .main-content {
            gap: 20px;
            width: 100%;
            padding-bottom: 20px;

            .sidebar-menu {
                width: 180px;
                background-color: var(--theme-search-wrapper-bg);
                box-shadow: 0px 0px 20px 0px rgba(0, 36, 65, 0.2);
                border-radius: 16px;
                padding: 10px 20px 20px 20px;
                height: fit-content;
                position: sticky;
                top: 10px;

                .menu-section {
                    margin-bottom: 30px;

                    .menu-title {
                        font-size: 16px;
                        font-weight: bold;
                        color: var(--theme-text-primary);
                        white-space: pre;
                    }

                    .menu-items {
                        .menu-item {
                            font-size: 14px;
                            padding: 10px 15px;
                            margin-bottom: 5px;
                            cursor: pointer;
                            border-radius: 4px;
                            transition: all 0.3s ease;
                            color: var(--theme-text-primary);
                            display: flex;
                            justify-content: space-between;
                            align-items: center;

                            &:hover {
                                background-color: var(--theme-system-module-1);
                                color: var(--theme-primary);
                            }

                            &.active {
                                background-color: var(--theme-primary);
                                color: white;
                            }

                            .save-icon {
                                font-size: 20px;

                                &.saved {
                                    color: #67c23a; /* 绿色 */
                                }

                                &.not-saved {
                                    color: #c0c4cc; /* 灰色 */
                                }
                            }
                        }
                    }
                }
            }

            .content-area {
                width: calc(100% - 180px - 80px);
                background-color: var(--theme-form-content-bg);
                border-radius: 8px;
                padding: 20px 20px 0 20px;

                .content-section {
                    margin-bottom: 20px;

                    .content-title {
                        margin-bottom: 5px;
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        .content-title-left {
                            font-size: 14px;
                            font-weight: bold;
                            color: var(--theme-text-primary);
                            display: flex;
                            align-items: center;
                        }
                        .content-title-left::before {
                            content: '';
                            display: inline-block;
                            width: 4px;
                            height: 18px;
                            background-color: #1a8cff;
                            border-radius: 2px;
                            margin-right: 8px;
                        }
                    }

                    .site-inspection-content {
                        background-color: #f5f8fa;
                        padding: 16px;
                        box-sizing: border-box;
                        .review-requirements {
                            margin-bottom: 10px;
                            .review-requirements-title {
                                color: var(--theme-text-primary);
                                margin-bottom: 5px;
                                font-size: 14px;
                                font-weight: bold;
                            }
                            ul {
                                list-style: none;
                                li {
                                    color: var(--theme-text-primary);
                                    line-height: 25px;
                                    font-size: 14px;
                                }
                            }
                        }
                    }

                    .section-content {
                        color: var(--theme-text-inverse);

                        .review-actions {
                            display: flex;
                            padding: 10px 0 10px 10px;
                        }
                    }
                }
            }
        }
    }
}

// 表格相关样式
.operation-buttons {
    display: flex;
    justify-content: center;
}

.table-header {
    margin: 10px 0 10px 10px;
    display: flex;
    justify-content: flex-start;
}

.attachment-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;

    .attachment-name {
        font-size: 12px;
        color: var(--theme-text-color);
    }
}
</style>
