<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item :label="t('ErpStock.WarehouseLocation.warehouseId')" prop="warehouseId">
        <el-select
          v-model="formData.warehouseId"
          :placeholder="t('ErpStock.WarehouseLocation.placeholderWarehouseId')"
          class="!w-1/1"
          @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="formData.areaId"
          :placeholder="t('ErpStock.WarehouseLocation.placeholderAreaId')"
          class="!w-1/1"
        >
          <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-row :gutter="10" class="!w-full">
          <el-col :xs="24" :sm="18" :md="16" :lg="14" :xl="12">
            <el-input v-model="formData.code" :placeholder="t('ErpStock.WarehouseLocation.placeholderCode')" :disabled="formData.isCode == true || formType === 'update'" />
          </el-col>
          <el-col :xs="24" :sm="6" :md="4" :lg="3" :xl="2">
            <div>
              <el-switch v-model="formData.isCode" :disabled="formType === 'update'" />
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item :label="t('ErpStock.WarehouseLocation.name')" prop="name">
        <el-input v-model="formData.name" :placeholder="t('ErpStock.WarehouseLocation.placeholderName')" />
      </el-form-item>
      <el-form-item :label="t('ErpStock.WarehouseLocation.areaSize')" prop="areaSize">
        <el-input-number
          v-model="formData.areaSize"
          :placeholder="t('ErpStock.WarehouseLocation.placeholderAreaSize')"
          :min="0"
          :precision="2"
          class="!w-1/1"
        />
      </el-form-item>
      <el-form-item :label="t('ErpStock.WarehouseLocation.maxLoadWeight')" prop="maxLoadWeight">
        <el-input-number
          v-model="formData.maxLoadWeight"
          :placeholder="t('ErpStock.WarehouseLocation.placeholderMaxLoadWeight')"
          :min="0"
          :precision="2"
          class="!w-1/1"
        />
      </el-form-item>
      <el-form-item :label="t('ErpStock.WarehouseLocation.positionX')" prop="positionX">
        <el-input-number
          v-model="formData.positionX"
          :placeholder="t('ErpStock.WarehouseLocation.placeholderPositionX')"
          :precision="0"
          class="!w-1/1"
        />
      </el-form-item>
      <el-form-item :label="t('ErpStock.WarehouseLocation.positionY')" prop="positionY">
        <el-input-number
          v-model="formData.positionY"
          :placeholder="t('ErpStock.WarehouseLocation.placeholderPositionY')"
          :precision="0"
          class="!w-1/1"
        />
      </el-form-item>
      <el-form-item :label="t('ErpStock.WarehouseLocation.positionZ')" prop="positionZ">
        <el-input-number
          v-model="formData.positionZ"
          :placeholder="t('ErpStock.WarehouseLocation.placeholderPositionZ')"
          :precision="0"
          class="!w-1/1"
        />
      </el-form-item>
      <el-form-item :label="t('ErpStock.WarehouseLocation.allowProductMix')" prop="allowProductMix">
        <el-switch v-model="formData.allowProductMix" />
      </el-form-item>
      <el-form-item :label="t('ErpStock.WarehouseLocation.allowBatchMix')" prop="allowBatchMix">
        <el-switch v-model="formData.allowBatchMix" />
      </el-form-item>
      <el-form-item :label="t('ErpStock.WarehouseLocation.status')" prop="status">
        <el-switch v-model="formData.status" :active-value="CommonStatusEnum.ENABLE" :inactive-value="CommonStatusEnum.DISABLE" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">{{ t('common.ok') }}</el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>

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

defineOptions({ name: 'WarehouseLocationForm' })

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

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref({
  id: undefined,
  warehouseId: undefined,
  areaId: undefined,
  code: undefined,
  name: undefined,
  areaSize: undefined,
  maxLoadWeight: undefined,
  positionX: undefined,
  positionY: undefined,
  positionZ: undefined,
  allowProductMix: false,
  allowBatchMix: false,
  status: undefined,
  isCode: true
})
const formRules = reactive({
  warehouseId: [{ required: true, message: t('ErpStock.WarehouseLocation.validatorWarehouseIdRequired'), trigger: 'blur' }],
  areaId: [{ required: true, message: t('ErpStock.WarehouseLocation.validatorAreaIdRequired'), trigger: 'blur' }],
  name: [{ required: true, message: t('ErpStock.WarehouseLocation.validatorNameRequired'), trigger: 'blur' }],
  allowProductMix: [{ required: true, message: t('ErpStock.WarehouseLocation.validatorAllowProductMixRequired'), trigger: 'blur' }],
  allowBatchMix: [{ required: true, message: t('ErpStock.WarehouseLocation.validatorAllowBatchMixRequired'), trigger: 'blur' }],
  status: [{ required: true, message: t('ErpStock.WarehouseLocation.validatorStatusRequired'), trigger: 'blur' }]
})
const formRef = ref()
const warehouseList = ref<any[]>([])
const areaList = ref<any[]>([])

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

const handleWarehouseChange = () => {
  formData.value.areaId = undefined
}

const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  warehouseList.value = await WarehouseApi.getWarehouseSimpleList()
  const areaData = await WarehouseAreaApi.getWarehouseAreaPage({ pageNo: 1, pageSize: 100 })
  areaList.value = areaData.list ?? []
  if (id) {
    formLoading.value = true
    try {
      formData.value = await WarehouseLocationApi.getWarehouseLocation(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })

const emit = defineEmits(['success'])
const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    const data = { ...formData.value } as unknown as WarehouseLocationVO
    if (data.isCode) {
      data.code = undefined
    }
    if (formType.value === 'create') {
      await WarehouseLocationApi.createWarehouseLocation(data)
      message.success(t('common.createSuccess'))
    } else {
      await WarehouseLocationApi.updateWarehouseLocation(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    warehouseId: undefined,
    areaId: undefined,
    code: undefined,
    name: undefined,
    areaSize: undefined,
    maxLoadWeight: undefined,
    positionX: undefined,
    positionY: undefined,
    positionZ: undefined,
    allowProductMix: false,
    allowBatchMix: false,
    status: CommonStatusEnum.ENABLE,
    isCode: true
  }
  formRef.value?.resetFields()
}
</script>
