<template>
  <div>
    <el-form inline :model="searchForm" class="-mb-15px" label-width="0" @submit.prevent>
      <el-form-item>
        <el-input
          v-model="searchForm.warehouseName"
          placeholder="仓库名称"
          @keyup.enter="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleSearch"> 搜索 </el-button>
        <el-button @click="resetQuery"> 重置 </el-button>
        <el-button type="primary" @click="openForm('create', null)"> 新增 </el-button>
      </el-form-item>
    </el-form>

    <el-table class="mt-20px" :data="tableList" border>
      <el-table-column type="index" width="50px" />
      <el-table-column prop="warehouseName" label="仓库名称" />
      <el-table-column prop="sort" label="排序" />
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="操作" width="120px">
        <template #default="{ row }">
          <el-button
            type="primary"
            style="padding: 0"
            :disabled="row.type == 1"
            text
            @click="openForm('update', row.warehouseId)"
          >
            修改
          </el-button>
          <el-button
            type="danger"
            style="padding: 0"
            :disabled="row.type == 1"
            text
            @click="handleRemove(row.warehouseId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-model:limit="searchForm.pageSize"
      v-model:page="searchForm.pageNo"
      :total="total"
      @pagination="getList"
    />
    <DialogWarehouse ref="warehouseDialog" @success="handleSearch" />
  </div>
</template>

<script setup name="Warehouse">
import DialogWarehouse from './DialogWarehouse.vue'
import * as WarehouseApi from '@/api/mall/warehouse'

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

const searchForm = ref({
  warehouseName: undefined,
  pageNo: 1,
  pageSize: 20
})

const loading = ref(false)
const total = ref(0)
const tableList = ref([])

function resetQuery() {
  searchForm.value = {
    warehouseName: undefined,
    pageNo: 1,
    pageSize: 20
  }
}

function handleSearch() {
  searchForm.value.pageNo = 1
  getList()
}

async function getList() {
  loading.value = true
  try {
    const data = await WarehouseApi.getWarehousePage(searchForm.value)
    tableList.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const warehouseDialog = ref()

function openForm(type, id) {
  warehouseDialog.value.open(type, id)
}

async function handleRemove(id) {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await WarehouseApi.deleteWarehouse(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch (err) {
    console.log(err)
  }
}

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

<style lang="scss" scoped></style>
