<template>
  <div class="dv-repair-panel">
    <div class="dv-repair-panel__header">
      <div class="dv-repair-panel__title">{{ dialogTitle }}</div>
      <el-button text @click="closeForm">
        <Icon icon="ep:close" />
      </el-button>
    </div>
    <div class="dv-repair-dialog" v-loading="formLoading">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item :label="t('FactoryModeling.AutocodeRule.dialogRuleCodeLabel')" prop="ruleCode">
          <el-input
            v-model="formData.ruleCode"
            :placeholder="t('FactoryModeling.AutocodeRule.dialogRuleCodePlaceholder')"
            :disabled="formType == 'update'"
          />
        </el-form-item>
        <el-form-item :label="t('FactoryModeling.AutocodeRule.dialogRuleNameLabel')" prop="ruleName">
          <el-input
            v-model="formData.ruleName"
            :placeholder="t('FactoryModeling.AutocodeRule.dialogRuleNamePlaceholder')"
          />
        </el-form-item>
        <el-form-item :label="t('FactoryModeling.AutocodeRule.dialogBarcodeTypeLabel')" prop="barcodeType">
          <el-radio-group v-model="formData.barcodeType">
            <el-radio :label="1">{{ t('FactoryModeling.AutocodeRule.barcodeTypeBarcodeLabel') }}</el-radio>
            <el-radio :label="2">{{ t('FactoryModeling.AutocodeRule.barcodeTypeQrcodeLabel') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="t('FactoryModeling.AutocodeRule.dialogRuleDescLabel')" prop="ruleDesc">
          <el-input
            v-model="formData.ruleDesc"
            :placeholder="t('FactoryModeling.AutocodeRule.dialogRuleDescPlaceholder')"
          />
        </el-form-item>
        <el-form-item :label="t('FactoryModeling.AutocodeRule.dialogMaxLengthLabel')" prop="maxLength">
          <el-input
            v-model="formData.maxLength"
            :placeholder="t('FactoryModeling.AutocodeRule.dialogMaxLengthPlaceholder')"
          />
        </el-form-item>
        <el-form-item :label="t('FactoryModeling.AutocodeRule.dialogIsPaddedLabel')" prop="isPadded">
          <el-radio-group v-model="formData.isPadded">
            <el-radio
              v-for="dict in getStrDictOptions(DICT_TYPE.ERP_AUTOCODE_IS_PADDING)"
              :key="dict.value"
              :label="dict.value"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="t('FactoryModeling.AutocodeRule.dialogPaddedCharLabel')" prop="paddedChar">
          <el-input
            v-model="formData.paddedChar"
            :placeholder="t('FactoryModeling.AutocodeRule.dialogPaddedCharPlaceholder')"
          />
        </el-form-item>
        <el-form-item :label="t('FactoryModeling.AutocodeRule.dialogPaddedMethodLabel')" prop="paddedMethod">
          <el-radio-group v-model="formData.paddedMethod">
            <el-radio
              v-for="dict in getStrDictOptions(DICT_TYPE.ERP_AUTOCODE_PADDING_TYPE)"
              :key="dict.value"
              :label="dict.value"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="t('FactoryModeling.AutocodeRule.dialogRemarkLabel')" prop="remark">
          <el-input
            v-model="formData.remark"
            :placeholder="t('FactoryModeling.AutocodeRule.dialogRemarkPlaceholder')"
            type="textarea"
          />
        </el-form-item>
        <el-form-item :label="t('FactoryModeling.AutocodeRule.dialogIsEnableLabel')" prop="isEnable">
          <el-radio-group v-model="formData.isEnable">
            <el-radio
              v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
              :key="dict.value"
              :label="dict.value"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 子表的表单 -->
      <el-tabs v-model="subTabsName">
        <el-tab-pane :label="t('FactoryModeling.AutocodeRule.dialogPartTabLabel')" name="autocodePart">
          <AutocodePartForm ref="autocodePartFormRef" :rule-id="formData.id" />
        </el-tab-pane>
      </el-tabs>
    </div>

    <div class="dv-repair-footer">
      <el-button @click="closeForm">{{ t('common.cancel') }}</el-button>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">{{ t('common.ok') }}</el-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { getStrDictOptions, getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { AutocodeRuleApi, AutocodeRuleVO } from '@/api/erp/autocode'
import AutocodePartForm from './components/AutocodePartForm.vue'

/** 编码规则 表单 */
defineOptions({ name: 'AutocodeRuleForm' })

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

const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref({
  id: undefined,
  ruleCode: undefined,
  ruleName: undefined,
  barcodeType: 1,
  ruleDesc: undefined,
  maxLength: undefined,
  isPadded: undefined,
  paddedChar: undefined,
  paddedMethod: undefined,
  remark: undefined,
  isEnable: undefined
})
const formRules = reactive({
  isEnable: [
    { required: true, message: t('FactoryModeling.AutocodeRule.validatorIsEnableRequired'), trigger: 'blur' }
  ]
})
const formRef = ref()

/** 子表的表单 */
const subTabsName = ref('autocodePart')
const autocodePartFormRef = ref()

let openRequestId = 0

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  const currentOpenId = ++openRequestId
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      const data = await AutocodeRuleApi.getAutocodeRule(id)
      const barcodeType = Number(data?.barcodeType ?? data?.barCodeType) === 2 ? 2 : 1
      formData.value = {
        ...data,
        barcodeType
      }
    } finally {
      formLoading.value = false
    }
  }
}

defineExpose({ open })

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

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

onBeforeUnmount(() => {
  openRequestId++
})

/** 提交表单 */
const submitForm = async () => {
  await formRef.value.validate()
  try {
    await autocodePartFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'autocodePart'
    return
  }
  formLoading.value = true
  try {
    const barcodeType = Number(formData.value.barcodeType) === 2 ? 2 : 1
    const data = {
      ...formData.value,
      barcodeType,
      barCodeType: barcodeType
    } as unknown as AutocodeRuleVO
    data.autocodeParts = autocodePartFormRef.value.getData()
    if (formType.value === 'create') {
      await AutocodeRuleApi.createAutocodeRule(data)
      message.success(t('common.createSuccess'))
    } else {
      await AutocodeRuleApi.updateAutocodeRule(data)
      message.success(t('common.updateSuccess'))
    }
    emit('success')
    closeForm()
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    ruleCode: undefined,
    ruleName: undefined,
    barcodeType: 1,
    ruleDesc: undefined,
    maxLength: undefined,
    isPadded: undefined,
    paddedChar: undefined,
    paddedMethod: undefined,
    remark: undefined,
    isEnable: true
  }
  formRef.value?.resetFields()
}
</script>

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

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

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

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

.dv-repair-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 12px;
  width: 100%;
  padding: 16px 20px 20px;
  border-top: 1px solid #ebeef5;
}

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

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

  .dv-repair-footer {
    padding: 16px;
  }
}
</style>
