<!-- 设备分类属性表单 -->
<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="DeviceAttrModelFormRules"
      label-width="100px"
    >
      <el-form-item label="属性名称" prop="name">
<!--        <el-input v-model="formData.name" placeholder="请输入属性名称"-->
<!--                  @compositionstart="handleCompositionStart"-->
<!--                  @compositionend="handleCompositionEnd"/>-->
        <lang-input v-model="formData.name" placeholder="请输入属性名称" />
      </el-form-item>
      <!--
      <el-form-item label="标识符" prop="code" >
        <el-input v-model="formData.code" placeholder="请输入标识符" disabled/>
      </el-form-item>
      -->
      <!-- 属性配置 -->
      <DeviceAttrModelProperty
        v-model="formData.selectOptions"
      />
      <el-form-item label="默认值" prop="defaultValue">
        <el-input v-model="formData.defaultValue" placeholder="请输入默认值" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="formData.description"
          :maxlength="200"
          :rows="3"
          placeholder="请输入属性描述"
          type="textarea"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import DeviceAttrModelProperty from './AttrTemplateModelProperty.vue'
import { DeviceAttrModelApi, DeviceAttrModelData } from '@/api/pms/deviceattrmodel'
import { DataSpecsDataType, DeviceAttrModelFormRules } from './config'
import pinyin from 'pinyin'
import { cloneDeep, debounce } from 'lodash-es'
import { isEmpty } from '@/utils/is'
import { defineProps } from 'vue'

/** 设备属性 模型数据表单 */
defineOptions({ name: 'AttrTemplateModelForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const isComposing = ref(false)

// 处理输入法开始事件
const handleCompositionStart = () => {
  isComposing.value = true
}

// 处理输入法结束事件
const handleCompositionEnd = (event: CompositionEvent) => {
  isComposing.value = false
  // 手动触发处理
  generateIdentifier((event.target as HTMLInputElement).value)
}

const formData = ref<DeviceAttrModelData>({
  deviceCategoryId: -1,
  dataType: DataSpecsDataType.DOUBLE,
  type: DataSpecsDataType.DOUBLE,
  requiredFlag: 0,
  code: '',
  description: '',
  defaultValue: '',
  selectOptions: {
    type: DataSpecsDataType.DOUBLE,
    defaultValue: '',
    requiredFlag: '',
    dataSpecs: {
      dataType: DataSpecsDataType.DOUBLE
    }
  },
})

const props = defineProps({
  deviceCategoryId: [String, Number]
})

const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeviceAttrModelApi.getDeviceAttrModel(id)
      // 情况一：属性初始化
      if (isEmpty(formData.value.selectOptions)) {
        formData.value.type = DataSpecsDataType.DOUBLE
        formData.value.selectOptions = {
          type: DataSpecsDataType.DOUBLE,
          dataSpecs: {
            dataType: DataSpecsDataType.DOUBLE
          }
        }
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open, close: () => (dialogVisible.value = false) })

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    const data = cloneDeep(formData.value) as DeviceAttrModelData
    data.deviceCategoryId = props.deviceCategoryId
    data.requiredFlag = formData.value.selectOptions.requiredFlag
    fillExtraAttributes(data)
    if (formType.value === 'create') {
      await DeviceAttrModelApi.createDeviceAttrModel(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeviceAttrModelApi.updateDeviceAttrModel(data)
      message.success(t('common.updateSuccess'))
    }
  } finally {
    dialogVisible.value = false // 确保关闭弹框
    emit('success')
    formLoading.value = false
  }
}

/** 填写额外的属性 */
const fillExtraAttributes = (data: any) => {
  // 处理不同类型的情况
  // 属性
  removeDataSpecs(data.selectOptions)
  data.type = data.selectOptions.type
  data.selectOptions.identifier = data.code
  data.selectOptions.code = data.code
  data.selectOptions.name = data.name
}
/** 处理 dataSpecs 为空的情况 */
const removeDataSpecs = (val: any) => {
  if (isEmpty(val.dataSpecs)) {
    delete val.dataSpecs
  }
  if (isEmpty(val.dataSpecsList)) {
    delete val.dataSpecsList
  }
}

// 处理属性名称生成标识符
const processInputName = (name: string) => {
  let result = ''
  for (const char of name) {
    // 汉字转拼音首字母
    if (/[\u4e00-\u9fa5]/.test(char)) {
      const pinyinArray = pinyin(char, {
        style: pinyin.STYLE_FIRST_LETTER
      })
      if (pinyinArray[0]?.[0]) {
        result += pinyinArray[0][0].toUpperCase()
      }
    }
    // 非汉字字符原样保留
    else {
      result += char
    }
  }
  return result
}

// 中文首字母提取方法
const getChineseInitials = (name: string) => {
  const chineseChars = name.match(/[\u4e00-\u9fa5]/g) || []
  if (chineseChars.length === 0) return ''

  const pinyinArray = pinyin(chineseChars.join(''), {
    style: pinyin.STYLE_FIRST_LETTER,
  })
  return pinyinArray.map(arr => arr[0]?.charAt(0).toUpperCase()).join('')
}

// 生成标识符方法
const generateIdentifier = debounce((name: string) => {
  /* if (formData.value.code)  return */

  const initials = processInputName(name)
  if (initials) {
    formData.value.code = `${initials}_${Date.now()}`
  }
}, 800)

// 监听属性名称变化
watchEffect(() => {
  if (formData.value.name && !isComposing.value) {
    generateIdentifier(formData.value.name)
  }
})

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    dataType: DataSpecsDataType.DOUBLE,
    type: DataSpecsDataType.DOUBLE,
    code: '',
    selectOptions: {
      type: DataSpecsDataType.DOUBLE,
      dataSpecs: {
        dataType: DataSpecsDataType.DOUBLE
      }
    },
  }
  formRef.value?.resetFields()
}

onMounted(async () => {
  // 如果不修改 属性名称 不要自动生成新标识符
  isComposing.value = true
})
</script>
