<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="720px">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" v-loading="formLoading">
      <el-form-item :label="t('EquipmentManagement.EquipmentKeyItems.code')" prop="code">
        <el-row :gutter="10" style="width: 100%">
          <el-col :xs="24" :sm="18" :md="16" :lg="14" :xl="12">
            <el-input
              v-model="formData.code"
              :placeholder="t('EquipmentManagement.EquipmentKeyItems.placeholderCode')"
              clearable
              :disabled="Boolean(formData.isCode) || 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'"
                @change="handleCodeAutoChange"
              />
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.EquipmentKeyItems.name')" prop="name">
        <el-input
          v-model="formData.name"
          :placeholder="t('EquipmentManagement.EquipmentKeyItems.placeholderName')"
          clearable
        />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.EquipmentKeyItems.description')" prop="description">
        <el-input
          v-model="formData.description"
          :placeholder="t('EquipmentManagement.EquipmentKeyItems.placeholderDescription')"
          clearable
          type="textarea"
        />
      </el-form-item>
        <el-form-item :label="t('EquipmentManagement.EquipmentKeyItems.count')" prop="count">
        <el-input
          v-model="formData.count"
          :placeholder="t('EquipmentManagement.EquipmentKeyItems.placeholderCount')"
          clearable
          type="number"
        />
      </el-form-item>
      <el-form-item v-if="formType === 'update'" :label="t('EquipmentManagement.EquipmentKeyItems.qrcode')" prop="qrcodeUrl">
        <div class="critical-component-qrcode-wrap">
          <el-image
            v-if="formData.qrcodeUrl"
            :src="formData.qrcodeUrl"
            :preview-src-list="[formData.qrcodeUrl]"
            preview-teleported
            fit="cover"
            class="critical-component-qrcode-img"
          >
            <template #error>
              <div class="critical-component-qrcode-error">{{ t('EquipmentManagement.EquipmentKeyItems.qrcodeLoadError') }}</div>
            </template>
          </el-image>
          <div v-else class="critical-component-qrcode-error">{{ t('EquipmentManagement.EquipmentKeyItems.qrcodeEmpty') }}</div>
          <div class="critical-component-qrcode-mask">
            <el-button
              circle
              :disabled="!formData.qrcodeUrl"
              @click="handlePreviewQrcode"
            >
              <Icon icon="ep:zoom-in" />
            </el-button>
            <el-button
              circle
              :loading="regenerateCodeLoading"
              :disabled="regenerateCodeLoading"
              @click="handleRegenerateCode"
            >
              <Icon icon="ep:refresh" />
            </el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.EquipmentKeyItems.remark')" prop="remark">
        <el-input
          v-model="formData.remark"
          :placeholder="t('EquipmentManagement.EquipmentKeyItems.placeholderRemark')"
          clearable
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
      <el-button type="primary" @click="submitForm" :disabled="formLoading">{{ t('common.ok') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { CriticalComponentApi, CriticalComponentVO } from '@/api/mes/criticalComponent'
import { createImageViewer } from '@/components/ImageViewer'

defineOptions({ name: 'CriticalComponentForm' })

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

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref<'create' | 'update'>('create')
const regenerateCodeLoading = ref(false)
const formRef = ref()

const formData = ref<Partial<CriticalComponentVO>>({
  id: undefined,
  code: undefined,
  isCode: undefined,
  name: undefined,
  description: undefined,
  count: undefined,
  remark: undefined,
  qrcodeUrl: undefined
})

const validateCode = (_rule, value, callback) => {
  if (Boolean(formData.value.isCode)) {
    callback()
    return
  }
  if (value === undefined || value === null || String(value).trim() === '') {
    callback(new Error(t('EquipmentManagement.EquipmentKeyItems.validatorCodeRequired')))
    return
  }
  callback()
}

const formRules = reactive({
  code: [{ validator: validateCode, trigger: ['blur', 'change'] }],
  name: [{ required: true, message: t('EquipmentManagement.EquipmentKeyItems.validatorNameRequired'), trigger: 'blur' }]
})

const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    isCode: true,
    name: undefined,
    description: undefined,
    count: undefined,
    remark: undefined,
    qrcodeUrl: undefined
  }
  formRef.value?.resetFields?.()
}

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

const handleRegenerateCode = async () => {
  if (!formData.value.id || !formData.value.code) return
  regenerateCodeLoading.value = true
  try {
    const data = await CriticalComponentApi.regenerateCode(formData.value.id, formData.value.code)
    if (data?.qrcodeUrl) {
      formData.value.qrcodeUrl = data.qrcodeUrl
    } else {
      const detail = await CriticalComponentApi.getCriticalComponent(formData.value.id)
      formData.value.qrcodeUrl = detail?.qrcodeUrl
      formData.value.code = detail?.code ?? formData.value.code
    }
    message.success(t('common.updateSuccess'))
  } finally {
    regenerateCodeLoading.value = false
  }
}

const handlePreviewQrcode = () => {
  if (!formData.value.qrcodeUrl) return
  createImageViewer({
    zIndex: 9999999,
    urlList: [formData.value.qrcodeUrl]
  })
}

const open = async (type: 'create' | 'update', id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (type === 'update' && id) {
    formLoading.value = true
    try {
      const detail = await CriticalComponentApi.getCriticalComponent(id)
      formData.value = {
        id: detail?.id,
        code: detail?.code,
        isCode: detail?.isCode ?? false,
        name: detail?.name,
        description: detail?.description,
        count: detail?.count,
        remark: detail?.remark,
        qrcodeUrl: detail?.qrcodeUrl
      }
    } finally {
      formLoading.value = false
    }
  }
}

defineExpose({ open })

const emit = defineEmits(['success'])

const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    if (formType.value === 'create') {
      await CriticalComponentApi.createCriticalComponent(formData.value)
      message.success(t('common.createSuccess'))
    } else {
      await CriticalComponentApi.updateCriticalComponent(formData.value)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>
<style scoped lang="scss">
.critical-component-qrcode-wrap {
  position: relative;
  height: 150px;
  width: fit-content;
  min-width: 150px;
  border-radius: 10px;
  overflow: hidden;
  border: 1px solid var(--el-border-color-lighter);
  background: var(--el-fill-color-blank);
}

.critical-component-qrcode-img {
  height: 150px;
  width: auto;
  display: block;
}

.critical-component-qrcode-error {
  height: 150px;
  min-width: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--el-text-color-secondary);
  font-size: 12px;
  padding: 0 12px;
}

.critical-component-qrcode-mask {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  background: rgba(0, 0, 0, 0.35);
  opacity: 0;
  transition: opacity 0.2s ease;
}

.critical-component-qrcode-wrap:hover .critical-component-qrcode-mask {
  opacity: 1;
}
</style>
