<template>
  <ContentWrap>
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="-mb-15px">
      <el-form-item :label="t('MoldManagement.MoldListPage.code')" prop="code"><el-input v-model="queryParams.code" :placeholder="t('MoldManagement.MoldListPage.placeholderCode')" clearable @keyup.enter="handleQuery" class="!w-200px" /></el-form-item>
      <el-form-item :label="t('MoldManagement.MoldListPage.name')" prop="name"><el-input v-model="queryParams.name" :placeholder="t('MoldManagement.MoldListPage.placeholderName')" clearable @keyup.enter="handleQuery" class="!w-200px" /></el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> {{ t('MoldManagement.MoldListPage.query') }}</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> {{ t('MoldManagement.MoldListPage.reset') }}</el-button>
        <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['erp:mold-brand:create']"><Icon icon="ep:plus" class="mr-5px" /> {{ t('MoldManagement.MoldListPage.addSubMold') }}</el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading" v-hasPermi="['erp:mold-brand:export']"><Icon icon="ep:download" class="mr-5px" /> {{ t('MoldManagement.MoldListPage.export') }}</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column :label="t('MoldManagement.MoldListPage.index')" type="index" width="70" align="center" />
      <el-table-column :label="t('MoldManagement.MoldListPage.subMoldName')" prop="name" min-width="160" />
      <el-table-column :label="t('MoldManagement.MoldListPage.type')" min-width="120">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SUBMOLD_TYPE" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column :label="t('MoldManagement.MoldListPage.installLocation')" min-width="140">
        <template #default="scope">
          {{ scope.row.installLocation || scope.row.installPosition || scope.row.currentPosition || scope.row.machineName || '-' }}
        </template>
      </el-table-column>
      <el-table-column :label="t('MoldManagement.MoldListPage.material')" min-width="120">
        <template #default="scope">
          {{ scope.row.material || '-' }}
        </template>
      </el-table-column>
      <el-table-column :label="t('MoldManagement.MoldListPage.quantity')" width="90" align="center">
        <template #default="scope">
          {{ scope.row.quantity || scope.row.count || 1 }}
        </template>
      </el-table-column>
      <el-table-column :label="t('MoldManagement.MoldListPage.operate')" fixed="right" width="160">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('update', scope.row.id)">{{ t('MoldManagement.MoldListPage.edit') }}</el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)">{{ t('MoldManagement.MoldListPage.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>
  <MoldForm ref="formRef" @success="getList" />
  <MoldRecordForm ref="recordFormRef" @success="getList" />
</template>
<script setup lang="ts">
import { defineAsyncComponent, nextTick } from 'vue'
import download from '@/utils/download'
import { DICT_TYPE } from '@/utils/dict'
import { MoldBrandApi } from '@/api/erp/mold'

const { t } = useI18n()
const message = useMessage() // 消息弹窗
const MoldForm = defineAsyncComponent(() => import('./MoldForm.vue') as any)
const MoldRecordForm = defineAsyncComponent(() => import('@/views/erp/mold/components/MoldRecordForm.vue') as any)

const props = defineProps<{
  brandId?: number // 型号id（主表的关联字段）
}>()
const loading = ref(false) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const exportLoading = ref(false) // 导出的加载中
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  brandId: undefined as unknown,
  code: undefined,
  name: undefined
})
const queryFormRef = ref()

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

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.brandId,
  (val: number) => {
    if (!val) {
      return
    }
    queryParams.brandId = val
    queryParams.code = undefined
    queryParams.name = undefined
    queryParams.pageNo = 1
    getList()
  },
  { immediate: true, deep: true }
)

/** 添加/修改操作 */
const formRef = ref()
const openForm = async (type: string, id?: number) => {
  if (!props.brandId) {
    message.error(t('MoldManagement.MoldListPage.selectBrandTip'))
    return
  }
  await nextTick()
  if (!formRef.value || typeof formRef.value.open !== 'function') {
    message.error(t('MoldManagement.MoldListPage.formNotReady'))
    return
  }
  formRef.value.open(type, id, props.brandId)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MoldBrandApi.deleteMold(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 导出按钮操作 */
const handleExport = async () => {
  if (!props.brandId) {
    message.error(t('MoldManagement.MoldListPage.selectBrandTip'))
    return
  }
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await MoldBrandApi.exportMold({
      ...queryParams,
      brandId: props.brandId
    })
    download.excel(data, t('MoldManagement.MoldListPage.exportFilename'))
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 添加/修改操作 */
const recordFormRef = ref()
const openRecordForm = (type: string, id?: number, brandId?: number) => {
  recordFormRef.value.open(type, id, brandId)
}

</script>
