<template>
  <div class="app-container" v-loading="loading">
    <!-- 筛选区 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" class="filter-form">
      <el-form-item label="卫生机构" prop="orgName">
        <el-select
          v-model="queryParams.orgName"
          placeholder="请选择"
          clearable
          style="width: 200px"
          :popper-append-to-body="false"
        >
          <el-option
            v-for="item in tenantOptions"
            :key="item.id"
            :label="item.tenantName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="诊室名称" prop="roomName">
        <el-input
          v-model="queryParams.roomName"
          placeholder="请输入诊室名称"
          clearable
          style="width: 200px"
          maxlength="50"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格区 -->
    <el-table
      v-loading="loading"
      :data="clinicRoomList"
      border
      style="width: 100%"
      class="clinic-room-table"
    >
      <el-table-column prop="id" label="ID" width="180" align="center" />
      <el-table-column prop="roomName" label="诊室名称" width="160" align="center" show-overflow-tooltip />
      <el-table-column prop="department" label="科室名称" width="160" align="center" show-overflow-tooltip />
      <el-table-column prop="building" label="诊室楼号" width="120" align="center" show-overflow-tooltip />
      <el-table-column prop="floor" label="楼层" width="90" align="center" />
      <el-table-column prop="roomNo" label="房间号" width="120" align="center" />
      <el-table-column prop="isDisabled" label="停用" width="90" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.isDisabled ? 'danger' : 'success'">
            {{ scope.row.isDisabled ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="备注" min-width="100" align="center" show-overflow-tooltip />
      <el-table-column prop="void" label="作废" width="90" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.void ? 'danger' : 'success'">
            {{ scope.row.void ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" align="center" fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            link
            icon="EditPen"
            @click="handleEdit(scope.row)"
            v-hasPermi="['appoinment:clinicRoom:edit']"
          >编辑</el-button>
          <el-button
            type="info"
            link
            icon="View"
            @click="handleView(scope.row)"
            v-hasPermi="['appoinment:clinicRoom:query']"
          >查看</el-button>
          <el-button
            type="danger"
            link
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['appoinment:clinicRoom:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/编辑/查看弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        :disabled="dialogType === 'view'"
      >
        <el-form-item label="科室名称" prop="department">
        <el-select
          v-model="form.department"
          placeholder="请选择科室"
          style="width: 100%"
          filterable
          :disabled="dialogType === 'view'"
        >
          <el-option
            v-for="item in departmentOptions"
            :key="item.deptId || item.id"
            :label="item.deptName || item.name"
            :value="item.deptName || item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="卫生机构" prop="orgName">
        <el-select
          v-model="form.orgName"
          placeholder="请选择"
          style="width: 100%"
          :disabled="dialogType === 'view'"
        >
          <el-option
            v-for="item in tenantOptions"
            :key="item.id"
            :label="item.tenantName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="诊室名称" prop="roomName">
        <el-input
          v-model="form.roomName"
          placeholder="请输入诊室名称"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="诊室楼号" prop="building">
        <el-input
          v-model="form.building"
          placeholder="请输入诊室楼号"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item label="诊室楼层" prop="floor">
        <el-input
          v-model="form.floor"
          placeholder="请输入诊室楼层"
          maxlength="10"
        />
      </el-form-item>
      <el-form-item label="诊室房间号" prop="roomNo">
        <el-input
          v-model="form.roomNo"
          placeholder="请输入诊室房间号"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item label="停用状态" prop="isDisabled">
        <el-radio-group v-model="form.isDisabled">
          <el-radio :label="false">启用</el-radio>
          <el-radio :label="true">停用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input
          v-model="form.remarks"
          type="textarea"
          :rows="3"
          placeholder="请输入备注"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="作废" prop="void">
        <el-radio-group v-model="form.void">
          <el-radio :label="false">否</el-radio>
          <el-radio :label="true">是</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="dialogType !== 'view'" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ClinicRoom">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getClinicRoomList,
  getClinicRoomDetail,
  addClinicRoom,
  updateClinicRoom,
  deleteClinicRoom,
  getDepartmentList,
  getTenantList
} from '@/api/appoinmentmanage/clinicRoom'

const { proxy } = getCurrentInstance()

// 加载状态
const loading = ref(false)
// 表格数据
const clinicRoomList = ref([])
// 总数
const total = ref(0)
// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  roomName: null,
  orgName: null
})
// 科室选项
const departmentOptions = ref([])
// 租户选项
const tenantOptions = ref([])
// 弹窗相关
const dialogVisible = ref(false)
const dialogType = ref('') // add/edit/view
const dialogTitle = ref('')
const formRef = ref()
// 表单数据
const form = reactive({
  id: null,
  roomName: '',
  department: '',
  building: '',
  floor: '',
  roomNo: '',
  isDisabled: false,
  remarks: '',
  void: false,
  orgName: null
})
// 表单验证规则
const rules = {
  roomName: [
    { required: true, message: '诊室名称不能为空', trigger: 'blur' },
    { max: 20, message: '诊室名称长度不能超过20个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          return callback()
        }
        if (!form.orgName) {
          return callback()
        }
        // 检查当前租户下是否已存在相同的诊室名称
        const isExist = clinicRoomList.value.some(item => {
          return item.roomName === value && 
                 item.orgName === form.orgName &&
                 item.id !== form.id
        })
        if (isExist) {
          callback(new Error('诊室名称已存在'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  department: [
    { required: true, message: '科室名称不能为空', trigger: 'change' }
  ],
  orgName: [
    { required: true, message: '卫生机构不能为空', trigger: 'change' }
  ]
}

// 获取诊室列表
function getList() {
  loading.value = true
  getClinicRoomList(queryParams)
    .then(response => {
      if (response.code === 200) {
        clinicRoomList.value = response.data?.records || response.data || []
        total.value = response.data?.total || clinicRoomList.value.length || 0
      } else {
        ElMessage.error(response.msg || '获取诊室列表失败')
      }
    })
    .catch(error => {
      console.error('获取诊室列表失败:', error)
      ElMessage.error('获取诊室列表失败')
    })
    .finally(() => {
      loading.value = false
    })
}

// 查询按钮操作
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
function resetQuery() {
  proxy.resetForm('queryRef')
  queryParams.roomName = null
  queryParams.orgName = null
  handleQuery()
}

// 新增按钮操作
function handleAdd() {
  resetForm()
  dialogType.value = 'add'
  dialogTitle.value = '新增诊室'
  dialogVisible.value = true

  // 为新增模式修改诊室名称验证规则：检查全局唯一性
  rules.roomName = [
    { required: true, message: '诊室名称不能为空', trigger: 'blur' },
    { max: 20, message: '诊室名称长度不能超过20个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          return callback()
        }
        // 新增时检查所有诊室名称是否已存在
        const isExist = clinicRoomList.value.some(item => {
          return item.roomName === value
        })
        if (isExist) {
          callback(new Error('诊室名称已存在'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 编辑按钮操作
function handleEdit(row) {
  resetForm()
  const id = row.id
  getClinicRoomDetail(id)
    .then(response => {
      if (response.code === 200) {
        Object.assign(form, response.data || row)
        dialogType.value = 'edit'
        dialogTitle.value = '编辑诊室'
        dialogVisible.value = true

        // 为编辑模式修改诊室名称验证规则：检查同一租户下是否重复
        rules.roomName = [
          { required: true, message: '诊室名称不能为空', trigger: 'blur' },
          { max: 20, message: '诊室名称长度不能超过20个字符', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback()
              }
              if (!form.orgName) {
                return callback()
              }
              // 编辑时检查当前租户下是否已存在相同的诊室名称（排除当前记录）
              const isExist = clinicRoomList.value.some(item => {
                return item.roomName === value &&
                       item.orgName === form.orgName &&
                       item.id !== form.id
              })
              if (isExist) {
                callback(new Error('诊室名称已存在'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      } else {
        ElMessage.error(response.msg || '获取诊室详情失败')
      }
    })
    .catch(error => {
      console.error('获取诊室详情失败:', error)
      ElMessage.error('获取诊室详情失败')
    })
}

// 查看按钮操作
function handleView(row) {
  resetForm()
  const id = row.id
  getClinicRoomDetail(id)
    .then(response => {
      if (response.code === 200) {
        Object.assign(form, response.data || row)
        dialogType.value = 'view'
        dialogTitle.value = '查看诊室详情'
        dialogVisible.value = true

        // 查看模式不需要验证规则，因为表单是禁用的
      } else {
        ElMessage.error(response.msg || '获取诊室详情失败')
      }
    })
    .catch(error => {
      console.error('获取诊室详情失败:', error)
      ElMessage.error('获取诊室详情失败')
    })
}

// 删除按钮操作
function handleDelete(row) {
  const id = row.id || row.ids
  ElMessageBox.confirm('是否确认删除诊室ID为"' + id + '"的数据项？')
    .then(() => {
      return deleteClinicRoom(id)
    })
    .then(response => {
      if (response.code === 200) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(response.msg || '删除失败')
      }
    })
    .catch(() => {})
}

// 提交表单
function submitForm() {
  formRef.value.validate(valid => {
    if (valid) {
      if (dialogType.value === 'edit') {
        updateClinicRoom(form)
          .then(response => {
            if (response.code === 200) {
              ElMessage.success('修改成功')
              dialogVisible.value = false
              getList()
            } else {
              ElMessage.error(response.msg || '修改失败')
            }
          })
          .catch(error => {
            console.error('修改失败:', error)
            ElMessage.error('修改失败')
          })
      } else {
        addClinicRoom(form)
          .then(response => {
            if (response.code === 200) {
              ElMessage.success('新增成功')
              dialogVisible.value = false
              getList()
            } else {
              ElMessage.error(response.msg || '新增失败')
            }
          })
          .catch(error => {
            console.error('新增失败:', error)
            ElMessage.error('新增失败')
          })
      }
    }
  })
}

// 取消按钮
function cancel() {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
function resetForm() {
  form.id = null
  form.roomName = ''
  form.department = ''
  form.building = ''
  form.floor = ''
  form.roomNo = ''
  form.isDisabled = false
  form.remarks = ''
  form.void = false
  form.orgName = null
  proxy.resetForm('formRef')
}

// 获取科室列表
function getDepartmentOptions() {
  getDepartmentList()
    .then(response => {
      if (response.code === 200) {
        // 处理不同的响应格式
        if (Array.isArray(response.data)) {
          departmentOptions.value = response.data
        } else if (response.data?.data && Array.isArray(response.data.data)) {
          departmentOptions.value = response.data.data
        } else if (response.data?.records && Array.isArray(response.data.records)) {
          departmentOptions.value = response.data.records
        } else {
          departmentOptions.value = []
        }
      } else {
        console.warn('获取科室列表失败:', response.msg)
      }
    })
    .catch(error => {
      console.error('获取科室列表失败:', error)
    })
}

// 获取租户列表
function getTenantOptions() {
  getTenantList()
    .then(response => {
      if (response.code === 200) {
        // 处理不同的响应格式
        if (response.data?.records && Array.isArray(response.data.records)) {
          tenantOptions.value = response.data.records
        } else if (Array.isArray(response.data)) {
          tenantOptions.value = response.data
        } else {
          tenantOptions.value = []
        }
      } else {
        console.warn('获取租户列表失败:', response.msg)
      }
    })
    .catch(error => {
      console.error('获取租户列表失败:', error)
    })
}

// 页面加载时初始化
onMounted(() => {
  getDepartmentOptions()
  getTenantOptions()
  getList()
})
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.filter-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.clinic-room-table {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

:deep(.el-table) {
  .el-table__header-wrapper th {
    background-color: #fafafa;
    font-weight: 500;
  }
}

:deep(.el-button--link) {
  padding: 0;
  margin: 0 5px;
}

// 响应式布局
@media (max-width: 768px) {
  .filter-form {
    :deep(.el-form-item) {
      display: block;
      margin-bottom: 16px;
    }
    
    :deep(.el-form-item__content) {
      width: 100%;
    }
  }
  
  .clinic-room-table {
    overflow-x: auto;
  }
}
</style>

