<template>
    <div class="diagnosis-page">
        <!-- 页面头部 -->
        <div class="page-header">
            <el-button link @click="handleBack" class="back-btn">
                <el-icon><ArrowLeft /></el-icon>
                返回
            </el-button>
            <h1 class="page-title">{{ pageTitle }}</h1>
        </div>

        <!-- 表单内容 -->
        <div class="page-content">
            <el-form
                ref="formRef"
                :model="formData"
                :rules="formRules"
                label-width="auto"
                class="diagnosis-form"
            >
                <!-- 基本信息 -->
                <div class="form-section">
                    <div class="section-title">基本信息</div>
                    
                    <el-form-item label="患者ID">
                        <el-input v-model="formData.patient_id" disabled placeholder="系统自动生成" />
                    </el-form-item>

                    <el-form-item label="患者姓名" prop="patient_name">
                        <el-input v-model="formData.patient_name" placeholder="请输入患者姓名" />
                    </el-form-item>

                    <el-form-item label="身份证号" prop="id_card">
                        <el-input
                            v-model="formData.id_card"
                            placeholder="请输入身份证号"
                            maxlength="18"
                            @blur="handleIdCardBlur"
                        />
                    </el-form-item>

                    <el-form-item label="手机号" prop="phone">
                        <el-input
                            v-model="formData.phone"
                            placeholder="请输入手机号"
                            maxlength="11"
                            @blur="handlePhoneBlur"
                        />
                    </el-form-item>

                    <el-form-item label="性别" prop="gender">
                        <el-radio-group v-model="formData.gender">
                            <el-radio :label="1">男</el-radio>
                            <el-radio :label="0">女</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="年龄" prop="age">
                        <el-input-number
                            v-model="formData.age"
                            :min="0"
                            :max="150"
                            placeholder="请输入年龄"
                            class="w-full"
                        />
                    </el-form-item>

                    <el-form-item label="诊断日期" prop="diagnosis_date">
                        <el-date-picker
                            v-model="formData.diagnosis_date"
                            type="date"
                            placeholder="请选择诊断日期"
                            value-format="YYYY-MM-DD"
                            class="w-full"
                        />
                    </el-form-item>
                </div>

                <!-- 生命体征 -->
                <div class="form-section">
                    <div class="section-title">生命体征</div>
                    
                    <el-form-item label="婚姻状态" prop="marital_status">
                        <el-select v-model="formData.marital_status" placeholder="请选择婚姻状态" class="w-full">
                            <el-option label="未婚" :value="0" />
                            <el-option label="已婚" :value="1" />
                            <el-option label="离异" :value="2" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="身高(cm)" prop="height">
                        <el-input-number
                            v-model="formData.height"
                            :min="0"
                            :max="300"
                            placeholder="请输入身高"
                            class="w-full"
                        />
                    </el-form-item>

                    <el-form-item label="体重(kg)" prop="weight">
                        <el-input-number
                            v-model="formData.weight"
                            :min="0"
                            :max="500"
                            :step="0.1"
                            placeholder="请输入体重"
                            class="w-full"
                        />
                    </el-form-item>

                    <el-form-item label="地区" prop="region">
                        <el-input v-model="formData.region" placeholder="请输入地区" />
                    </el-form-item>

                    <el-form-item label="收缩压(mmHg)" prop="systolic_pressure">
                        <el-input-number
                            v-model="formData.systolic_pressure"
                            :min="0"
                            :max="250"
                            placeholder="请输入收缩压"
                            class="w-full"
                        />
                    </el-form-item>

                    <el-form-item label="舒张压(mmHg)" prop="diastolic_pressure">
                        <el-input-number
                            v-model="formData.diastolic_pressure"
                            :min="0"
                            :max="150"
                            placeholder="请输入舒张压"
                            class="w-full"
                        />
                    </el-form-item>

                    <el-form-item label="空腹血糖(mmol/L)" prop="fasting_blood_sugar">
                        <el-input
                            v-model="formData.fasting_blood_sugar"
                            placeholder="请输入空腹血糖，如：8.5 或 8-9"
                            maxlength="20"
                            class="w-full"
                        />
                    </el-form-item>
                </div>

                <!-- 诊断类型 -->
                <div class="form-section">
                    <div class="section-title">诊断信息</div>
                    
                    <el-form-item label="诊断类型" prop="diagnosis_type">
                        <el-select v-model="formData.diagnosis_type" placeholder="请选择诊断类型" class="w-full">
                            <el-option
                                v-for="item in diagnosisTypeOptions"
                                :key="item.value"
                                :label="item.name"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="证型" prop="syndrome_type">
                        <el-select v-model="formData.syndrome_type" placeholder="请选择证型" class="w-full">
                            <el-option
                                v-for="item in syndromeTypeOptions"
                                :key="item.value"
                                :label="item.name"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="糖尿病期数" prop="diabetes_type">
                        <el-select v-model="formData.diabetes_type" placeholder="请选择糖尿病期数" class="w-full">
                            <el-option
                                v-for="item in diabetesTypeOptions"
                                :key="item.value"
                                :label="item.name + (item.remark ? ' (' + item.remark + ')' : '')"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="状态" prop="status">
                        <el-radio-group v-model="formData.status">
                            <el-radio :label="1">启用</el-radio>
                            <el-radio :label="0">禁用</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="在用药物" prop="current_medications">
                        <el-input
                            v-model="formData.current_medications"
                            type="textarea"
                            :rows="3"
                            placeholder="请填写患者当前正在使用的药物（如降压药、降糖药等），多种请换行或顿号分隔"
                            maxlength="2000"
                            show-word-limit
                        />
                    </el-form-item>
                </div>

                <!-- 主诉 -->
                <div class="form-section">
                    <div class="section-title">主诉</div>
                    
                    <el-form-item label="发现糖尿病就患病史" prop="diabetes_discovery_year">
                        <el-input
                            v-model="formData.diabetes_discovery_year"
                            clearable
                            maxlength="50"
                            show-word-limit
                            placeholder="可填数字或文字，如：5、1年、半年"
                            class="w-full"
                        />
                    </el-form-item>

                    <el-form-item label="当地医院诊断结果">
                        <el-checkbox-group v-model="formData.local_hospital_diagnosis" class="checkbox-group">
                            <el-checkbox-button label="糖尿病">糖尿病</el-checkbox-button>
                            <el-checkbox-button label="高血压">高血压</el-checkbox-button>
                            <el-checkbox-button label="糖尿病高血压">糖尿病高血压</el-checkbox-button>
                        </el-checkbox-group>
                    </el-form-item>

                    <el-form-item label="当地就诊医院名称" prop="local_hospital_name">
                        <el-input
                            v-model="formData.local_hospital_name"
                            placeholder="请输入当地就诊医院名称（不能填写当地、本地、互联网等关键词）"
                        />
                    </el-form-item>
                </div>

                <!-- 现病史 -->
                <div class="form-section">
                    <div class="section-title">现病史</div>
                    
                    <el-form-item label="口腔感觉">
                        <el-radio-group v-model="formData.appetite" class="radio-group">
                            <el-radio-button v-for="item in appetiteOptions" :key="item.value" :label="item.value">
                                {{ item.name }}
                            </el-radio-button>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="每日饮水量">
                        <el-radio-group v-model="formData.water_intake" class="radio-group">
                            <el-radio-button v-for="item in waterIntakeOptions" :key="item.value" :label="item.value">
                                {{ item.name }}
                            </el-radio-button>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="近一个月体重变化">
                        <el-radio-group v-model="formData.weight_change" class="radio-group">
                            <el-radio-button v-for="item in weightChangeOptions" :key="item.value" :label="item.value">
                                {{ item.name }}
                            </el-radio-button>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="脂肪肝程度">
                        <el-radio-group v-model="formData.fatty_liver_degree" class="radio-group">
                            <el-radio-button v-for="item in fattyLiverDegreeOptions" :key="item.value" :label="item.value">
                                {{ item.name }}
                            </el-radio-button>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="饮食情况">
                        <el-checkbox-group v-model="formData.diet_condition" class="checkbox-group">
                            <el-checkbox-button v-for="item in dietConditionOptions" :key="item.value" :label="item.value">
                                {{ item.name }}
                            </el-checkbox-button>
                        </el-checkbox-group>
                    </el-form-item>

                    <el-form-item label="肢体感觉">
                        <el-checkbox-group v-model="formData.body_feeling" class="checkbox-group">
                            <el-checkbox-button v-for="item in bodyFeelingOptions" :key="item.value" :label="item.value">
                                {{ item.name }}
                            </el-checkbox-button>
                        </el-checkbox-group>
                    </el-form-item>

                    <el-form-item label="睡眠情况">
                        <el-checkbox-group v-model="formData.sleep_condition" class="checkbox-group">
                            <el-checkbox-button v-for="item in sleepConditionOptions" :key="item.value" :label="item.value">
                                {{ item.name }}
                            </el-checkbox-button>
                        </el-checkbox-group>
                    </el-form-item>

                    <el-form-item label="眼睛情况">
                        <el-checkbox-group v-model="formData.eye_condition" class="checkbox-group">
                            <el-checkbox-button v-for="item in eyeConditionOptions" :key="item.value" :label="item.value">
                                {{ item.name }}
                            </el-checkbox-button>
                        </el-checkbox-group>
                    </el-form-item>

                    <el-form-item label="头部感觉">
                        <el-checkbox-group v-model="formData.head_feeling" class="checkbox-group">
                            <el-checkbox-button v-for="item in headFeelingOptions" :key="item.value" :label="item.value">
                                {{ item.name }}
                            </el-checkbox-button>
                        </el-checkbox-group>
                    </el-form-item>

                    <el-form-item label="出汗情况">
                        <el-checkbox-group v-model="formData.sweat_condition" class="checkbox-group">
                            <el-checkbox-button v-for="item in sweatConditionOptions" :key="item.value" :label="item.value">
                                {{ item.name }}
                            </el-checkbox-button>
                        </el-checkbox-group>
                    </el-form-item>

                    <el-form-item label="皮肤情况">
                        <el-checkbox-group v-model="formData.skin_condition" class="checkbox-group">
                            <el-checkbox-button v-for="item in skinConditionOptions" :key="item.value" :label="item.value">
                                {{ item.name }}
                            </el-checkbox-button>
                        </el-checkbox-group>
                    </el-form-item>

                    <el-form-item label="小便情况">
                        <el-checkbox-group v-model="formData.urine_condition" class="checkbox-group">
                            <el-checkbox-button v-for="item in urineConditionOptions" :key="item.value" :label="item.value">
                                {{ item.name }}
                            </el-checkbox-button>
                        </el-checkbox-group>
                    </el-form-item>

                    <el-form-item label="大便情况">
                        <el-checkbox-group v-model="formData.stool_condition" class="checkbox-group">
                            <el-checkbox-button v-for="item in stoolConditionOptions" :key="item.value" :label="item.value">
                                {{ item.name }}
                            </el-checkbox-button>
                        </el-checkbox-group>
                    </el-form-item>

                    <el-form-item label="腰肾情况">
                        <el-checkbox-group v-model="formData.kidney_condition" class="checkbox-group">
                            <el-checkbox-button v-for="item in kidneyConditionOptions" :key="item.value" :label="item.value">
                                {{ item.name }}
                            </el-checkbox-button>
                        </el-checkbox-group>
                    </el-form-item>

                    <el-form-item label="病情补充" prop="symptoms">
                        <el-input
                            v-model="formData.symptoms"
                            type="textarea"
                            :rows="3"
                            placeholder="请输入症状"
                        />
                    </el-form-item>
                </div>

                <!-- 既往史 -->
                <div class="form-section">
                    <div class="section-title">既往史</div>
                    
                    <el-form-item label="">
                        <el-checkbox-group v-model="formData.past_history" class="checkbox-group">
                            <el-checkbox-button
                                v-for="item in pastHistoryOptions"
                                :key="item.value"
                                :label="item.value"
                            >
                                {{ item.name }}
                            </el-checkbox-button>
                        </el-checkbox-group>
                    </el-form-item>
                </div>

                <!-- 其他病史 -->
                <div class="form-section">
                    <div class="section-title">其他病史</div>
                    
                    <el-form-item label="外伤史">
                        <el-radio-group v-model="formData.trauma_history">
                            <el-radio :label="1">有</el-radio>
                            <el-radio :label="0">无</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="手术史">
                        <el-radio-group v-model="formData.surgery_history">
                            <el-radio :label="1">有</el-radio>
                            <el-radio :label="0">无</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="过敏史">
                        <el-radio-group v-model="formData.allergy_history">
                            <el-radio :label="1">有</el-radio>
                            <el-radio :label="0">无</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="家族病史">
                        <el-radio-group v-model="formData.family_history">
                            <el-radio :label="1">有</el-radio>
                            <el-radio :label="0">无</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="妊娠哺乳史">
                        <el-radio-group v-model="formData.pregnancy_history">
                            <el-radio :label="1">有</el-radio>
                            <el-radio :label="0">无</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </div>

                <!-- 诊断详情 -->
                <div class="form-section">
                    <div class="section-title">诊断详情</div>
                    

                    <el-form-item label="舌苔" prop="tongue_coating">
                        <el-input v-model="formData.tongue_coating" placeholder="请输入舌苔情况" />
                    </el-form-item>

                    <el-form-item label="脉象" prop="pulse">
                        <el-input v-model="formData.pulse" placeholder="请输入脉象" />
                    </el-form-item>

                    <el-form-item label="治则" prop="treatment_principle">
                        <el-input
                            v-model="formData.treatment_principle"
                            type="textarea"
                            :rows="3"
                            placeholder="请输入治则"
                        />
                    </el-form-item>

                    <el-form-item label="处方" prop="prescription">
                        <el-input
                            v-model="formData.prescription"
                            type="textarea"
                            :rows="3"
                            placeholder="请输入处方"
                        />
                    </el-form-item>

                    <el-form-item label="医嘱" prop="doctor_advice">
                        <el-input
                            v-model="formData.doctor_advice"
                            type="textarea"
                            :rows="3"
                            placeholder="请输入医嘱"
                        />
                    </el-form-item>

                    <el-form-item label="备注" prop="remark">
                        <el-input
                            v-model="formData.remark"
                            type="textarea"
                            :rows="2"
                            placeholder="请输入备注"
                        />
                    </el-form-item>
                </div>
            </el-form>
        </div>

        <!-- 页面底部按钮 -->
        <div class="page-footer">
            <el-button @click="handleBack" class="btn-cancel">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="submitting" class="btn-submit">
                保存
            </el-button>
        </div>
    </div>
</template>
<script setup lang="ts">
import { tcmDiagnosisAdd, tcmDiagnosisEdit, tcmDiagnosisDetail, checkPhone, checkIdCard } from '@/api/tcm'
import { getDictData } from '@/api/app'
import feedback from '@/utils/feedback'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { ArrowLeft } from '@element-plus/icons-vue'

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

const formRef = ref()
const mode = ref('add')
const submitting = ref(false)
const pageTitle = computed(() => (mode.value === 'add' ? '新增诊单' : '编辑诊单'))

const formData = ref({
    id: '',
    patient_id: '',
    patient_name: '',
    id_card: '',
    phone: '',
    gender: 1,
    age: undefined as number | undefined,
    diagnosis_date: '',
    diagnosis_type: '',
    syndrome_type: '',
    diabetes_type: '',
    diabetes_discovery_year: '',
    local_hospital_diagnosis: [],
    local_hospital_name: '',
    marital_status: undefined as number | undefined,
    height: undefined as number | undefined,
    weight: undefined as number | undefined,
    region: '',
    systolic_pressure: undefined as number | undefined,
    diastolic_pressure: undefined as number | undefined,
    fasting_blood_sugar: '',
    appetite: '',
    water_intake: '',
    diet_condition: [],
    weight_change: '',
    body_feeling: [],
    sleep_condition: [],
    eye_condition: [],
    head_feeling: [],
    sweat_condition: [],
    skin_condition: [],
    urine_condition: [],
    stool_condition: [],
    kidney_condition: [],
    fatty_liver_degree: '',
    past_history: [],
    trauma_history: 0,
    surgery_history: 0,
    allergy_history: 0,
    family_history: 0,
    pregnancy_history: 0,
    symptoms: '',
    tongue_coating: '',
    pulse: '',
    treatment_principle: '',
    prescription: '',
    doctor_advice: '',
    remark: '',
    current_medications: '',
    status: 1
})

const validatePhone = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('请输入手机号'))
        return
    }
    if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('手机号格式不正确'))
        return
    }
    callback()
}

const validateIdCard = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback()
        return
    }
    if (!/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/.test(value)) {
        callback(new Error('身份证号格式不正确'))
        return
    }
    callback()
}

const formRules = {
    patient_name: [{ required: true, message: '请输入患者姓名', trigger: 'blur' }],
    id_card: [{ validator: validateIdCard, trigger: 'blur' }],
    phone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
    gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
    age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
    diagnosis_type: [{ required: true, message: '请选择诊断类型', trigger: 'change' }],
    syndrome_type: [{ required: true, message: '请选择证型', trigger: 'change' }],
    diabetes_type: [{ required: true, message: '请选择糖尿病期数', trigger: 'change' }],
    local_hospital_name: [{ required: true, message: '请输入当地就诊医院名称', trigger: 'blur' }],
    diabetes_discovery_year: [{ max: 50, message: '最多50个字符', trigger: 'blur' }]
}

const diagnosisTypeOptions = ref<any[]>([])
const syndromeTypeOptions = ref<any[]>([])
const diabetesTypeOptions = ref<any[]>([])
const pastHistoryOptions = ref<any[]>([])
const appetiteOptions = ref<any[]>([])
const waterIntakeOptions = ref<any[]>([])
const dietConditionOptions = ref<any[]>([])
const weightChangeOptions = ref<any[]>([])
const bodyFeelingOptions = ref<any[]>([])
const sleepConditionOptions = ref<any[]>([])
const eyeConditionOptions = ref<any[]>([])
const headFeelingOptions = ref<any[]>([])
const sweatConditionOptions = ref<any[]>([])
const skinConditionOptions = ref<any[]>([])
const urineConditionOptions = ref<any[]>([])
const stoolConditionOptions = ref<any[]>([])
const kidneyConditionOptions = ref<any[]>([])
const fattyLiverDegreeOptions = ref<any[]>([])

const getDictOptions = async () => {
    try {
        const [
            diagnosisType, syndromeType, diabetesType, pastHistory,
            appetite, waterIntake, dietCondition, weightChange,
            bodyFeeling, sleepCondition, eyeCondition, headFeeling,
            sweatCondition, skinCondition, urineCondition, stoolCondition,
            kidneyCondition, fattyLiverDegree
        ] = await Promise.all([
            getDictData({ type: 'diagnosis_type' }),
            getDictData({ type: 'syndrome_type' }),
            getDictData({ type: 'diabetes_type' }),
            getDictData({ type: 'past_history' }),
            getDictData({ type: 'appetite' }),
            getDictData({ type: 'water_intake' }),
            getDictData({ type: 'diet_condition' }),
            getDictData({ type: 'weight_change' }),
            getDictData({ type: 'body_feeling' }),
            getDictData({ type: 'sleep_condition' }),
            getDictData({ type: 'eye_condition' }),
            getDictData({ type: 'head_feeling' }),
            getDictData({ type: 'sweat_condition' }),
            getDictData({ type: 'skin_condition' }),
            getDictData({ type: 'urine_condition' }),
            getDictData({ type: 'stool_condition' }),
            getDictData({ type: 'kidney_condition' }),
            getDictData({ type: 'fatty_liver_degree' })
        ])
        
        diagnosisTypeOptions.value = diagnosisType?.diagnosis_type || []
        syndromeTypeOptions.value = syndromeType?.syndrome_type || []
        diabetesTypeOptions.value = diabetesType?.diabetes_type || []
        pastHistoryOptions.value = pastHistory?.past_history || []
        appetiteOptions.value = appetite?.appetite || []
        waterIntakeOptions.value = waterIntake?.water_intake || []
        dietConditionOptions.value = dietCondition?.diet_condition || []
        weightChangeOptions.value = weightChange?.weight_change || []
        bodyFeelingOptions.value = bodyFeeling?.body_feeling || []
        sleepConditionOptions.value = sleepCondition?.sleep_condition || []
        eyeConditionOptions.value = eyeCondition?.eye_condition || []
        headFeelingOptions.value = headFeeling?.head_feeling || []
        sweatConditionOptions.value = sweatCondition?.sweat_condition || []
        skinConditionOptions.value = skinCondition?.skin_condition || []
        urineConditionOptions.value = urineCondition?.urine_condition || []
        stoolConditionOptions.value = stoolCondition?.stool_condition || []
        kidneyConditionOptions.value = kidneyCondition?.kidney_condition || []
        fattyLiverDegreeOptions.value = fattyLiverDegree?.fatty_liver_degree || []
    } catch (error) {
        console.error('获取字典数据失败:', error)
    }
}

const handlePhoneBlur = async () => {
    if (!formData.value.phone || !/^1[3-9]\d{9}$/.test(formData.value.phone)) {
        return
    }
    
    try {
        const result = await checkPhone({
            phone: formData.value.phone,
            id: formData.value.id || ''
        })
        
        if (result.exists) {
            ElMessage.warning(result.message)
        }
    } catch (error) {
        console.error('检查手机号失败:', error)
    }
}

const handleIdCardBlur = async () => {
    if (!formData.value.id_card || !/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/.test(formData.value.id_card)) {
        return
    }
    
    try {
        const result = await checkIdCard({
            id_card: formData.value.id_card,
            id: formData.value.id || ''
        })
        
        if (result.exists) {
            ElMessage.warning(result.message)
        }
    } catch (error) {
        console.error('检查身份证号失败:', error)
    }
}

const handleSubmit = async () => {
    await formRef.value?.validate()
    
    submitting.value = true
    try {
        if (mode.value === 'add') {
            const result = await tcmDiagnosisAdd(formData.value)
            feedback.msgSuccess('新增成功')
            
            if (result && result.id) {
                mode.value = 'edit'
                formData.value.id = result.id
                
                try {
                    const detail = await tcmDiagnosisDetail({ id: result.id })
                    formData.value.patient_id = detail.patient_id
                } catch (error) {
                    console.error('获取详情失败:', error)
                }
                
                router.replace({ query: { id: result.id } })
            }
        } else {
            await tcmDiagnosisEdit(formData.value)
            feedback.msgSuccess('编辑成功')
        }
    } catch (error) {
        console.error('提交失败:', error)
    } finally {
        submitting.value = false
    }
}

const handleBack = () => {
    router.back()
}

onMounted(async () => {
    // 加载字典数据
    await getDictOptions()
    
    // 延迟隐藏侧边栏，确保DOM已完全加载
    setTimeout(() => {
        // 隐藏侧边栏
        const sidebar = document.querySelector('.el-aside')
        if (sidebar) {
            (sidebar as HTMLElement).style.display = 'none'
        }
        
        // 调整主容器宽度
        const main = document.querySelector('.el-main')
        if (main) {
            (main as HTMLElement).style.width = '100%'
            (main as HTMLElement).style.marginLeft = '0'
        }
        
        // 调整容器
        const container = document.querySelector('.el-container')
        if (container) {
            (container as HTMLElement).style.width = '100%'
        }
    }, 100)
    
    const id = route.query.id as string
    if (id) {
        mode.value = 'edit'
        const data = await tcmDiagnosisDetail({ id: Number(id) })
        formData.value = data
    }
})

onBeforeUnmount(() => {
    // 页面卸载时恢复侧边栏
    const sidebar = document.querySelector('.el-aside')
    if (sidebar) {
        (sidebar as HTMLElement).style.display = ''
    }
    
    const main = document.querySelector('.el-main')
    if (main) {
        (main as HTMLElement).style.width = ''
        (main as HTMLElement).style.marginLeft = ''
    }
    
    const container = document.querySelector('.el-container')
    if (container) {
        (container as HTMLElement).style.width = ''
    }
})
</script>
<style>
.p-4{
    padding: 0px;
}
</style>
<style lang="scss" scoped>
* {
    box-sizing: border-box;
}

html, body {
    margin: 0;
    padding: 0;
}

.diagnosis-page {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    width: 100%;
    background-color: #f5f7fa;
    margin: 0;
    padding: 0;
}

.page-header {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 16px;
    background-color: #fff;
    border-bottom: 1px solid #ebeef5;
    position: sticky;
    top: 0;
    z-index: 100;
    width: 100%;

    .back-btn {
        padding: 0;
        font-size: 16px;
        color: #606266;
        flex-shrink: 0;
        
        &:hover {
            color: #409eff;
        }
    }

    .page-title {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: #303133;
        flex: 1;
    }
}

.page-content {
    flex: 1;
    width: 100%;
    overflow-y: auto;
    padding: 16px;

    @media (min-width: 768px) {
        padding: 24px;
    }
}

.diagnosis-form {
    width: 100%;

    :deep(.el-form-item) {
        margin-bottom: 16px;
    }

    :deep(.el-form-item__label) {
        font-weight: 500;
        color: #606266;
    }

    :deep(.el-input),
    :deep(.el-input-number),
    :deep(.el-select),
    :deep(.el-date-editor) {
        width: 100%;
    }
}

.form-section {
    background-color: #fff;
    border-radius: 4px;
    padding: 16px;
    margin-bottom: 16px;
    width: 100%;

    .section-title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 16px;
        padding-bottom: 12px;
        border-bottom: 2px solid #409eff;
    }
}

.radio-group {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    width: 100%;

    :deep(.el-radio-button) {
        flex: 0 1 auto;
        min-width: 60px;
    }
}

.checkbox-group {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    width: 100%;

    :deep(.el-checkbox-button) {
        flex: 0 1 auto;
        min-width: 60px;
    }
}

.form-tips {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
    line-height: 1.5;
}

.page-footer {
    display: flex;
    gap: 12px;
    padding: 16px;
    background-color: #fff;
    border-top: 1px solid #ebeef5;
    position: sticky;
    bottom: 0;
    z-index: 100;
    width: 100%;

    @media (max-width: 767px) {
        flex-direction: column;
    }

    .btn-cancel,
    .btn-submit {
        flex: 1;
        height: 40px;
        font-size: 16px;
        font-weight: 500;

        @media (min-width: 768px) {
            flex: 0 1 auto;
            min-width: 120px;
        }
    }

    .btn-cancel {
        @media (max-width: 767px) {
            order: 2;
        }
    }

    .btn-submit {
        @media (max-width: 767px) {
            order: 1;
        }
    }
}

@media (max-width: 767px) {
    .page-header {
        padding: 12px;

        .page-title {
            font-size: 16px;
        }
    }

    .page-content {
        padding: 12px;
    }

    .form-section {
        padding: 12px;
        margin-bottom: 12px;

        .section-title {
            font-size: 14px;
            margin-bottom: 12px;
            padding-bottom: 8px;
        }
    }

    .radio-group,
    .checkbox-group {
        gap: 6px;

        :deep(.el-radio-button),
        :deep(.el-checkbox-button) {
            min-width: 50px;
            font-size: 12px;
        }
    }

    :deep(.el-form-item__label) {
        font-size: 14px;
    }

    :deep(.el-input__inner),
    :deep(.el-textarea__inner) {
        font-size: 14px;
    }
}

@media (prefers-color-scheme: dark) {
    .diagnosis-page {
        background-color: #1a1a1a;
    }

    .page-header,
    .page-footer,
    .form-section {
        background-color: #2a2a2a;
        border-color: #444;
    }

    .page-title,
    .section-title {
        color: #e0e0e0;
    }
}
</style>
