<template>
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      min-label-width="68px"
    >
      <el-form-item label="工艺路线编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入工艺路线编码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="工艺路线名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入工艺路线名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="是否启用" prop="isEnable">
        <el-select v-model="queryParams.isEnable" placeholder="请选择是否启用" clearable class="!w-180px">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime" v-show="showAllFilters">
        <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 v-if="filterCount > 3">
        <el-button type="text" class="text-primary" @click="toggleFilters">
          <Icon :icon="showAllFilters ? 'ep:arrow-up' : 'ep:arrow-down'" class="mr-5px" />
          {{ showAllFilters ? t('common.shrink') : t('common.expand') }}
        </el-button>
      </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')"
        >
          <Icon icon="ep:plus" class="mr-5px" /> {{ t('action.add') }}
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['mes:process-route:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> {{ t('action.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"
      :max-height="planTableMaxHeight"
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" reserve-selection />
      <el-table-column label="工艺路线编码" align="center" prop="code" sortable />
      <el-table-column label="工艺路线名称" align="center" prop="name" sortable />
      <el-table-column label="是否启用" align="center" prop="isEnable" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.isEnable" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
        sortable
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['mes:process-route:update']"
          >
            {{ t('action.edit') }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['mes:process-route:delete']"
          >
            {{ t('action.del') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

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

<script setup lang="ts">
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ProcessRouteApi, ProcessRouteVO } from '@/api/mes/processroute'
import ProcessRouteForm from './ProcessRouteForm.vue'

defineOptions({ name: 'ProcessRoute' })

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

const loading = ref(true)
const list = ref<ProcessRouteVO[]>([])
const total = ref(0)
const tableRef = ref()
const planTableMaxHeight = ref(520)
const planPaginationRef = ref<HTMLElement>()

const updatePlanTableMaxHeight = async () => {
  await nextTick()
  const tableTop = tableRef.value?.$el?.getBoundingClientRect().top ?? 0
  const paginationHeight = planPaginationRef.value?.getBoundingClientRect().height ?? 72
  const pageBottomGap = 56
  const availableHeight = window.innerHeight - tableTop - paginationHeight - pageBottomGap
  planTableMaxHeight.value = Math.min(window.innerHeight, Math.max(240, Math.floor(availableHeight)))
}
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  name: undefined,
  isEnable: undefined,
  createTime: []
})
const queryFormRef = ref()
const exportLoading = ref(false)
const selectedIds = ref<number[]>([])
const showAllFilters = ref(false)
const filterCount = 4

const toggleFilters = () => {
  showAllFilters.value = !showAllFilters.value
  updatePlanTableMaxHeight()
}

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

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

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

const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await ProcessRouteApi.deleteProcessRoute(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

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

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const params = {
      ...queryParams,
      ids: selectedIds.value.length ? selectedIds.value.join(',') : undefined
    }
    const data = await ProcessRouteApi.exportProcessRoute(params)
    download.excel(data, '工艺路线.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

onMounted(() => {
  getList()
  updatePlanTableMaxHeight()
  window.addEventListener("resize", updatePlanTableMaxHeight)
})

onBeforeUnmount(() => {
  window.removeEventListener("resize", updatePlanTableMaxHeight)
})
</script>
