<template>
  <div class="critical-component-panel">
    <div class="critical-component-panel__header">
      <div class="critical-component-panel__title">{{ dialogTitle }}</div>
      <el-button text @click="closeForm">
        <Icon icon="ep:close" />
      </el-button>
    </div>
    <div class="critical-component-dialog" v-loading="formLoading">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <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.deviceSpec')" prop="deviceSpec">
          <el-input
            v-model="formData.deviceSpec"
            :placeholder="t('EquipmentManagement.EquipmentKeyItems.placeholderDeviceSpec')"
            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-row :gutter="16">
          <el-col :span="12" >
            <el-form-item  :label="t('EquipmentManagement.EquipmentKeyItems.qrcode')" prop="qrcodeUrl">
              <QrcodeActionCard
                :image-url="formData.qrcodeUrl"
                :print-id="formData.id"
                :print-template-type="3"
                :print-title="`${formData.name || '关键件'}码打印预览`"
                :print-paper-width="80"
                :print-paper-height="80"
                :print-max-width="220"
                :empty-text="t('EquipmentManagement.EquipmentKeyItems.qrcodeEmpty')"
                :error-text="t('EquipmentManagement.EquipmentKeyItems.qrcodeLoadError')"
                :refresh-url="getQrcodeRefreshUrl()"
                :refresh-disabled="!formData.id || !formData.code"
                refresh-confirm-text="确认刷新该关键件二维码吗？"
                :template-json="formData.templateJson"
                :print-data="buildPrintData()"
                @refresh-success="handleQrcodeRefreshSuccess"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item :label="t('EquipmentManagement.EquipmentKeyItems.images')" prop="images">
              <UploadImg style="height: 100px" v-model="formData.images" />
            </el-form-item>
          </el-col>
        </el-row>
        <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>
    </div>
    <div class="critical-component-footer">
      <el-button @click="closeForm">{{ t('common.cancel') }}</el-button>
      <el-button type="primary" @click="submitForm" :disabled="formLoading">{{ t('common.ok') }}</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { CriticalComponentApi, CriticalComponentVO } from '@/api/mes/criticalComponent'
import QrcodeActionCard from '@/components/QrcodeActionCard/index.vue'
import UploadImg from "@/components/UploadFile/src/UploadImg.vue";

defineOptions({ name: 'CriticalComponentForm' })

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

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

const formData = ref<Partial<CriticalComponentVO>>({
  id: undefined,
  code: undefined,
  isCode: undefined,
  name: undefined,
  description: undefined,
  count: undefined,
  remark: undefined,
  qrcodeUrl: undefined,
  templateJson: undefined,
  images: 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,
    templateJson: undefined,
    images: undefined
  }
  formRef.value?.resetFields?.()
}

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

const getQrcodeRefreshUrl = () => {
  if (!formData.value.id || !formData.value.code) return ''
  return `/mes/critical-component/regenerate-code?id=${formData.value.id}&code=${encodeURIComponent(String(formData.value.code))}`
}

const buildPrintData = () => {
  return {
    id: formData.value.id,
    code: formData.value.code,
    name: formData.value.name,
    description: formData.value.description,
    count: formData.value.count,
    remark: formData.value.remark,
    qrcodeUrl: formData.value.qrcodeUrl
  }
}

const handleQrcodeRefreshSuccess = async (data: any) => {
  if (!formData.value.id) return
  if (data?.qrcodeUrl) {
    formData.value.qrcodeUrl = data.qrcodeUrl
    return
  }
  const detail = await CriticalComponentApi.getCriticalComponent(formData.value.id)
  formData.value.qrcodeUrl = detail?.qrcodeUrl
  formData.value.code = detail?.code ?? formData.value.code
}

let openRequestId = 0

const open = async (type: 'create' | 'update', id?: number) => {
  const currentOpenId = ++openRequestId
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (type === 'update' && id) {
    formLoading.value = true
    try {
      const detail = await CriticalComponentApi.getCriticalComponent(id)
      if (currentOpenId !== openRequestId) return
      const templateJson = detail?.templateJson
      const parsedTemplateJson = typeof templateJson === 'string'
        ? JSON.parse(templateJson)
        : templateJson
      formData.value = {
        id: detail?.id,
        code: detail?.code,
        isCode: detail?.isCode ?? false,
        name: detail?.name,
        deviceSpec: detail?.deviceSpec,
        description: detail?.description,
        count: detail?.count,
        remark: detail?.remark,
        qrcodeUrl: detail?.qrcodeUrl,
        templateJson: parsedTemplateJson,
        images: detail?.images
      }
    } finally {
      formLoading.value = false
    }
  }
}

defineExpose({ open })

const emit = defineEmits(['success', 'closed'])

const closeForm = () => {
  openRequestId++
  emit('closed')
}

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'))
    }
    emit('success')
    closeForm()
  } finally {
    formLoading.value = false
  }
}
</script>

<style lang="scss" scoped>
.critical-component-panel {
  background: #fff;
  border-radius: 12px;
  box-shadow: var(--el-box-shadow-light);
}

.critical-component-panel__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.critical-component-panel__title {
  color: #1f2937;
  font-size: 18px;
  font-weight: 600;
}

.critical-component-dialog {
  max-height: calc(100vh - 220px);
  padding: 20px 20px 0;
  padding-right: 16px;
  overflow-y: auto;
}

.critical-component-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  width: 100%;
  padding: 16px 20px 20px;
  border-top: 1px solid #ebeef5;
}

@media (max-width: 768px) {
  .critical-component-panel__header {
    padding: 14px 16px;
  }

  .critical-component-dialog {
    max-height: none;
    padding: 16px 16px 0;
    overflow-y: visible;
  }

  .critical-component-footer {
    padding: 16px;
  }
}
</style>
