<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.pressureNetInfo')" min-width="180">
        <template #default="scope">
          <div>{{ t('MoldManagement.MoldListPage.lastReplace') }}：{{ scope.row.pressureNetTime }}</div>
          <div>{{ t('MoldManagement.MoldListPage.usedDays') }}：{{ scope.row.pressureNetDays }}{{
            t('MoldManagement.MoldListPage.days') }}</div>
          <div v-if="scope.row.remark">{{ t('MoldManagement.MoldListPage.remark') }}：{{ scope.row.remark }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="t('MoldManagement.MoldListPage.operate')" fixed="right" width="220">
        <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>
          <el-button link type="warning" @click="openPressureNetRecord(scope.row.id)">{{
            t('MoldManagement.MoldListPage.pressureNetRecord') }}</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" />

  <!-- 压网记录弹框 -->
  <Dialog v-model="pressureNetDialogVisible" :title="t('MoldManagement.MoldListPage.pressureNetRecord')" width="700px">
    <div class="pressure-net-dialog-content">
      <el-table v-loading="pressureNetLoading" :data="pressureNetRecordList" :stripe="true"
        :show-overflow-tooltip="true">
        <el-table-column :label="t('MoldManagement.MoldListPage.subMoldName')" prop="moldName" min-width="120" />
        <el-table-column :label="t('MoldManagement.MoldListPage.pressureNetTime')" prop="pressureNetTime"
          min-width="160" :formatter="dateFormatter" />
        <el-table-column :label="t('MoldManagement.MoldListPage.createTime')" prop="createTime" min-width="160"
          :formatter="dateFormatter" />
        <el-table-column :label="t('MoldManagement.MoldListPage.remark')" prop="remark" min-width="160">
          <template #default="scope">
            {{ scope.row.remark || '-' }}
          </template>
        </el-table-column>
      </el-table>
      <Pagination :total="pressureNetTotal" v-model:page="pressureNetPageParams.pageNo"
        v-model:limit="pressureNetPageParams.pageSize" @pagination="getPressureNetRecordList" />
    </div>
  </Dialog>
  <MoldRecordForm ref="recordFormRef" @success="getList" />
</template>
<script setup lang="ts">
import { defineAsyncComponent, nextTick } from 'vue'
import download from '@/utils/download'
import { dateFormatter } from '@/utils/formatTime'
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)
}

/** 压网记录弹框 */
const pressureNetDialogVisible = ref(false)
const pressureNetLoading = ref(false)
const pressureNetRecordList = ref<any[]>([])
const pressureNetTotal = ref(0)
const pressureNetPageParams = reactive({
  pageNo: 1,
  pageSize: 10,
  moldId: undefined as number | undefined
})

const openPressureNetRecord = (moldId: number) => {
  pressureNetPageParams.moldId = moldId
  pressureNetPageParams.pageNo = 1
  pressureNetDialogVisible.value = true
  getPressureNetRecordList()
}

const getPressureNetRecordList = async () => {
  pressureNetLoading.value = true
  try {
    const data = await MoldBrandApi.getPressureNetRecordPage(pressureNetPageParams)
    pressureNetRecordList.value = data.list ?? []
    pressureNetTotal.value = data.total ?? 0
  } finally {
    pressureNetLoading.value = false
  }
}

</script>
<style lang="scss" scoped>
.pressure-net-dialog-content {
  max-height: 500px;
  overflow-y: auto;
  padding: 10px;
}
</style>
