<template>
  <div class="app-container">
    <div class="config-header">
      <el-button type="primary" @click="handleDefault">默认(M)</el-button>
      <el-button type="success" @click="handleSave">保存(S)</el-button>
      <el-button type="danger" @click="handleClose">关闭(X)</el-button>
    </div>
    
    <el-tabs v-model="activeTab" class="config-tabs">
      <el-tab-pane label="划价收费1" name="tab1">
        <div class="tab-content">划价收费1相关配置</div>
      </el-tab-pane>
      
      <el-tab-pane label="划价收费2" name="tab2">
        <div class="tab-content">划价收费2相关配置</div>
      </el-tab-pane>
      
      <el-tab-pane label="挂号处理" name="tab3">
        <el-form ref="formRef" :model="formData" label-width="150px" class="config-form compact-form">
          <!-- 第一行 -->
          <div class="form-row">
            <el-form-item label="病历本费用（元）" prop="medicalRecordFee">
              <el-input-number v-model="formData.medicalRecordFee" style="width: 150px" :controls-position="'right'" :step="1" :min="0" />
            </el-form-item>
            <el-form-item label="" prop="medicalRecordFlag" checkbox-label>
              <template #label>
                <div class="checkbox-label-container">
                  <el-checkbox v-model="formData.medicalRecordFlag" style="margin-right: 8px;" />
                  <span>病历费入账标志</span>
                </div>
              </template>
            </el-form-item>
          </div>
          
          <!-- 第二行 -->
          <div class="form-row">
            <el-form-item label="就诊卡费（元）" prop="patientCardFee">
              <el-input-number v-model="formData.patientCardFee" style="width: 150px" :controls-position="'right'" :step="1" :min="0" />
            </el-form-item>
            <el-form-item label="" prop="isNightShift" checkbox-label>
              <template #label>
                <div class="checkbox-label-container">
                  <el-checkbox v-model="formData.isNightShift" style="margin-right: 8px;" />
                  <span>是否启用晚班</span>
                </div>
              </template>
            </el-form-item>
          </div>
          
          <!-- 第三行 -->
          <div class="form-row">
            <el-form-item label="" prop="patientCardFlag" checkbox-label>
              <template #label>
                <div class="checkbox-label-container">
                  <el-checkbox v-model="formData.patientCardFlag" style="margin-right: 8px;" />
                  <span>就诊卡记账标志</span>
                </div>
              </template>
            </el-form-item>
            <el-form-item label="上午接诊起始时间" prop="morningStartTime">
              <el-input v-model="formData.morningStartTime" style="width: 150px" />
            </el-form-item>
          </div>
          
          <!-- 第四行 -->
          <div class="form-row">
            <el-form-item label="" prop="autoGenerateOutpatientNo" checkbox-label>
              <template #label>
                <div class="checkbox-label-container">
                  <el-checkbox v-model="formData.autoGenerateOutpatientNo" style="margin-right: 8px;" />
                  <span>自动产生门诊号</span>
                </div>
              </template>
            </el-form-item>
            <el-form-item label="" prop="allowModifyOutpatientNo" checkbox-label>
              <template #label>
                <div class="checkbox-label-container">
                  <el-checkbox v-model="formData.allowModifyOutpatientNo" style="margin-right: 8px;" />
                  <span>建档时是否允许修改门诊号</span>
                </div>
              </template>
            </el-form-item>
          </div>
          
          <!-- 第五行 -->
          <div class="form-row">
            <el-form-item label="下午起始时间" prop="afternoonStartTime">
              <el-input v-model="formData.afternoonStartTime" style="width: 150px" />
            </el-form-item>
            <el-form-item label="晚上起始时间" prop="eveningStartTime" v-if="formData.isNightShift">
              <el-input v-model="formData.eveningStartTime" style="width: 150px" />
            </el-form-item>
          </div>
          
          <!-- 第六行 -->
          <div class="form-row">
            <el-form-item label="挂号有效期（天）" prop="registrationValidity">
              <el-input-number v-model="formData.registrationValidity" style="width: 150px" :controls-position="'right'" :step="1" :min="0" />
            </el-form-item>
            <el-form-item label="挂号单据模式" prop="registrationDocumentMode">
              <el-select v-model="formData.registrationDocumentMode" style="width: 150px">
                <el-option label="使用发票" value="使用发票" />
                <el-option label="普通单据" value="其他模式" />
              </el-select>
            </el-form-item>
          </div>
          
          <!-- 第七行 -->
          <div class="form-row">
            <el-form-item label="" prop="exemptFlag" checkbox-label>
              <template #label>
                <div class="checkbox-label-container">
                  <el-checkbox v-model="formData.exemptFlag" style="margin-right: 8px;" />
                  <span>减免标志</span>
                </div>
              </template>
            </el-form-item>
            <el-form-item label="" prop="consultationFlag" checkbox-label>
              <template #label>
                <div class="checkbox-label-container">
                  <el-checkbox v-model="formData.consultationFlag" style="margin-right: 8px;" />
                  <span>义诊标志</span>
                </div>
              </template>
            </el-form-item>
            <el-form-item label="" prop="enableHolidayFeeFloat" checkbox-label>
              <template #label>
                <div class="checkbox-label-container">
                  <el-checkbox v-model="formData.enableHolidayFeeFloat" style="margin-right: 8px;" />
                  <span>启用法定节假日挂号费浮动</span>
                </div>
              </template>
            </el-form-item>
          </div>
          
          <!-- 第八行 -->
          <div class="form-row">
            <el-form-item label="监护人规定年龄（岁）" prop="guardianAge">
              <el-input-number v-model="formData.guardianAge" style="width: 150px" :controls-position="'right'" :step="1" :min="0" />
            </el-form-item>
            <el-form-item label="" prop="enableDoubleScreen" checkbox-label>
              <template #label>
                <div class="checkbox-label-container">
                  <el-checkbox v-model="formData.enableDoubleScreen" style="margin-right: 8px;" />
                  <span>门诊挂号启用双屏</span>
                </div>
              </template>
            </el-form-item>
          </div>
          
          <!-- 第九行 -->
          <div class="form-row">
            <el-form-item label="" prop="optionalRegistrationType" checkbox-label>
              <template #label>
                <div class="checkbox-label-container">
                  <el-checkbox v-model="formData.optionalRegistrationType" style="margin-right: 8px;" />
                  <span>挂号类型可选择</span>
                </div>
              </template>
            </el-form-item>
          </div>
        </el-form>
      </el-tab-pane>
      
      <el-tab-pane label="挂号预约" name="tab4">
        <div class="tab-content">挂号预约相关配置</div>
      </el-tab-pane>
      
      <el-tab-pane label="打印设置" name="tab5">
        <el-checkbox v-model="formData.isPrint">是否打印挂号单</el-checkbox>
      </el-tab-pane>
      
      <el-tab-pane label="其他选项" name="tab6">
        <div class="tab-content">其他选项相关配置</div>
      </el-tab-pane>
      
      <el-tab-pane label="病人账户" name="tab7">
        <div class="tab-content">病人账户相关配置</div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { listConfig, getConfigKey, addConfig, updateConfig } from '@/api/system/config';

const router = useRouter();
const formRef = ref(null);
const activeTab = ref('tab1');

// 表单数据
const formData = reactive({
  medicalRecordFee: '1',
  patientCardFee: '1',
  medicalRecordFlag: true,
  patientCardFlag: false,
  autoGenerateOutpatientNo: true,
  allowModifyOutpatientNo: false,
  enableHolidayFeeFloat: true,
  enableDoubleScreen: true,
  isNightShift: false,
  exemptFlag: false,
  consultationFlag: false,
  optionalRegistrationType: false,
  morningStartTime: '08:00',
  afternoonStartTime: '13:00',
  eveningStartTime: '22:00',
  registrationValidity: '5',
  registrationDocumentMode: '使用发票',
  guardianAge: '16',
  isPrint: false,
});

// 加载配置数据
const loadConfigData = async (showSuccessMessage = true) => {
  try {
    // 调用系统配置API获取数据，不设置configType过滤条件以获取所有配置
    const response = await listConfig({ pageSize: 1000 });
    
    // 处理响应数据，兼容不同的返回格式
    let configs = [];
    if (response && response.data) {
      if (Array.isArray(response.data)) {
        configs = response.data;
      } else if (response.data.rows && Array.isArray(response.data.rows)) {
        configs = response.data.rows;
      } else {
        console.error('返回数据格式不符合预期:', response);
      }
    } else if (response && response.rows && Array.isArray(response.rows)) {
      configs = response.rows;
    } else {
      console.error('API返回空响应:', response);
    }
    
    console.log('loadConfigData - 获取到的配置列表:', configs);
    console.log('loadConfigData - 配置总数:', configs.length);
    
    // 将配置数据映射到表单
    if (configs && configs.length > 0) {
      configs.forEach(config => {
        const { configKey, configValue } = config;
        
        // 处理布尔类型字段
        if (configKey in formData) {
          if (typeof formData[configKey] === 'boolean') {
            formData[configKey] = configValue === '1';
          } else {
            formData[configKey] = configValue;
          }
        }
      });
    }
    
    if (showSuccessMessage) {
      ElMessage.success('配置数据加载成功');
    }
  } catch (error) {
    console.error('加载配置数据失败:', error);
    ElMessage.warning('无法加载配置数据，使用默认值');
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadConfigData();
});

// 默认按钮点击事件
const handleDefault = () => {
  // 重置为默认值
  Object.assign(formData, {
    medicalRecordFee: '1',
    patientCardFee: '1',
    medicalRecordFlag: true,
    patientCardFlag: false,
    autoGenerateOutpatientNo: true,
    allowModifyOutpatientNo: false,
    enableHolidayFeeFloat: true,
    enableDoubleScreen: true,
    isNightShift: false,
    exemptFlag: false,
    consultationFlag: false,
    optionalRegistrationType: false,
    morningStartTime: '08:00',
    afternoonStartTime: '13:00',
    eveningStartTime: '22:00',
    registrationValidity: '5',
    registrationDocumentMode: '使用发票',
    guardianAge: '16',
    isPrint: false,
  });
  ElMessage.success('已恢复默认值');
};

// 保存按钮点击事件
const handleSave = async () => {
  try {
    // 这里可以添加表单验证逻辑
    if (formRef.value) {
      await formRef.value.validate();
    }
    
    // 将表单数据转换为系统配置格式，并添加必要的默认值
    const configData = [
      { configKey: 'medicalRecordFee', configValue: formData.medicalRecordFee, configName: '病历本费用', configType: 'Y' },
      { configKey: 'patientCardFee', configValue: formData.patientCardFee, configName: '就诊卡费', configType: 'Y' },
      { configKey: 'medicalRecordFlag', configValue: formData.medicalRecordFlag ? '1' : '0', configName: '病历费入账标志', configType: 'Y' },
      { configKey: 'isNightShift', configValue: formData.isNightShift ? '1' : '0', configName: '是否启用晚班', configType: 'Y' },
      { configKey: 'patientCardFlag', configValue: formData.patientCardFlag ? '1' : '0', configName: '就诊卡记账标志', configType: 'Y' },
      { configKey: 'morningStartTime', configValue: formData.morningStartTime, configName: '上午接诊起始时间', configType: 'Y' },
      { configKey: 'autoGenerateOutpatientNo', configValue: formData.autoGenerateOutpatientNo ? '1' : '0', configName: '自动产生门诊号', configType: 'Y' },
      { configKey: 'allowModifyOutpatientNo', configValue: formData.allowModifyOutpatientNo ? '1' : '0', configName: '建档时是否允许修改门诊号', configType: 'Y' },
      { configKey: 'afternoonStartTime', configValue: formData.afternoonStartTime, configName: '下午起始时间', configType: 'Y' },
      { configKey: 'eveningStartTime', configValue: formData.eveningStartTime, configName: '晚上起始时间', configType: 'Y' },
      { configKey: 'registrationValidity', configValue: formData.registrationValidity, configName: '挂号有效期（天）', configType: 'Y' },
      { configKey: 'registrationDocumentMode', configValue: formData.registrationDocumentMode, configName: '挂号单据模式', configType: 'Y' },
      { configKey: 'exemptFlag', configValue: formData.exemptFlag ? '1' : '0', configName: '减免标志', configType: 'Y' },
      { configKey: 'consultationFlag', configValue: formData.consultationFlag ? '1' : '0', configName: '义诊标志', configType: 'Y' },
      { configKey: 'enableHolidayFeeFloat', configValue: formData.enableHolidayFeeFloat ? '1' : '0', configName: '启用法定节假日挂号费浮动', configType: 'Y' },
      { configKey: 'guardianAge', configValue: formData.guardianAge, configName: '监护人规定年龄（岁）', configType: 'Y' },
      { configKey: 'enableDoubleScreen', configValue: formData.enableDoubleScreen ? '1' : '0', configName: '门诊挂号启用双屏', configType: 'Y' },
      { configKey: 'optionalRegistrationType', configValue: formData.optionalRegistrationType ? '1' : '0', configName: '挂号类型可选择', configType: 'Y' },
      { configKey: 'isPrint', configValue: formData.isPrint ? '1' : '0', configName: '是否打印挂号单', configType: 'Y' },
    ];
    
    let successCount = 0;
    let failedParams = [];
    
    try {
      // 先获取所有配置，避免重复调用API
      const allConfigsResponse = await listConfig({ pageSize: 1000 });
      console.log('handleSave - listConfig返回完整结果:', JSON.stringify(allConfigsResponse));
      
      // 检查返回结果结构
      let allConfigs = [];
      if (allConfigsResponse.code === 200) {
        if (allConfigsResponse.data && Array.isArray(allConfigsResponse.data)) {
          allConfigs = allConfigsResponse.data;
        } else if (allConfigsResponse.data && allConfigsResponse.data.rows) {
          allConfigs = allConfigsResponse.data.rows;
        } else if (Array.isArray(allConfigsResponse.rows)) {
          allConfigs = allConfigsResponse.rows;
        } else if (Array.isArray(allConfigsResponse)) {
          allConfigs = allConfigsResponse;
        }
      }
      
      console.log('handleSave - 最终获取到的所有配置:', allConfigs);
      console.log('handleSave - 配置总数:', allConfigs.length);
      
      // 构建配置项映射表，方便快速查找
      const configMap = new Map();
      allConfigs.forEach(config => {
        configMap.set(config.configKey, config);
        console.log('handleSave - 添加到映射表:', config.configKey);
      });
      
      // 调用系统配置API保存每个参数
      for (const config of configData) {
        try {
          const existingConfig = configMap.get(config.configKey);
          
          console.log(`处理参数: ${config.configName} (${config.configKey})`);
          console.log(`现有配置:`, existingConfig);
          console.log(`要保存的值:`, config.configValue);
          
          if (existingConfig && existingConfig.configId) {
            // 如果存在则更新，保留原有数据的configId和创建时间
            console.log(`更新参数 ${config.configKey}，使用configId: ${existingConfig.configId}`);
            const updateResult = await updateConfig({ 
              ...config, 
              configId: existingConfig.configId,
              createTime: existingConfig.createTime, 
              remark: existingConfig.remark || '收费系统配置参数',
              configType: existingConfig.configType || 'N'
            });
            console.log(`更新结果:`, updateResult);
          } else {
            // 如果不存在则新增，添加默认备注
            console.log(`新增参数 ${config.configKey}`);
            const addResult = await addConfig({ 
              ...config, 
              remark: '收费系统配置参数',
              configType: 'N'
            });
            console.log(`新增结果:`, addResult);
          }
          successCount++;
        } catch (paramError) {
          console.error(`保存参数 ${config.configName} (${config.configKey}) 失败:`, paramError);
          console.error(`错误详情:`, paramError.response || paramError);
          failedParams.push(config.configName);
          // 继续处理下一个参数，不中断整体流程
        }
      }
    } catch (error) {
      console.error('获取配置列表失败:', error);
      ElMessage.error('获取配置列表失败，无法保存参数');
      return;
    }
    
    // 根据保存结果显示相应消息
    if (failedParams.length === 0) {
      ElMessage.success(`保存成功`);
      // 保存成功后重新加载数据，确保页面显示最新配置
      loadConfigData(false); // 不显示加载成功消息
    } else if (successCount > 0) {
      ElMessage.warning(`${successCount} 个参数保存成功，但以下 ${failedParams.length} 个参数保存失败: ${failedParams.join(', ')}`);
      // 部分成功也重新加载数据
      loadConfigData(false); // 不显示加载成功消息
    } else {
      ElMessage.error(`所有参数保存失败，请检查系统配置`);
    }
  } catch (error) {
    console.error('保存过程中发生错误:', error);
    ElMessage.error('保存操作异常，请重试');
  }
};

// 关闭按钮点击事件
const handleClose = () => {
  router.back();
};
</script>

<style scoped>
.app-container {
  padding: 5px;
}

.config-header {
  margin-bottom: 5px;
}

.config-header .el-button {
  margin-right: 10px;
}

.config-tabs {
  margin-top: 0;
}

.config-form {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: nowrap; /* 禁止行内元素换行 */
  overflow-x: hidden; /* 防止溢出 */
}

.config-form .el-form-item {
  margin-bottom: 0;
  margin-right: 60px; /* 增加间距 */
  min-width: 350px; /* 增加最小宽度 */
  display: flex;
  align-items: center;
  flex-shrink: 0; /* 禁止压缩 */
}

/* 紧凑表单样式 */
.compact-form {
  label-width: 150px !important;
}

.compact-form .el-form-item {
  margin-bottom: 10px;
}

/* 所有表单标签的统一样式 */
.config-form .el-form-item__label {
  font-weight: 500;
  width: 220px !important; /* 足够宽的标签宽度 */
  text-align: right;
  padding-right: 15px;
  white-space: nowrap !important; /* 强制不换行 */
  overflow: visible !important; /* 允许内容溢出（确保不截断） */
  text-overflow: clip !important; /* 不显示省略号 */
  flex-shrink: 0 !important; /* 禁止压缩 */
  font-size: 14px !important; /* 统一字体大小 */
  line-height: 32px !important; /* 统一行高 */
  height: 32px !important; /* 统一高度 */
  margin: 0 !important; /* 清除默认边距 */
  padding: 0 15px 0 0 !important; /* 统一内边距 */
}

/* 复选框标签样式 */
.compact-form .el-form-item[checkbox-label] .el-form-item__label {
  padding-right: 10px;
  width: 150px !important;
  text-align: right;
}

.compact-form .el-form-item[checkbox-label] .el-form-item__content {
  margin-left: 0 !important;
}

/* 自定义复选框标签容器 */
.checkbox-label-container {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  height: 100%;
}

.checkbox-label-container span {
  font-size: 14px;
  white-space: nowrap;
}

/* 空标签的样式，用于对齐 */
.config-form .el-form-item__label:empty {
  width: 18px !important;
  padding-right: 5px !important;
}

.config-form .el-form-item--medium .el-form-item__content {
  line-height: 32px;
  flex-shrink: 0;
  height: 32px;
}

.config-form .el-checkbox {
  margin-left: 0;
  font-size: 14px;
}

/* 确保输入框与标签对齐 */
.config-form .el-input {
  height: 32px;
  font-size: 14px;
}

.config-form .el-input__wrapper {
  height: 32px;
}

.tab-content {
  padding: 10px;
  color: #606266;
  text-align: center;
  line-height: 60px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>