<template>
  <ContentWrap>
    <!-- 防噎食评估表 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="110px"
    >
      <TenantSelect v-model="queryParams.tenantIds" placeholder="请选择机构名称" prop="tenantIds" />
      <el-form-item label="长者姓名">
        <el-input
          v-model="queryParams.elderName"
          placeholder="长者姓名"
          class="!w-240px"
          clearable
        />
      </el-form-item>

      <el-form-item label="评估人">
        <el-input v-model="queryParams.assessor" placeholder="评估人" class="!w-240px" clearable />
      </el-form-item>

      <el-form-item label="记录日期">
        <el-date-picker
          size="default"
          ref="selectRef"
          class="!w-240px"
          v-model="queryParams.assessDate"
          type="daterange"
          :clearable="true"
          :editable="false"
          placeholder="选择记录日期"
          value-format="YYYY-MM-DD"
          format="YYYY-MM-DD"
          date-format="YYYY-MM-DD"
        />
      </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)" />
      <ButtonImport @click="handleImportCard" />
    </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
        label="机构名称"
        v-if="userStore.getUser.id == 1"
        type="index"
        width="150"
        align="center"
      >
        <template #default="{ row }">
          {{ findLabelById(userStore.getOrgTenant.options, row.tenantId) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="elderName"
        header-align="center"
        align="center"
        label="长者姓名"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column
        prop="assessor"
        header-align="center"
        align="center"
        label="评估人"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column
        prop="assessDate"
        header-align="center"
        align="center"
        label="记录日期"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column
        prop="riskLevel"
        header-align="center"
        align="center"
        label="风险等级"
        min-width="120"
        show-overflow-tooltip
      >
        <template #default="scope">
          <el-tag :type="getRiskLevelType(scope.row.riskLevel)">
            {{ getRiskLevelText(scope.row.riskLevel) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="creator"
        header-align="center"
        align="center"
        label="记录人"
        min-width="150"
        show-overflow-tooltip
      />

      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-button link type="primary" @click="openFormEdit(scope.row, scope.row.id)">
            编辑
          </el-button>
          <el-button link type="warning" @click="openFormDetail(scope.row, scope.row.id)">
            详情
          </el-button>
          <el-button link type="danger" @click="openClose(scope.row)"> 删除 </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" />
</template>

<script setup lang="ts">
import AddForm from './AddForm.vue'
import ButtonAdd from '@/components/ButtonAdd/src/ButtonAdd.vue'
import ButtonImport from '@/components/ButtonImport/src/ButtonImport.vue'
import { useUserStore } from '@/store/modules/user'
import { getCurrentMonthRange } from '@/utils/dateUtil'
import { asphyxiationDelete, asphyxiationPage } from '@/api/social-work'
import { exportWithExpandedObjectArrays } from '@/utils/excel-export'
import { findLabelById } from '@/utils/dict'

const message = useMessage()
const { t } = useI18n()
const userStore = useUserStore()
const loading = ref(true)
const total = ref(0)
const list = ref([])

const exportLoading = ref(false)
let queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  elderName: '',
  assessor: '',
  // assessDate: getCurrentMonthRange(),
  assessDate: [],
  tenantIds: userStore.orgTenantId
})
const queryFormRef = ref()

// 打开导出弹窗
const handleImportCard = async () => {
  exportLoading.value = true
  try {
    const queryP = {
      pageNo: 1,
      pageSize: 9999,
      elderName: queryParams.elderName,
      assessor: queryParams.assessor,
      assessDate: queryParams.assessDate,
      tenantIds: queryParams.tenantIds
    }
    const data = await asphyxiationPage(queryP)
    const exportData = data.list || []

    if (exportData.length === 0) {
      message.warning('暂无数据可导出')
      return
    }

    const processedData = exportData.map((item) => {
      const row: any = {
        orgName: findLabelById(userStore.getOrgTenant.options, item.tenantId) || '',
        elderName: item.elderName || '',
        assessor: item.assessor || '',
        assessDate: item.assessDate || '',
        assessScore: item.assessScore ?? '',
        creator: item.creator || ''
      }
      row.riskLevelText = getRiskLevelText(item.riskLevel) || '-'
      return row
    })

    const headers = [
      {
            'key': 'orgName',
            'title': '机构名称'
      },
      {
            'key': 'elderName',
            'title': '长者姓名'
      },
      {
            'key': 'assessor',
            'title': '评估人'
      },
      {
            'key': 'assessDate',
            'title': '记录日期'
      },
      {
            'key': 'riskLevelText',
            'title': '风险等级'
      },
      {
            'key': 'creator',
            'title': '记录人'
      }
]

    exportWithExpandedObjectArrays(processedData, headers, `防噎食评估_${new Date().getTime()}.xlsx`, '防噎食评估')
    message.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    message.error('导出失败，请重试')
  } finally {
    exportLoading.value = false
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await asphyxiationPage(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
  await getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.elderName = ''
  queryParams.assessor = ''
  queryParams.tenantIds = userStore.orgTenantId
  // queryParams.assessDate = getCurrentMonthRange()
  queryParams.assessDate = []
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (id?: number) => {
  if (queryParams.tenantIds.length == 0 || queryParams.tenantIds.length > 1) {
    message.error('新增只能选择一个机构')
    return
  }
  formRef.value.open(queryParams.tenantIds[0], id, false)
}

const openFormEdit = (row: any = {}, id?: number) => {
  formRef.value.open(row.tenantId, id, false)
}

const openFormDetail = (row: any = {}, id?: number) => {
  formRef.value.open(row.tenantId, id, true)
}

const openClose = async (item: any) => {
  try {
    const res = await message.confirm('确定要删除吗?', '提示')
    if (res == 'confirm') {
      try {
        const res = await asphyxiationDelete(item.id)
        if (res) {
          message.success(t('common.updateSuccess'))
          await getList()
        }
      } catch (err) {}
    }
  } catch {}
}

/** 取消按钮操作 */
const cancelDelete = async (id: number) => {
  try {
    await message.cancelConfirm()
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const route = useRoute()
/** 初始化 **/
onMounted(() => {
  if (route.query && route.query.elderName) {
    queryParams.elderName = route.query.elderName as string
  }
  getList()
})

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

// 获取风险等级类型
const getRiskLevelType = (riskLevel: string) => {
  switch (riskLevel) {
    case 'none':
      return 'success'
    case 'low':
      return 'info'
    case 'medium':
      return 'warning'
    case 'high':
      return 'danger'
    default:
      return ''
  }
}

// 获取风险等级文本
const getRiskLevelText = (riskLevel: string) => {
  switch (riskLevel) {
    case 'none':
      return '无风险'
    case 'low':
      return '低风险'
    case 'medium':
      return '中度风险'
    case 'high':
      return '高风险'
    default:
      return '-'
  }
}
</script>

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