<template>
  <div class="appoinmentmanage-container">
    <div class="appoinmentmanage-header">
      <h2 class="appoinmentmanage-title">科室名称管理</h2>
    </div>
    
    <div class="appoinmentmanage-content">
      <!-- 查询条件 -->
      <div class="query-condition">
        <el-select v-model="queryParams.orgName" placeholder="全部机构" class="query-select">
          <el-option label="全部机构" value=""></el-option>
          <el-option label="中联医院" value="中联医院"></el-option>
        </el-select>
        
        <el-select v-model="queryParams.deptName" placeholder="全部科室" class="query-select">
          <el-option label="全部科室" value=""></el-option>
          <el-option v-for="dept in departmentOptions" :key="dept.id || dept.code" :label="dept.name || dept.deptName" :value="dept.name || dept.deptName"></el-option>
        </el-select>
        
        <el-button type="primary" @click="handleQuery" class="query-button">查询</el-button>
        <el-button @click="handleReset" class="reset-button">重置</el-button>
        <el-button type="success" @click="handleAppointmentSetting" class="appointment-setting-button">预约设置</el-button>
      </div>
      
      <!-- 科室列表 -->
      <div class="dept-table-container">
        <el-table :data="deptList" border style="width: 100%" class="centered-table">
          <!-- 添加空状态提示 -->
          <template #empty>
            <div style="padding: 20px 0;">
              <el-icon><DocumentRemove /></el-icon>
              <span style="margin-left: 8px;">暂无数据</span>
            </div>
          </template>
          
          <!-- 适配常见的后端字段名 -->
          <el-table-column prop="id" label="ID" width="150"></el-table-column>
          <el-table-column prop="orgName" label="卫生机构" width="350">
            <template #default="scope">
              {{ scope.row.orgName || scope.row.organizationName || scope.row.org || '' }}
            </template>
          </el-table-column>
          <el-table-column prop="deptName" label="科室名称" width="350">
            <template #default="scope">
              {{ scope.row.deptName || scope.row.departmentName || scope.row.name || '' }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" width="400">
            <template #default="scope">
              {{ scope.row.remark || scope.row.description || scope.row.note || '' }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="作废标志">
            <template #default="scope">
              <el-tag :type="(scope.row.status === 1 || scope.row.status === true || scope.row.status === '1') ? 'success' : 'danger'">
                {{ (scope.row.status === 1 || scope.row.status === true || scope.row.status === '1') ? '有效' : '无效' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="350" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">
                <el-icon><EditPen /></el-icon>
              </el-button>
              <el-button type="info" size="small" @click="handleView(scope.row)">
                <el-icon><View /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
  
  <!-- 预约设置弹窗 -->
  <el-dialog
    v-model="appointmentSettingDialog"
    title="预约设置"
    width="400px"
    center
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="50%"
    :before-close="handleAppointmentSettingCancel"
  >
    <el-form label-position="top" :model="appointmentSettingForm">
      <el-form-item label="取消预约时间类型">
        <el-select v-model="appointmentSettingForm.cancelAppointmentType" placeholder="请选择" style="width: 200px">
          <el-option label="年" value="年"></el-option>
          <el-option label="月" value="月"></el-option>
          <el-option label="日" value="日"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="取消预约次数">
        <el-input-number
          v-model="appointmentSettingForm.cancelAppointmentCount"
          :min="0"
          :step="1"
          placeholder="请输入"
        ></el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleAppointmentSettingCancel">取消</el-button>
        <el-button type="primary" @click="handleAppointmentSettingConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="AppoinmentManage">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElDialog, ElSelect, ElOption, ElInput, ElForm, ElFormItem } from 'element-plus'
import { EditPen, View, DocumentRemove } from '@element-plus/icons-vue'
import { listDept, searchDept } from '@/api/appoinmentmanage/dept'
import { getLocationTree } from '@/views/charge/outpatientregistration/components/outpatientregistration'

// 查询参数
const queryParams = ref({
  orgName: '',
  deptName: ''
})

// 科室选项列表
const departmentOptions = ref([])

// 科室列表
const deptList = ref([])

// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 预约设置弹窗
const appointmentSettingDialog = ref(false)

// 预约设置表单数据
const appointmentSettingForm = ref({
  cancelAppointmentType: '年',
  cancelAppointmentCount: 0
})

// 获取科室列表（通用方法）
const fetchDeptList = async (apiFunction) => {
  try {
    const res = await apiFunction({
      ...queryParams.value,
      pageNo: pagination.value.currentPage,
      pageSize: pagination.value.pageSize
    })
    console.log('后端返回的数据:', res)
    if (res.code === 200) {
      // 适配不同的后端数据结构
      let dataList = []
      let totalCount = 0
      
      // 首先检查是否存在嵌套的data结构
      let actualData = res.data
      // 处理嵌套data结构（用户提供的格式）
      if (actualData && actualData.code === 200 && actualData.msg) {
        actualData = actualData.data
      }
      
      // 检查是否是标准分页结构 (Spring Boot Page)
      if (actualData && actualData.content) {
        // Spring Boot Page结构使用content字段
        dataList = actualData.content
        totalCount = actualData.totalElements || 0
      } else if (actualData && actualData.records) {
        // 自定义分页结构使用records字段
        dataList = actualData.records
        totalCount = actualData.total || 0
      } else if (Array.isArray(actualData)) {
        // 直接返回数组
        dataList = actualData
        totalCount = actualData.length
      } else if (actualData && actualData.list) {
        // 其他可能的列表字段名
        dataList = actualData.list
        totalCount = actualData.total || actualData.list.length
      } else {
        // 默认处理
        dataList = actualData || []
        totalCount = Array.isArray(actualData) ? actualData.length : 0
      }
      
      deptList.value = dataList
      pagination.value.total = totalCount
      
      console.log('处理后的数据列表:', deptList.value)
      console.log('总记录数:', pagination.value.total)
    } else {
      ElMessage.error(res.msg || '获取科室列表失败')
    }
  } catch (error) {
    console.error('获取科室列表失败:', error)
    ElMessage.error('获取科室列表失败')
  }
}

// 获取科室列表（默认列表）
const getDeptList = async () => {
  await fetchDeptList(listDept)
}

// 查询
const handleQuery = () => {
  pagination.value.currentPage = 1
  fetchDeptList(searchDept)
}

// 重置
const handleReset = () => {
  queryParams.value = {
    orgName: '',
    deptName: ''
  }
  pagination.value.currentPage = 1
  getDeptList()
}

// 预约设置弹窗显示
const handleAppointmentSetting = () => {
  appointmentSettingDialog.value = true
}

// 预约设置确定
const handleAppointmentSettingConfirm = () => {
  // 这里可以添加表单验证和提交逻辑
  console.log('预约设置提交:', appointmentSettingForm.value)
  ElMessage.success('预约设置保存成功')
  appointmentSettingDialog.value = false
}

// 预约设置取消
const handleAppointmentSettingCancel = () => {
  appointmentSettingDialog.value = false
}

// 路由和导航
const router = useRouter()

// 编辑
const handleEdit = (row) => {
  // 导航到医生排班页面，传递科室ID和编辑模式
  router.push({
    path: `/appoinmentmanage/doctorschedule/${row.id}`,
    query: { mode: 'edit' }
  })
}

// 查看
const handleView = (row) => {
  // 导航到医生排班页面，传递科室ID和查看模式
  router.push({
    path: `/appoinmentmanage/doctorschedule/${row.id}`,
    query: { mode: 'view' }
  })
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  getDeptList()
}

// 当前页码变化
const handleCurrentChange = (current) => {
  pagination.value.currentPage = current
  getDeptList()
}

// 获取门诊挂号的就诊科室数据
const getDepartmentOptions = async () => {
  try {
    const response = await getLocationTree()
    if (response.code === 200) {
      // 适配不同的后端数据结构
      let actualData = response.data
      // 处理嵌套data结构
      if (actualData && actualData.code === 200 && actualData.msg) {
        actualData = actualData.data
      }
      
      // 确保数据是数组格式
      if (Array.isArray(actualData)) {
        departmentOptions.value = actualData
      } else if (actualData && actualData.records) {
        departmentOptions.value = actualData.records
      } else if (actualData && actualData.content) {
        departmentOptions.value = actualData.content
      } else if (actualData && actualData.list) {
        departmentOptions.value = actualData.list
      } else {
        departmentOptions.value = []
      }
    } else {
      console.error('获取科室列表失败:', response.msg)
      departmentOptions.value = []
    }
  } catch (error) {
    console.error('获取科室列表失败:', error)
    departmentOptions.value = []
  }
}

// 页面加载时获取科室列表
onMounted(() => {
  getDeptList()
  getDepartmentOptions()
})
</script>

<style scoped lang="scss">
.appoinmentmanage-container {
  width: 100%;
  height: 100%;
  padding: 20px;
  background-color: #f5f7fa;
}

.appoinmentmanage-header {
  margin-bottom: 20px;
}

.appoinmentmanage-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.appoinmentmanage-content {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.query-condition {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 16px;
}

.query-select {
  width: 200px;
}

.query-button, .reset-button, .appointment-setting-button {
  min-width: 100px;
}

.dept-table-container {
  width: 100%;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 表格居中样式 */
.centered-table {
  :deep(.el-table__header-wrapper th.el-table__cell),
  :deep(.el-table__body-wrapper td.el-table__cell) {
    text-align: center;
  }
}
</style>

<style scoped>
/* 确保弹窗内容区占满宽度 */
:deep(.el-dialog__body) {
  padding: 20px;
}
</style>