<template>
  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item :label="t('EquipmentManagement.EquipmentKeyItems.code')" prop="code">
        <el-input
          v-model="queryParams.code"
          :placeholder="t('EquipmentManagement.EquipmentKeyItems.placeholderCode')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.EquipmentKeyItems.name')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="t('EquipmentManagement.EquipmentKeyItems.placeholderName')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.EquipmentKeyItems.description')" prop="description">
        <el-input
          v-model="queryParams.description"
          :placeholder="t('EquipmentManagement.EquipmentKeyItems.placeholderDescription')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.EquipmentKeyItems.remark')" prop="remark">
        <el-input
          v-model="queryParams.remark"
          :placeholder="t('EquipmentManagement.EquipmentKeyItems.placeholderRemark')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.EquipmentKeyItems.createTime')" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          :start-placeholder="t('common.startTimeText')"
          :end-placeholder="t('common.endTimeText')"
          :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('common.query') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('common.reset') }}
        </el-button>
        <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['mes:critical-component:create']">
          <Icon icon="ep:plus" class="mr-5px" />
          {{ t('action.add') }}
        </el-button>
        <el-button
          type="danger"
          plain
          @click="handleBatchDelete"
          :disabled="!selectedIds.length"
          v-hasPermi="['mes:critical-component:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" />
          {{ t('EquipmentManagement.EquipmentKeyItems.delete') }}
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['mes:critical-component:export']"
        >
          <Icon icon="ep:download" class="mr-5px" />
          {{ t('action.export') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column :label="t('EquipmentManagement.EquipmentKeyItems.code')" align="center" prop="code" min-width="140" />
      <el-table-column :label="t('EquipmentManagement.EquipmentKeyItems.name')" align="center" prop="name" min-width="140" />
      <el-table-column :label="t('EquipmentManagement.EquipmentKeyItems.description')" align="center" prop="description" min-width="180" />
      <el-table-column :label="t('EquipmentManagement.EquipmentKeyItems.remark')" align="center" prop="remark" min-width="180" />
      <el-table-column :label="t('EquipmentManagement.EquipmentKeyItems.createTime')" align="center" prop="createTime" :formatter="dateFormatter" width="180" />
      <el-table-column :label="t('EquipmentManagement.EquipmentKeyItems.operate')" align="center" width="140" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('update', scope.row)" v-hasPermi="['mes:critical-component:update']">
            {{ t('EquipmentManagement.EquipmentKeyItems.edit') }}
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['mes:critical-component:delete']">
            {{ t('EquipmentManagement.EquipmentKeyItems.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>

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

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { CriticalComponentApi, CriticalComponentVO } from '@/api/mes/criticalComponent'
import CriticalComponentForm from './CriticalComponentForm.vue'

defineOptions({ name: 'CriticalComponent' })

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

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

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined as string | undefined,
  name: undefined as string | undefined,
  description: undefined as string | undefined,
  remark: undefined as string | undefined,
  createTime: [] as string[]
})

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

const getList = async () => {
  loading.value = true
  try {
    const data = await CriticalComponentApi.getCriticalComponentPage(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: CriticalComponentVO[]) => {
  selectedIds.value = rows.map((r) => r.id).filter((id): id is number => typeof id === 'number')
}

const formRef = ref()
const openForm = (type: 'create' | 'update', row?: Partial<CriticalComponentVO>) => {
  formRef.value.open(type, row)
}

const handleDelete = async (id?: number) => {
  if (!id) return
  try {
    await message.delConfirm()
    await CriticalComponentApi.deleteCriticalComponent(String(id))
    message.success(t('common.delSuccess'))
    await getList()
  } catch {
  }
}

const handleBatchDelete = async () => {
  if (!selectedIds.value.length) return
  try {
    await message.delConfirm()
    await CriticalComponentApi.deleteCriticalComponent(selectedIds.value.join(','))
    message.success(t('common.delSuccess'))
    selectedIds.value = []
    await getList()
  } catch {
  }
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const params = {
      ...queryParams,
      ids: selectedIds.value.length ? selectedIds.value.join(',') : undefined
    }
    const data = await CriticalComponentApi.exportCriticalComponent(params)
    download.excel(data, '设备关键件.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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