<!-- ERP 仓库列表 -->
<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="auto"
    >
      <el-form-item :label="t('ErpStock.Warehouse.name')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="t('ErpStock.Warehouse.placeholderName')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('ErpStock.Warehouse.categoryType')" prop="categoryType">
        <el-select
          v-model="queryParams.categoryType"
          :placeholder="t('ErpStock.Warehouse.placeholderCategoryType')"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MATERIAL_CLASSIFICATION_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('ErpStock.Warehouse.status')" prop="status">
        <el-select
          v-model="queryParams.status"
          :placeholder="t('ErpStock.Warehouse.placeholderStatus')"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </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('FactoryModeling.FactoryStructure.collapseText') :
            t('FactoryModeling.FactoryStructure.expandText') }}
        </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')"
          v-hasPermi="['erp:warehouse:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> {{ t('action.add') }}
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:warehouse: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 width="30" :label="t('action.select')" type="selection" /> -->
      <el-table-column :label="t('ErpStock.Warehouse.name')" align="center" prop="name"  sortable />
      <el-table-column :label="t('ErpStock.Warehouse.categoryType')" align="center" prop="categoryType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MATERIAL_CLASSIFICATION_TYPE" :value="scope.row.categoryType" />
        </template>
      </el-table-column>
      <el-table-column :label="t('ErpStock.Warehouse.address')" align="center" prop="address" />
      <!-- <el-table-column
        label="仓储费"
        align="center"
        prop="warehousePrice"
        :formatter="erpPriceTableColumnFormatter"
      /> -->
      <!-- <el-table-column
        label="搬运费"
        align="center"
        prop="truckagePrice"
        :formatter="erpPriceTableColumnFormatter"
      /> -->
      <el-table-column :label="t('ErpStock.Warehouse.principal')" align="center" prop="principal" />
      <el-table-column :label="t('ErpStock.Warehouse.remark')" align="center" prop="remark" />
      <el-table-column :label="t('ErpStock.Warehouse.sort')" align="center" prop="sort" />
      <el-table-column :label="t('ErpStock.Warehouse.status')" align="center" prop="status" sortable>
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        :label="t('ErpStock.Warehouse.createTime')"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
       sortable />
      <el-table-column :label="t('common.operate')" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:warehouse:update']"
          >
            {{ t('action.edit') }}
          </el-button>
          <el-button
            link
            type="info"
            @click="openDetail(scope.row.id)"
          >
            {{ t('action.detail') }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:warehouse: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>

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

  <!-- 详情弹窗 -->
  <Dialog :title="t('action.detail')" v-model="detailDialogVisible" width="1200px">
    <div v-if="detailData">
      <el-descriptions :column="2" border>
        <el-descriptions-item :label="t('ErpStock.Warehouse.name')">{{ detailData.name }}</el-descriptions-item>
        <el-descriptions-item :label="t('ErpStock.Warehouse.categoryType')">
          <dict-tag :type="DICT_TYPE.MATERIAL_CLASSIFICATION_TYPE" :value="detailData.categoryType" />
        </el-descriptions-item>
        <el-descriptions-item :label="t('ErpStock.Warehouse.address')">{{ detailData.address }}</el-descriptions-item>
        <el-descriptions-item :label="t('ErpStock.Warehouse.principal')">{{ detailData.principal }}</el-descriptions-item>
        <el-descriptions-item :label="t('ErpStock.Warehouse.remark')">{{ detailData.remark || '-' }}</el-descriptions-item>
        <el-descriptions-item :label="t('ErpStock.Warehouse.sort')">{{ detailData.sort }}</el-descriptions-item>
        <el-descriptions-item :label="t('ErpStock.Warehouse.status')">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="detailData.status" />
        </el-descriptions-item>
      </el-descriptions>

      <el-tabs v-model="activeTab" class="mt-4">
        <el-tab-pane :label="t('ErpStock.WarehouseArea.areaName')" name="area">
          <el-table :data="detailData.areaList || []" style="width: 100%">
            <el-table-column :label="t('ErpStock.WarehouseArea.areaCode')" prop="areaCode" />
            <el-table-column :label="t('ErpStock.WarehouseArea.areaName')" prop="areaName" />
            <el-table-column :label="t('ErpStock.WarehouseArea.areaSize')" prop="areaSize" />
            <el-table-column :label="t('ErpStock.WarehouseArea.description')" prop="description" />
            <el-table-column :label="t('ErpStock.WarehouseArea.status')" 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('ErpStock.WarehouseArea.createTime')" prop="createTime" :formatter="(row) => new Date(row.createTime).toLocaleString()" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { WarehouseApi, WarehouseVO } from '@/api/erp/stock/warehouse'
import WarehouseForm from './WarehouseForm.vue'
import { erpPriceTableColumnFormatter } from '@/utils'
import { Dialog } from '@/components/Dialog'

/** ERP 仓库列表 */
defineOptions({ name: 'ErpWarehouse' })

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

const loading = ref(true) // 列表的加载中
const list = ref<WarehouseVO[]>([]) // 列表的数据
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,
  name: undefined,
  categoryType: undefined,
  status: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const showAllFilters = ref(false)
const filterCount = 2
const toggleFilters = () => {
  showAllFilters.value = !showAllFilters.value
  updatePlanTableMaxHeight()
}
const detailDialogVisible = ref(false) // 详情弹窗的是否展示
const detailData = ref<WarehouseVO | null>(null) // 详情的数据
const activeTab = ref('area') // 当前激活的tab

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await WarehouseApi.getWarehousePage(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 WarehouseApi.deleteWarehouse(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const ids = selectionList.value.map((item) => item.id).filter((v) => v != null)
    const params = {
      ...queryParams,
      ids: ids.length ? ids.join(',') : undefined
    }
    const data = await WarehouseApi.exportWarehouse(params)
    download.excel(data, t('ErpStock.Warehouse.exportName'))
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 打开详情弹窗 */
const openDetail = async (id: number) => {
  try {
    detailData.value = await WarehouseApi.getWarehouse(id)
    detailDialogVisible.value = true
  } catch (error) {
    message.error(t('common.requestError'))
  }
}

/** 选中操作 */
const selectionList = ref<WarehouseVO[]>([])
const handleSelectionChange = (rows: WarehouseVO[]) => {
  selectionList.value = rows
}

/** 初始化 **/
onMounted(() => {
  getList()
  updatePlanTableMaxHeight()
  window.addEventListener('resize', updatePlanTableMaxHeight)
})

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