<template>
  <div class="app-container">
    <div class="search-con">
      <div class="title">查询条件</div>
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="成员" prop="personId">
          <el-select v-model="queryParams.personId" placeholder="请选择成员" clearable filterable>
            <el-option v-for="item in memberList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="疾病名称" prop="diseaseName">
          <el-input v-model="queryParams.diseaseName" placeholder="请输入疾病名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="diseaseStatus">
          <el-select v-model="queryParams.diseaseStatus" placeholder="请选择状态" clearable>
            <el-option v-for="dict in disease_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用" prop="isActive">
          <el-select v-model="queryParams.isActive" placeholder="请选择" clearable>
            <el-option v-for="dict in is_active" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="search-btn-con">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button type="info" icon="Refresh" @click="resetQuery">重置</el-button>
      </div>
    </div>
    <div class="main-con">
      <div class="title-con">
        <div class="title">慢性疾病档案</div>
        <div class="operate-btn-con">
          <el-button @click="handleAdd" icon="Plus" v-hasPermi="['health:chronicDisease:add']">新增</el-button>
          <el-button :disabled="multiple" icon="Delete" @click="handleDelete" v-hasPermi="['health:chronicDisease:remove']">删除</el-button>
        </div>
      </div>
      <div class="content-con" v-loading="loading" height="calc(100% - 0.65rem)">
        <el-table v-loading="loading" :data="chronicDiseaseList" @selection-change="handleSelectionChange" height="calc(100% - 0.65rem)">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" label="序号" :index="indexMethod" width="50"></el-table-column>
          <el-table-column label="成员" align="center" prop="personName" width="100" />
          <el-table-column label="疾病名称" align="center" prop="diseaseName" min-width="120" show-overflow-tooltip />
          <el-table-column label="疾病编码" align="center" prop="diseaseCode" width="100" />
          <el-table-column label="确诊日期" align="center" prop="diagnosisDate" width="110">
            <template #default="scope">
              <span>{{ parseTime(scope.row.diagnosisDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="diseaseStatus" width="80">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.diseaseStatus)">
                {{ getStatusLabel(scope.row.diseaseStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="主治医生" align="center" prop="mainDoctor" width="100" />
          <el-table-column label="就诊医院" align="center" prop="hospital" min-width="120" show-overflow-tooltip />
          <el-table-column label="科室" align="center" prop="department" width="100" />
          <el-table-column label="是否启用" align="center" prop="isActive" width="80">
            <template #default="scope">
              <el-switch
                v-model="scope.row.isActive"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(scope.row)"
                v-hasPermi="['health:chronicDisease:edit']"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
            <template v-slot="scope">
              <div class="ctrl-btn d-flex">
                <el-tooltip v-for="item in operateList" :key="item.id" class="item" effect="dark" :content="item.title" placement="top">
                  <el-button :icon="item.icon" :v-hasPermi="item.hasPermi" circle @click="handleOperate(item.id, scope.row)"></el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          small
          background
          layout="total,sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 添加或修改慢性疾病档案对话框 -->
    <el-dialog :title="title" v-model="open" width="880px" append-to-body>
      <el-form ref="chronicDiseaseRef" :model="form" :inline="true" :rules="rules" label-width="120px">
        <el-form-item label="成员" prop="personId">
          <el-select v-model="form.personId" placeholder="请选择成员" filterable @change="handleMemberChange">
            <el-option v-for="item in memberList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="关联疾病" prop="diseaseId">
          <el-select v-model="form.diseaseId" placeholder="请选择疾病（可选）" clearable filterable @change="handleDiseaseChange">
            <el-option v-for="item in diseaseList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="疾病名称" prop="diseaseName">
          <el-input v-model="form.diseaseName" placeholder="请输入疾病名称" />
        </el-form-item>
        <el-form-item label="疾病编码" prop="diseaseCode">
          <el-input v-model="form.diseaseCode" placeholder="ICD-10编码（可选）" />
        </el-form-item>
        <el-form-item label="确诊日期" prop="diagnosisDate">
          <el-date-picker v-model="form.diagnosisDate" type="date" placeholder="选择确诊日期" value-format="YYYY-MM-DD" style="width: 200px" />
        </el-form-item>
        <el-form-item label="状态" prop="diseaseStatus">
          <el-select v-model="form.diseaseStatus" placeholder="请选择状态">
            <el-option v-for="dict in disease_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主治医生" prop="mainDoctor">
          <el-input v-model="form.mainDoctor" placeholder="请输入主治医生" />
        </el-form-item>
        <el-form-item label="就诊医院" prop="hospital">
          <el-input v-model="form.hospital" placeholder="请输入就诊医院" />
        </el-form-item>
        <el-form-item label="科室" prop="department">
          <el-input v-model="form.department" placeholder="请输入科室" />
        </el-form-item>
        <el-form-item label="诊断结果" style="width: 792px" prop="notes">
          <el-input v-model="form.notes" type="textarea" :rows="3" placeholder="请输入说明" />
        </el-form-item>
        <el-form-item label="备注" style="width: 792px" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template v-if="title !== '查看慢性疾病档案'" #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ChronicDisease">
import { listChronicDisease, getChronicDisease, delChronicDisease, addChronicDisease, updateChronicDisease } from '@/api/health/chronicDisease'
import { listHealthDiseases } from '@/api/health/healthDiseases'
import { listPerson } from '@/api/health/person'

const { proxy } = getCurrentInstance()
const { disease_status, is_active } = proxy.useDict('disease_status', 'is_active')

const chronicDiseaseList = ref([])
const memberList = ref([])
const diseaseList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const operateList = ref([
  { id: 'view', icon: 'View', title: '查看', hasPermi: ['health:chronicDisease:query'] },
  { id: 'edit', icon: 'Edit', title: '修改', hasPermi: ['health:chronicDisease:edit'] },
  { id: 'delete', icon: 'Delete', title: '删除', hasPermi: ['health:chronicDisease:remove'] }
])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    personId: null,
    diseaseName: null,
    diseaseStatus: null,
    isActive: null
  },
  rules: {
    personId: [{ required: true, message: '成员不能为空', trigger: 'change' }],
    diseaseName: [{ required: true, message: '疾病名称不能为空', trigger: 'blur' }],
    diseaseStatus: [{ required: true, message: '状态不能为空', trigger: 'change' }]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 获取状态类型 */
function getStatusType(status) {
  const types = { 1: 'success', 2: 'warning', 3: 'danger' }
  return types[status] || 'info'
}

/** 获取状态标签 */
function getStatusLabel(status) {
  const labels = { 1: '稳定', 2: '需关注', 3: '急性期' }
  return labels[status] || '未知'
}

/** 操作按钮 */
const handleOperate = (operate, row) => {
  switch (operate) {
    case 'view':
      handleView(row)
      break
    case 'edit':
      handleUpdate(row)
      break
    case 'delete':
      handleDelete(row)
      break
    default:
      break
  }
}

/** 查询成员列表 */
function getMemberList() {
  listPerson({ pageNum: 1, pageSize: 1000 }).then((response) => {
    memberList.value = response.rows || []
  })
}

/** 查询疾病列表 */
function getDiseaseList() {
  listHealthDiseases({ pageNum: 1, pageSize: 1000 }).then((response) => {
    diseaseList.value = response.rows || []
  })
}

/** 查询慢性疾病档案列表 */
function getList() {
  loading.value = true
  listChronicDisease(queryParams.value).then((response) => {
    chronicDiseaseList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    personId: null,
    diseaseId: null,
    diseaseName: null,
    diseaseCode: null,
    diagnosisDate: null,
    diseaseStatus: 1,
    mainDoctor: null,
    hospital: null,
    department: null,
    notes: null,
    isActive: 1,
    remark: null
  }
  proxy.resetForm('chronicDiseaseRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

// 分页
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

// 每页显示条数改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}

// 序号翻页递增
const indexMethod = (index) => {
  const nowPage = queryParams.value.pageNum
  const nowLimit = queryParams.value.pageSize
  return index + 1 + (nowPage - 1) * nowLimit
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 查看
const handleView = (row) => {
  title.value = '查看慢性疾病档案'
  form.value = { ...row }
  open.value = true
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加慢性疾病档案'
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getChronicDisease(_id).then((response) => {
    form.value = response.data
    open.value = true
    title.value = '修改慢性疾病档案'
  })
}

/** 状态修改 */
function handleStatusChange(row) {
  const text = row.isActive === 1 ? '启用' : '停用'
  proxy.$modal
    .confirm('确认要"' + text + '"该慢性疾病档案吗？')
    .then(() => {
      return updateChronicDisease({ id: row.id, isActive: row.isActive })
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + '成功')
    })
    .catch(() => {
      row.isActive = row.isActive === 0 ? 1 : 0
    })
}

/** 选择疾病时自动填充疾病名称 */
function handleDiseaseChange(diseaseId) {
  if (diseaseId) {
    const disease = diseaseList.value.find((item) => item.id === diseaseId)
    if (disease) {
      form.value.diseaseName = disease.name
    }
  }
}

/** 选择成员时清空疾病选择 */
function handleMemberChange() {
  // 可以在这里添加其他逻辑
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs.chronicDiseaseRef.validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateChronicDisease(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addChronicDisease(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(function () {
      return delChronicDisease(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

// 初始化
getMemberList()
getDiseaseList()
getList()
</script>

<style scoped></style>
