<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="720px">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="编码" prop="code">
            <el-row :gutter="20" style="width: 100%">
              <el-col :span="18">
                <el-input v-model="formData.code" placeholder="请输入型号编码" :disabled="Boolean(formData.isCode) || formType === 'update'" />
              </el-col>
              <el-col :span="6">
                <div>
                  <el-switch v-model="formData.isCode" :disabled="formType === 'update'" @change="handleCodeAutoChange" />
                </div>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入型号名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品型号" prop="productId">
            <el-select v-model="formData.productId" filterable clearable placeholder="请选择产品型号" class="w-1/1" @change="handleProductChange">
              <el-option v-for="item in productList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="版本" prop="version">
            <el-input v-model="formData.version" placeholder="请输入版本号，如1.0" @input="handleVersionInput" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择状态" class="w-1/1">
              <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="模穴数" prop="moldSize">
            <el-input-number v-model="formData.moldSize" :min="1" :precision="0" class="w-1/1" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预期寿命" prop="useTime">
            <el-input-number v-model="formData.useTime" :min="0" class="w-1/1" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="图片" prop="images">
            <UploadImg v-model="formData.images" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="是否启用" prop="isEnable">
            <el-radio-group v-model="formData.isEnable">
              <el-radio :label="true">启用</el-radio>
              <el-radio :label="false">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">保存</el-button>
      <el-button @click="dialogVisible = false">关闭</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { MoldBrandApi, type MoldBrandVO } from '@/api/erp/mold'
import { ProductApi, type ProductVO } from '@/api/erp/product/product'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { useDictStoreWithOut } from '@/store/modules/dict'

defineOptions({ name: 'MoldBrandForm' })

const message = useMessage()
const dictStore = useDictStoreWithOut()
const productList = ref<ProductVO[]>([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formRef = ref()
const statusOptions = computed(() => getIntDictOptions(DICT_TYPE.ERP_MOLD_STATUS))
const formData = ref<MoldBrandVO>({
  id: undefined as unknown as number,
  code: '',
  name: '',
  moldType: '',
  productId: undefined,
  productName: '',
  productIds: [],
  images: '',
  version: '',
  status: 0,
  useTime: 0,
  maintainType: undefined,
  maintainTime: undefined,
  moldSize: 1,
  remark: '',
  isEnable: true,
  isCode: true
})

const validateCode = (_rule: any, value: any, callback: any) => {
  if (Boolean(formData.value.isCode)) {
    callback()
    return
  }
  if (value === undefined || value === null || String(value).trim() === '') {
    callback(new Error('型号编码不能为空'))
    return
  }
  callback()
}

const handleCodeAutoChange = (value: boolean) => {
  if (value) {
    formData.value.code = ''
  }
  formRef.value?.clearValidate('code')
}

const handleVersionInput = (value: string) => {
  formData.value.version = value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1')
}

const stripVersionPrefix = (val: any): string => {
  if (!val) return ''
  return String(val).replace(/^V/i, '')
}

const addVersionPrefix = (val: any): string => {
  if (!val) return ''
  const raw = String(val).replace(/^V/i, '')
  return raw ? `V${raw}` : ''
}

const formRules = reactive({
  code: [{ validator: validateCode, trigger: 'blur' }],
  name: [{ required: true, message: '型号名称不能为空', trigger: 'blur' }],
  moldType: [{ required: true, message: '模具类型不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '产品型号不能为空', trigger: 'change' }],
  moldSize: [{ required: true, message: '模穴数不能为空', trigger: 'blur' }],
  isEnable: [{ required: true, message: '请选择启用状态', trigger: 'change' }]
})

const resetForm = () => {
  formData.value = {
    id: undefined as unknown as number,
    code: '',
    name: '',
    moldType: '',
    productId: undefined,
    productName: '',
    productIds: [],
    images: '',
    version: '',
    status: 0,
    useTime: 0,
    maintainType: undefined,
    maintainTime: undefined,
    moldSize: 1,
    remark: '',
    isEnable: true,
    isCode: true
  }
  formRef.value?.resetFields()
}

const handleProductChange = (value?: number) => {
  const current = productList.value.find((item) => item.id === value)
  formData.value.productName = current?.name || ''
  formData.value.productIds = value ? [value] : []
}

const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '新增模具组' : '编辑模具组'
  formType.value = type
  resetForm()
  await dictStore.setDictMap()
  productList.value = await ProductApi.getMesProductSimpleList()
  if (!id) return
  formLoading.value = true
  try {
    const data = await MoldBrandApi.getMoldBrand(id)
    formData.value = {
      ...formData.value,
      ...data,
      isCode: (data as any)?.isCode ?? false,
      version: stripVersionPrefix(data?.version),
      productIds: Array.isArray(data?.productIds)
        ? data.productIds
        : data?.productId
          ? [data.productId]
          : []
    }
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open })

const emit = defineEmits(['success'])

const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    handleProductChange(formData.value.productId)
    const payload: MoldBrandVO = {
      ...formData.value,
      version: addVersionPrefix(formData.value.version),
      productIds: Array.isArray(formData.value.productIds)
        ? formData.value.productIds
        : formData.value.productId
          ? [formData.value.productId]
          : [],
      isEnable: Boolean(formData.value.isEnable)
    }
    if (formType.value === 'create') {
      await MoldBrandApi.createMoldBrand(payload)
      message.success('新增成功')
    } else {
      await MoldBrandApi.updateMoldBrand(payload)
      message.success('更新成功')
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>
