<template>
  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item label="维修编码" prop="subjectCode">
        <el-input v-model="queryParams.subjectCode" placeholder="请输入维修编码" clearable @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <el-form-item label="维修名称" prop="subjectName">
        <el-input v-model="queryParams.subjectName" placeholder="请输入维修名称" clearable @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <el-form-item label="维修内容" prop="projectContent">
        <el-input
          v-model="queryParams.projectContent"
          placeholder="请输入维修内容"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </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-button type="primary" plain @click="openForm('create')">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button type="danger" plain @click="handleBatchDelete" :disabled="!selectedIds.length">
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" fixed="left" reserve-selection />
      <el-table-column label="维修编码" align="center" prop="subjectCode" min-width="130" :formatter="cellOrDash" />
      <el-table-column label="维修名称" align="center" prop="subjectName" min-width="160" :formatter="cellOrDash" />
      <el-table-column label="模具名称" align="center" prop="moldName" min-width="160" :formatter="cellOrDash" />
      <el-table-column label="维修内容" align="center" prop="projectContent" min-width="200" :formatter="cellOrDash" />
      <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateOrDash" width="180" />
      <el-table-column label="操作" align="center" width="140" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('update', scope.row)">编辑</el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

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

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { MoldRepairItemsApi, MoldRepairItemVO } from '@/api/mold/moldRepairItems'
import MoldRepairItemsForm from './MoldRepairItemsForm.vue'

defineOptions({ name: 'MoldRepairItems' })

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

const loading = ref(true)
const list = ref<MoldRepairItemVO[]>([])
const total = ref(0)
const exportLoading = ref(false)

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  subjectCode: undefined as string | undefined,
  subjectName: undefined as string | undefined,
  projectContent: undefined as string | undefined,
  createTime: [] as string[]
})

const queryFormRef = ref()
const tableRef = ref()
const selectedIds = ref<number[]>([])
const formRef = ref()

const cellOrDash = (_row: any, _column: any, cellValue: any) => {
  if (cellValue === undefined || cellValue === null || cellValue === '') return '-'
  return String(cellValue)
}

const dateOrDash = (row: any, column: any, cellValue: any) => {
  const text = dateFormatter(row, column, cellValue)
  if (text === undefined || text === null || text === '') return '-'
  return String(text)
}

const getList = async () => {
  loading.value = true
  try {
    const data = await MoldRepairItemsApi.getRepairItemsPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

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

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

const handleSelectionChange = (rows: any[]) => {
  selectedIds.value = rows?.map((row) => row.id).filter((id) => id !== undefined) ?? []
}

const openForm = (type: string, row?: any) => {
  formRef.value.open(type, row)
}

const buildIdsParam = (ids: number | number[]) => {
  return Array.isArray(ids) ? ids.join(',') : String(ids)
}

const handleDelete = async (ids: number | number[]) => {
  try {
    await message.delConfirm()
    await MoldRepairItemsApi.deleteRepairItems(buildIdsParam(ids))
    message.success(t('common.delSuccess'))
    selectedIds.value = []
    tableRef.value?.clearSelection?.()
    await getList()
  } catch {}
}

const handleBatchDelete = async () => {
  if (!selectedIds.value.length) {
    message.error('请选择需要删除的数据')
    return
  }
  await handleDelete(selectedIds.value)
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const params = {
      ...queryParams,
      ids: selectedIds.value.length ? selectedIds.value.join(',') : undefined
    }
    const data = await MoldRepairItemsApi.exportRepairItems(params)
    download.excel(data, '模具维修项目.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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