<template>
  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item :label="t('MoldManagement.MoldRepairItems.subjectCode')" prop="subjectCode">
        <el-input
          v-model="queryParams.subjectCode"
          :placeholder="t('MoldManagement.MoldRepairItems.placeholderSubjectCode')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('MoldManagement.MoldRepairItems.subjectName')" prop="subjectName">
        <el-input
          v-model="queryParams.subjectName"
          :placeholder="t('MoldManagement.MoldRepairItems.placeholderSubjectName')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('MoldManagement.MoldRepairItems.projectContent')" prop="projectContent">
        <el-input
          v-model="queryParams.projectContent"
          :placeholder="t('MoldManagement.MoldRepairItems.placeholderProjectContent')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('MoldManagement.MoldRepairItems.createTime')" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          :start-placeholder="t('MoldManagement.MoldRepairItems.placeholderCreateTimeStart')"
          :end-placeholder="t('MoldManagement.MoldRepairItems.placeholderCreateTimeEnd')"
          :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" /> {{ t('MoldManagement.MoldRepairItems.search') }}</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> {{ t('MoldManagement.MoldRepairItems.reset') }}</el-button>
        <el-button type="primary" plain @click="openForm('create')">
          <Icon icon="ep:plus" class="mr-5px" /> {{ t('MoldManagement.MoldRepairItems.add') }}
        </el-button>
        <el-button type="danger" plain @click="handleBatchDelete" :disabled="!selectedIds.length">
          <Icon icon="ep:delete" class="mr-5px" /> {{ t('MoldManagement.MoldRepairItems.batchDelete') }}
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" /> {{ t('MoldManagement.MoldRepairItems.export') }}
        </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="t('MoldManagement.MoldRepairItems.subjectCode')" align="center" prop="subjectCode" min-width="150"
        :formatter="cellOrDash"
      />
      <el-table-column
        :label="t('MoldManagement.MoldRepairItems.subjectName')" align="center" prop="subjectName" min-width="170"
        :formatter="cellOrDash"
      />
      <el-table-column
        :label="t('MoldManagement.MoldRepairItems.moldName')" align="center" prop="moldName" min-width="170"
        :formatter="cellOrDash"
      />
      <el-table-column
        :label="t('MoldManagement.MoldRepairItems.projectContent')" align="center" prop="projectContent" min-width="220"
        :formatter="cellOrDash"
      />
      <el-table-column
        :label="t('MoldManagement.MoldRepairItems.createTime')" align="center" prop="createTime"
        :formatter="dateOrDash" min-width="190"
      />
      <el-table-column :label="t('MoldManagement.MoldRepairItems.operate')" align="center" min-width="160" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('update', scope.row)">
            {{ t('MoldManagement.MoldRepairItems.edit') }}
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)">
            {{ t('MoldManagement.MoldRepairItems.delete') }}
          </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(t('MoldManagement.MoldRepairItems.selectDeleteTip'))
    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, t('MoldManagement.MoldRepairItems.exportFilename'))
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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