<template>
  <ContentWrap>
    <!-- 搜索表单 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
    >
      <el-form-item label="训练时间">
        <el-date-picker
          size="default"
          class="!w-240px"
          v-model="queryParams.trainingTime"
          type="daterange"
          :clearable="true"
          :editable="false"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          format="YYYY-MM-DD"
          date-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="长者姓名">
        <el-input
          v-model="queryParams.elderName"
          placeholder="长者姓名"
          class="!w-240px"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" style="margin-left: 2vw">
          <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">
      <ButtonAdd @click="openForm(undefined)" v-hasPermi="['records:rehabilitation-training:add']" />
      <ButtonImport @click="outTab(undefined)" v-hasPermi="['records:rehabilitation-training:add']" />
      <el-button type="info" plain @click="importRef.open()" v-hasPermi="['records:medical-care-records:output']">
        <Icon icon="ep:download" /> 导入
      </el-button>
    </div>
    <el-table v-loading="loading" :data="list" :header-cell-style="tableHeaderColor">
      <el-table-column header-align="center" align="center" label="序号" width="60">
        <template #default="scope">
          {{
            scope.$index + (queryParams.pageNo * queryParams.pageSize - queryParams.pageSize) + 1
          }}
        </template>
      </el-table-column>
      <el-table-column prop="trainingTime" header-align="center" align="center" label="训练时间" min-width="180" show-overflow-tooltip :formatter="dateFormatter" />
      <!-- <el-table-column prop="admissionNumber" header-align="center" align="center" label="入院号" min-width="150" show-overflow-tooltip/> -->
      <el-table-column prop="elderName" header-align="center" align="center" label="姓名" min-width="120" show-overflow-tooltip/>
      <el-table-column prop="bedInfo" header-align="center" align="center" label="床位信息" min-width="150" show-overflow-tooltip/>
      <el-table-column prop="recordContent" header-align="center" align="center" label="记录内容" min-width="200" show-overflow-tooltip/>
      <el-table-column prop="therapist" header-align="center" align="center" label="康复师" min-width="120" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" min-width="180" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openFormDetail(scope.row.recordId)"
          >
            <Icon icon="ep:view" class="mr-5px" /> 查看
          </el-button>
          <el-button
            v-hasPermi="['records:rehabilitation-training:update']"
            link
            type="primary"
            @click="openFormEdit(scope.row)"
          >
            <Icon icon="ep:edit" class="mr-5px" /> 编辑
          </el-button>
          <el-button
            v-hasPermi="['records:rehabilitation-training:delete']"
            link
            type="danger"
            @click="openFormDelete(scope.row.recordId)"
          >
            <Icon icon="ep:delete" class="mr-5px" /> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <AddForm ref="formRef" @success="getList" />
  <EditForm ref="editRef" @success="getList" />
  <DetailForm ref="detailRef" @success="getList" />

  <Import
    ref="importRef"
    @success="getList"
    :config="{
      title: '导入',
      downloadUrl: '/training/records/import-template',
      excelTempName: '机构养老-【康复训练记录】模板',
      importUrl: '/training/records/import',
      failExportUrl: '/elderlyInfo/downErrorExcel'
    }"
  />

</template>

<script setup lang="ts">
import { useUserStore } from '@/store/modules/user'
import { trainingPage, trainingDelete } from "@/api/elderly/nursing/records/rehabilitation-training";
import download from "@/utils/download";
import { getTenantId } from '@/utils/auth'
import { dateFormatter } from '@/utils/formatTime'
import {formatToDateTime} from "@/utils/dateUtil";
import {exportWithExpandedObjectArrays} from "@/utils/excel-export";
import {careRecordsPage} from "@/api/member/appointment";
import Import from "@/components/ImportFile/index.vue";

const AddForm = defineAsyncComponent(() => import('./AddForm.vue'))
const EditForm = defineAsyncComponent(() => import('./EditForm.vue'))
const DetailForm = defineAsyncComponent(() => import('./DetailForm.vue'))
const ButtonAdd = defineAsyncComponent(() => import("@/components/ButtonAdd/src/ButtonAdd.vue"))

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const userStore = useUserStore()
const loading = ref(true) // 列表的加载中
const importRef = ref()
const exportLoading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
let queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  trainingTime: [],
  elderName: '',
  tenantId: getTenantId()
})
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await trainingPage(queryParams)
    list.value = data.list || []
    total.value = data.total
  } 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 = () => {
  queryParams.trainingTime = []
  queryParams.elderName = ''
  queryParams.tenantId = getTenantId()
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加操作 */
const formRef = ref()
const openForm = (recordId?: number) => {
  formRef.value.open(queryParams.tenantId, recordId, false)
}

const outTab = async () => {
// 处理批量导出
  loading.value = true
    try {
      const list = await trainingPage(queryParams)
      if (list.list.length <= 0) {
        message.error('暂无数据可以导出!')
        return
      }
      const headers = [
        { key: 'trainingTime', title: '训练时间' },
        { key: 'contractNumber', title: '合同号' },
        { key: 'elderName', title: '长者姓名' },
        { key: 'bedInfo', title: '床位号' },
        { key: 'recordContent', title: '记录内容' },
        { key: 'therapist', title: '康复师' }
      ]
      exportWithExpandedObjectArrays(list.list, headers, `康复训练记录${formatToDateTime()}.xlsx`, '康复训练记录')
    } catch (_) {}finally {
      loading.value = false
    }
}

/** 编辑操作 */
const editRef = ref()
const openFormEdit = (row: any = {}) => {
  editRef.value.open(row.tenantId, row.recordId, false)
}

/** 详情操作 */
const detailRef = ref()
const openFormDetail = (recordId?: number) => {
  detailRef.value.open(undefined, recordId, true)
}

/** 删除操作 */
const openFormDelete = async (recordId) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await trainingDelete(recordId)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}
/** 初始化 **/
onMounted(() => {
  getList()
})

// 表头格式
const tableHeaderColor = ({ rowIndex }: any) => {
  if (rowIndex === 0) {
    return {
      backgroundColor: '#f8f8f9',
      color: '#666666',
      fontWeight: 'bold'
    }
  }
}
</script>

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

