<template>
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="90px"
    >
      <TenantSelect v-model="queryParams.tenantIds" placeholder="请选择机构名称" prop="tenantIds" />
      <el-form-item label="长者姓名" prop="elderName">
        <el-input v-model="queryParams.elderName" placeholder="请输入长者姓名" class="!w-240px" />
      </el-form-item>
      <el-form-item label="记录日期" prop="recordDate">
        <el-date-picker
          type="daterange"
          value-format="YYYY-MM-DD"
          format="YYYY-MM-DD"
          date-format="YYYY-MM-DD"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          v-model="queryParams.recordDate"
          class="!w-240px"
          @clear="handleDateClose"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <div class="mb-10px" style="display:flex;align-items:center;justify-content: space-between;gap: 10px;">
      <div style="display:flex;align-items:center;gap: 10px;">
        <el-button type="primary" plain @click="openForm()" v-hasPermi="['elderly:blood-glucose:add']">
          <Icon icon="ep:plus" class="mr-5px" />
          新增
        </el-button>
        <el-button type="warning" plain @click="exportExcel" v-hasPermi="['elderly:blood-glucose:export']">
          <Icon icon="ep:download" class="mr-5px" />
          导出
        </el-button>
      </div>
    </div>

    <Table2
      v-loading="loading"
      :data="list"
      :columns="columns"
      :queryParams="queryParams"
    >
      <template #pre="{scope}">
        <el-button link type="primary" @click="openForm(scope, 2)" v-hasPermi="['elderly:blood-glucose:edit']">编辑</el-button>
        <el-button link type="danger" @click="handleDelete(scope)" v-hasPermi="['elderly:blood-glucose:delete']">删除</el-button>
      </template>
    </Table2>

    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <Form ref="formRef" @success="getList" />
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { useUserStore } from '@/store/modules/user'
import Form from './component/form.vue'
import { DICT_TYPE } from '@/utils/dict'
import {
  deleteBloodGlucose,
  getBloodGlucosePage,
  exportBloodGlucoseExcel
} from '@/api/elderly/assess/blood-glucose'
import download from '@/utils/download'

defineOptions({ name: 'BloodGlucose' })

const userStore = useUserStore()
const message = useMessage()
const { t } = useI18n()

const loading = ref(true)
const total = ref(0)
const list = ref<any[]>([])

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  tenantIds: userStore.orgTenantId,
  recordDate: undefined,
  elderName: undefined
})

const queryFormRef = ref()

const columns = reactive([
  { label: '长者姓名', field: 'elderName' },
  { label: '房间号', field: 'roomName' },
  { label: '床位号', field: 'bedName' },
  { label: '性别', field: 'elderSex', type: '1', dictArr: DICT_TYPE.SYSTEM_USER_SEX },
  { label: '记录日期', field: 'recordDate' },
  { label: '血糖值', field: 'bloodSugar' },
  { label: '备注', field: 'remark' },
])

const handleDateClose = () => {
  queryParams.recordDate = undefined
}

const getList = async () => {
  loading.value = true
  try {
    const data = await getBloodGlucosePage(queryParams)
    list.value = data.list || []
    total.value = data.total || 0
  } finally {
    loading.value = false
  }
}

const handleQuery = async () => {
  if (!queryFormRef.value) return
  const valid = await queryFormRef.value.validate()
  if (!valid) return
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

const formRef = ref()
const openForm = (row: any = {}, type: number = 1) => {
  if (queryParams.tenantIds.length == 0 || (queryParams.tenantIds.length > 1 && !row.tenantId)) {
    message.error(`${type === 1 ? '新增' : '编辑'}只能选择一个机构`)
    return
  }
  console.log('row', row)
  formRef.value.open(row.tenantId || queryParams.tenantIds[0], row.id, type)
}

const handleDelete = async (row: any) => {
  try {
    await message.delConfirm()
    await deleteBloodGlucose(row.id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const exportExcel = async () => {
  try {
    await message.exportConfirm()
    const data = await exportBloodGlucoseExcel(queryParams)
    download.excel(data, '血糖记录.xls')
  } catch {
  }
}

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


