<template>
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="auto"
    >
      <el-form-item :label="t('ErpStock.WarehouseLocation.warehouseId')" prop="warehouseId">
        <el-select
          v-model="queryParams.warehouseId"
          :placeholder="t('ErpStock.WarehouseLocation.placeholderWarehouseId')"
          clearable
          class="!w-240px"
          @change="handleWarehouseChange"
        >
          <el-option
            v-for="item in warehouseList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('ErpStock.WarehouseLocation.areaId')" prop="areaId">
        <el-select
          v-model="queryParams.areaId"
          :placeholder="t('ErpStock.WarehouseLocation.placeholderAreaId')"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="item in filteredAreaList"
            :key="item.id"
            :label="item.areaName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('ErpStock.WarehouseLocation.code')" prop="code">
        <el-input
          v-model="queryParams.code"
          :placeholder="t('ErpStock.WarehouseLocation.placeholderCode')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('ErpStock.WarehouseLocation.name')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="t('ErpStock.WarehouseLocation.placeholderName')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('ErpStock.WarehouseLocation.status')" prop="status">
        <el-select
          v-model="queryParams.status"
          :placeholder="t('ErpStock.WarehouseLocation.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>
        <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-location:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> {{ t('action.add') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      row-key="id"
    >
      <el-table-column :label="t('ErpStock.WarehouseLocation.warehouseId')" align="center" prop="warehouseId" sortable>
        <template #default="scope">
          {{ getWarehouseName(scope.row.warehouseId) }}
        </template>
      </el-table-column>
      <el-table-column :label="t('ErpStock.WarehouseLocation.areaId')" align="center" prop="areaId" sortable>
        <template #default="scope">
          {{ getAreaName(scope.row.areaId) }}
        </template>
      </el-table-column>
      <el-table-column :label="t('ErpStock.WarehouseLocation.code')" align="center" prop="code" sortable />
      <el-table-column :label="t('ErpStock.WarehouseLocation.name')" align="center" prop="name" sortable />
      <el-table-column :label="t('ErpStock.WarehouseLocation.areaSize')" align="center" prop="areaSize" />
      <el-table-column :label="t('ErpStock.WarehouseLocation.maxLoadWeight')" align="center" prop="maxLoadWeight" />
      <el-table-column :label="t('ErpStock.WarehouseLocation.position')" align="center">
        <template #default="scope">
          {{ scope.row.positionX ?? '-' }}, {{ scope.row.positionY ?? '-' }}, {{ scope.row.positionZ ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column :label="t('ErpStock.WarehouseLocation.allowProductMix')" align="center" prop="allowProductMix">
        <template #default="scope">
          <el-tag :type="scope.row.allowProductMix ? 'success' : 'danger'" size="small">
            {{ scope.row.allowProductMix ? t('common.yes') : t('common.no') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="t('ErpStock.WarehouseLocation.allowBatchMix')" align="center" prop="allowBatchMix">
        <template #default="scope">
          <el-tag :type="scope.row.allowBatchMix ? 'success' : 'danger'" size="small">
            {{ scope.row.allowBatchMix ? t('common.yes') : t('common.no') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="t('ErpStock.WarehouseLocation.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.WarehouseLocation.createTime')" align="center" prop="createTime" :formatter="dateFormatter" width="180px" sortable />
      <el-table-column :label="t('common.operate')" align="center" width="150px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:warehouse-location:update']"
          >
            {{ t('action.edit') }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:warehouse-location: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>

  <WarehouseLocationForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { WarehouseLocationApi, WarehouseLocationVO } from '@/api/erp/stock/warehouselocation'
import { WarehouseApi } from '@/api/erp/stock/warehouse'
import { WarehouseAreaApi } from '@/api/erp/stock/warehousearea'
import WarehouseLocationForm from './WarehouseLocationForm.vue'

defineOptions({ name: 'ErpWarehouseLocation' })

const message = useMessage()
const { t } = useI18n()

const loading = ref(true)
const list = ref<WarehouseLocationVO[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  warehouseId: undefined,
  areaId: undefined,
  code: undefined,
  name: undefined,
  status: undefined
})
const queryFormRef = ref()
const warehouseList = ref<any[]>([])
const areaList = ref<any[]>([])

const filteredAreaList = computed(() => {
  if (!queryParams.warehouseId) return areaList.value
  return areaList.value.filter((item) => item.warehouseId === queryParams.warehouseId)
})

const getWarehouseName = (warehouseId: number) => {
  return warehouseList.value.find((w) => w.id === warehouseId)?.name ?? '-'
}

const getAreaName = (areaId: number) => {
  return areaList.value.find((a) => a.id === areaId)?.areaName ?? '-'
}

const getList = async () => {
  loading.value = true
  try {
    const data = await WarehouseLocationApi.getWarehouseLocationPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const getWarehouseList = async () => {
  warehouseList.value = await WarehouseApi.getWarehouseSimpleList()
}

const getAreaList = async () => {
  const data = await WarehouseAreaApi.getWarehouseAreaPage({ pageNo: 1, pageSize: 100 })
  areaList.value = data.list ?? []
}

const handleWarehouseChange = () => {
  queryParams.areaId = undefined
}

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 WarehouseLocationApi.deleteWarehouseLocation(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

onMounted(() => {
  getWarehouseList()
  getAreaList()
  getList()
})
</script>
