<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="memberId">
          <el-select v-model="queryParams.memberId" 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="planId">
          <el-select v-model="queryParams.planId" placeholder="请选择计划" clearable filterable style="width: 250px">
            <el-option v-for="item in planList" :key="item.id" :label="item.planName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option v-for="dict in medication_task_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </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 :disabled="multiple" icon="Delete" @click="handleDelete" v-hasPermi="['health:medicationTask:remove']">删除</el-button>
        </div>
      </div>
      <div class="content-con" v-loading="loading">
        <el-table v-loading="loading" :data="taskList" @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="planName" width="150" />
          <el-table-column label="人员" align="center" prop="personName" width="80" />
          <el-table-column label="药品" align="center" prop="medicineName" width="180" />
          <el-table-column label="计划日期" align="center" prop="plannedDate" width="110">
            <template #default="scope">
              {{ formatDate(scope.row.plannedDate) }}
            </template>
          </el-table-column>
          <el-table-column label="计划时间" align="center" prop="plannedTime" width="100">
            <template #default="scope">
              {{ formatTime(scope.row.plannedTime) }}
            </template>
          </el-table-column>
          <el-table-column label="实际时间" align="center" width="160">
            <template #default="scope">
              {{ scope.row.actualTime ? formatDateTime(scope.row.actualTime) : '--' }}
            </template>
          </el-table-column>
          <el-table-column label="剂量" align="center" width="100">
            <template #default="scope">
              {{ scope.row.plannedDosage }}
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status" width="90">
            <template #default="scope">
              <dict-tag :options="medication_task_status" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="notes" show-overflow-tooltip />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template v-slot="scope">
              <div class="ctrl-btn d-flex">
                <el-tooltip v-if="scope.row.status === 0" class="item" effect="dark" content="确认服药" placement="top">
                  <el-button type="success" icon="Check" v-hasPermi="['health:medicationTask:edit']" circle @click="handleConfirm(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip v-if="scope.row.status === 0" class="item" effect="dark" content="跳过" placement="top">
                  <el-button type="warning" icon="Close" v-hasPermi="['health:medicationTask:edit']" circle @click="handleSkip(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="删除" placement="top">
                  <el-button icon="Delete" v-hasPermi="['health:medicationTask:remove']" circle @click="handleDelete(scope.row)"></el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          small
          background
          layout="total,sizes, prev, pager, next"
          :page-sizes="[10, 20, 50]"
          :total="total"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          @size-change="getList"
          @current-change="getList"
        />
      </div>
    </div>

    <!-- 确认服药对话框 -->
    <el-dialog title="确认服药" v-model="confirmDialogVisible" width="400px">
      <el-form>
        <el-form-item label="实际服药时间">
          <el-time-picker v-model="actualTime" placeholder="选择实际服药时间" format="HH:mm" value-format="HH:mm" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="confirmDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitConfirm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 跳过对话框 -->
    <el-dialog title="跳过服药" v-model="skipDialogVisible" width="400px">
      <el-form>
        <el-form-item label="跳过原因">
          <el-input v-model="skipNotes" type="textarea" placeholder="请输入跳过原因（选填）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="skipDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSkip">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MedicationTask">
import { listMedicationTask, delMedicationTask, confirmMedication, skipMedication } from '@/api/health/medicationTask'
import { listMedicationPlan } from '@/api/health/medicationPlan'
import { listPerson } from '@/api/health/person'

const { proxy } = getCurrentInstance()
const { medication_task_status } = proxy.useDict('medication_task_status')

const taskList = ref([])
const planList = ref([])
const memberList = ref([])
const loading = ref(false)
const multiple = ref(true)
const total = ref(0)
const dateRange = ref([])
const ids = ref([])

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  memberId: null,
  planId: null,
  status: null,
  plannedDateBegin: null,
  plannedDateEnd: null
})

const confirmDialogVisible = ref(false)
const actualTime = ref('')
const skipDialogVisible = ref(false)
const skipNotes = ref('')
const currentRow = ref(null)

const getList = async () => {
  loading.value = true
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.plannedDateBegin = dateRange.value[0]
    queryParams.plannedDateEnd = dateRange.value[1]
  } else {
    queryParams.plannedDateBegin = null
    queryParams.plannedDateEnd = null
  }
  try {
    const res = await listMedicationTask(queryParams)
    taskList.value = res.rows || []
    total.value = res.total || 0
  } finally {
    loading.value = false
  }
}

const getPlanList = async () => {
  const res = await listMedicationPlan({})
  planList.value = res.rows || []
}

const getMemberList = async () => {
  const res = await listPerson({})
  memberList.value = res.rows || []
}

const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

const resetQuery = () => {
  dateRange.value = []
  queryParams.memberId = null
  queryParams.planId = null
  queryParams.status = null
  handleQuery()
}

const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id)
  multiple.value = !selection.length
}

const handleConfirm = (row) => {
  currentRow.value = row
  // 默认当前时间
  const now = new Date()
  actualTime.value = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`
  confirmDialogVisible.value = true
}

const submitConfirm = async () => {
  if (!actualTime.value) {
    proxy.$modal.msgError('请选择实际服药时间')
    return
  }
  // confirmType=1 表示确认服药，confirmTime 传递时间字符串
  await confirmMedication(currentRow.value.id, 1, actualTime.value)
  proxy.$modal.msgSuccess('操作成功')
  confirmDialogVisible.value = false
  getList()
}

const handleSkip = (row) => {
  currentRow.value = row
  skipNotes.value = ''
  skipDialogVisible.value = true
}

const submitSkip = async () => {
  await skipMedication(currentRow.value.id, skipNotes.value)
  proxy.$modal.msgSuccess('操作成功')
  skipDialogVisible.value = false
  getList()
}

const handleDelete = async (row) => {
  const idList = row.id ? [row.id] : ids.value
  await proxy.$modal.confirm('确认删除选中的记录？')
  await delMedicationTask(idList.join(','))
  proxy.$modal.msgSuccess('删除成功')
  getList()
}

const indexMethod = (index) => {
  return (queryParams.pageNum - 1) * queryParams.pageSize + index + 1
}

const formatDate = (date) => {
  if (!date) return '--'
  // 处理数组格式 [2026, 3, 21]
  if (Array.isArray(date)) {
    return `${date[0]}-${String(date[1]).padStart(2, '0')}-${String(date[2]).padStart(2, '0')}`
  }
  // 处理字符串格式
  if (typeof date === 'string') {
    return date.substring(0, 10)
  }
  return '--'
}

const formatTime = (time) => {
  if (!time) return '--'
  // 处理数组格式 [8, 0] 或 [14, 30]
  if (Array.isArray(time)) {
    return `${String(time[0]).padStart(2, '0')}:${String(time[1]).padStart(2, '0')}`
  }
  // 处理字符串格式
  if (typeof time === 'string') {
    return time.substring(0, 5)
  }
  return '--'
}

const formatDateTime = (datetime) => {
  if (!datetime) return '--'
  return datetime.replace('T', ' ').substring(0, 16)
}

onMounted(() => {
  getList()
  getPlanList()
  getMemberList()
})
</script>

<style scoped lang="scss"></style>
