<!-- ERP 产品列表 -->
<template>


  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item :label="t('SparePartsManagement.SpareInfo.name')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="t('SparePartsManagement.SpareInfo.placeholderName')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </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="['erp:product:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> {{ t('action.add') }}
        </el-button>
        <el-button
          type="warning"
          plain
          @click="openImport"
          v-hasPermi="['erp:product:import']"
        >
          <Icon icon="ep:upload" class="mr-5px" /> {{ t('action.import') }}
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:product: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">
      <el-table-column :label="t('SparePartsManagement.SpareInfo.code')" align="center" prop="barCode" />
      <el-table-column :label="t('SparePartsManagement.SpareInfo.name')" align="left" prop="name"  width="220px"/>
      <el-table-column v-if="checkPermi(['erp:component:standard'])" :label="t('SparePartsManagement.SpareInfo.standard')" align="center" prop="standard" />
      <el-table-column :label="t('SparePartsManagement.SpareInfo.category')" align="center" prop="categoryName" />
      <el-table-column :label="t('SparePartsManagement.SpareInfo.unit')" align="center" prop="unitName" />
      <el-table-column :label="t('SparePartsManagement.SpareInfo.safetyNumber')" align="center" prop="safetyNumber" />
      <el-table-column :label="t('SparePartsManagement.SpareInfo.status')" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        :label="t('SparePartsManagement.SpareInfo.createTime')"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column :label="t('SparePartsManagement.SpareInfo.operate')" align="center" width="150px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:product:update']"
          >
            {{ t('action.edit') }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:product: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>

  <!-- 表单弹窗：添加/修改 -->
  <ProductForm ref="formRef" @success="getList" />

  <Dialog v-model="importDialogVisible" :title="t('action.import')" width="400">
    <el-upload
      ref="uploadRef"
      v-model:file-list="importFileList"
      :action="importUrl + '?updateSupport=' + updateSupport"
      :auto-upload="false"
      :disabled="importLoading"
      :headers="uploadHeaders"
      :limit="1"
      :on-error="handleImportError"
      :on-exceed="handleImportExceed"
      :on-success="handleImportSuccess"
      accept=".xlsx, .xls"
      drag
    >
      <Icon icon="ep:upload" />
      <div class="el-upload__text">
        将文件拖到此处，或点击上传
      </div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <div class="el-upload__tip">
            <el-checkbox v-model="updateSupport" />
            是否更新已存在的数据
          </div>
          <span>仅支持 .xlsx, .xls 格式</span>
          <el-link
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            type="primary"
            @click="importTemplate"
          >
            下载导入模板
          </el-link>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button :disabled="importLoading" type="primary" @click="submitImport">{{ t('common.ok') }}</el-button>
      <el-button @click="importDialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { ProductCategoryApi, ProductCategoryVO } from '@/api/erp/product/category'
import ProductForm from './ProductForm.vue'
import { DICT_TYPE } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import { erpPriceTableColumnFormatter } from '@/utils'
import BomForm from '@/views/mes/bom/BomForm.vue'
import { checkPermi } from '@/utils/permission'
import { getAccessToken, getTenantId } from '@/utils/auth'

/** ERP 产品列表 */
defineOptions({ name: 'ErpProduct' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ProductVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  categoryId: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const importDialogVisible = ref(false)
const importLoading = ref(false)
const uploadRef = ref()
const importUrl =
  import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/erp/product/import'
const uploadHeaders = ref()
const importFileList = ref([])
const updateSupport = ref(0)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    queryParams.categoryId = 5
    const data = await ProductApi.getProductPage(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 formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

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

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ProductApi.exportProduct(queryParams)
    download.excel(data, t('SparePartsManagement.SpareInfo.exportFilename'))
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const openImport = () => {
  importDialogVisible.value = true
  importLoading.value = false
  importFileList.value = []
  updateSupport.value = 0
}

const submitImport = async () => {
  if (importFileList.value.length === 0) {
    message.error('请选择导入文件')
    return
  }
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    tenantId: getTenantId()
  }
  importLoading.value = true
  uploadRef.value?.submit()
}

const handleImportSuccess = (response: any) => {
  if (!response || response.code !== 0) {
    message.error(response?.msg || '导入失败')
    importLoading.value = false
    return
  }
  message.success('导入成功')
  importLoading.value = false
  importDialogVisible.value = false
  getList()
}

const handleImportError = () => {
  message.error('导入失败')
  importLoading.value = false
}

const handleImportExceed = () => {
  message.error('只能上传一个文件')
}

const importTemplate = async () => {
  const res = await ProductApi.importProductTemplate()
  download.excel(res, '产品导入模板.xls')
}

/** 初始化 **/
onMounted(async () => {
  queryParams.categoryId = 2
  await getList()
})
</script>
