<template>
  <div id="TradingDetailedInfoAdd" class="InfoBox" :class="{ active: dialogInfoTradingAdd }">
    <div class="header">
      <div>
        <span v-if="editor" class="title">{{ $t('Label.RefusalEditor') }}</span>
        <span v-else class="title">{{ $t('Label.AddRefusal') }}</span>
      </div>
      <span class="close crm-cursor" @click="close">
        <el-icon><Close /></el-icon>
      </span>
    </div>
    <el-form ref="formRef" :rules="rules" :model="form" label-width="150PX">
      <el-form-item prop="content" :label="$t('Label.CN') + '：'">
        <el-input v-model="form.content" :placeholder="$t('Placeholder.Input')"></el-input>
      </el-form-item>
      <el-form-item prop="enContent" :label="$t('Label.EN') + '：'">
        <el-input v-model="form.enContent" :placeholder="$t('Placeholder.Input')"></el-input>
      </el-form-item>
      <el-form-item prop="subIndex" :label="$t('Label.SubIndex') + '：'">
        <el-input v-model.trim="form.subIndex" :placeholder="$t('Placeholder.Input')"></el-input>
      </el-form-item>
    </el-form>
    <span class="btn crm-cursor" @click="confirm"
      ><span>{{ $t('Btn.Confirm') }}</span></span
    >
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch, onMounted, inject } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { FormInstance, FormRules } from 'element-plus'
  import ServiceSystem from '@/service/system'
  import Config from '@/config/index'
  import { Close } from '@element-plus/icons-vue'

  const { Code } = Config
  const { t } = useI18n()
  const Session = inject('session')
  const pigeon = inject('pigeon')

  interface Props {
    dialogInfoTradingAdd: boolean
    editor?: string
    myInfo?: any
    formList?: any
  }

  const props = withDefaults(defineProps<Props>(), {
    dialogInfoTradingAdd: false,
    editor: '',
    myInfo: null,
    formList: null,
  })

  const emit = defineEmits<{
    (e: 'update:dialogInfoTradingAdd', value: boolean): void
    (e: 'confirmToReload'): void
    (e: 'close'): void
  }>()

  // Refs
  const formRef = ref<FormInstance>()

  // Reactive data
  const form = reactive({})
  const refusalType = ref(null)
  const rules = ref<FormRules>({
    subIndex: [
      {
        required: true,
        message: t('Placeholder.Input'),
        trigger: 'blur',
      },
    ],
  })

  // Methods

  // 提交
  const confirm = () => {
    if (!formRef.value) return

    formRef.value.validate((valid) => {
      if (valid) {
        toConfirm()
      } else {
        return false
      }
    })
  }

  const toConfirm = () => {
    if (props.editor) {
      reasonsUpdate()
    } else {
      reasonsAdd()
    }
  }

  // 原因添加
  const reasonsAdd = async () => {
    try {
      // 验证表单
      if (!formRef.value) return
      const valid = await formRef.value.validate()
      if (!valid) return

      // 准备数据
      const formData = {
        type: refusalType.value,
        ...form,
        subIndex: Number(form.subIndex) || 0,
      }

      // 调用接口
      const res = await ServiceSystem.reasonsRefusalAdd(formData)

      if (res.code === Code.StatusOK) {
        emit('confirmToReload', true)
        formRef.value.resetFields()
        pigeon.success(t('Msg.Success'))
      } else {
        pigeon.error(res.msg || t('Msg.Fail'))
      }
    } catch (error) {
      console.error('添加失败:', error)
      pigeon.error(t('Msg.SystemError'))
    }
  }

  // 原因更新
  const reasonsUpdate = async () => {
    try {
      // 验证表单
      if (!formRef.value) return
      const valid = await formRef.value.validate()
      if (!valid) return

      // 准备数据
      const formData = {
        ...form,
        subIndex: Number(form.subIndex) || 0,
      }

      // 调用接口
      const res = await ServiceSystem.reasonsRefusalUpdate(formData)

      if (res.code === Code.StatusOK) {
        emit('confirmToReload', true)
        emit('closeAdd', false)
        formRef.value.resetFields()
        pigeon.success(t('Msg.Success'))
      } else {
        pigeon.error(res.msg || t('Msg.Fail'))
      }
    } catch (error) {
      console.error('更新失败:', error)
      pigeon.error(t('Msg.SystemError'))
    }
  }

  const close = () => {
    emit('update:dialogInfoTradingAdd', false)
    emit('close')
  }

  const selectChange = () => {
    // 选择变更处理
  }

  // Lifecycle
  onMounted(() => {})

  // Watch
  watch(
    () => props.formList,
    (newVal) => {
      if (newVal) {
        Object.assign(form, newVal)
      }
    },
    { immediate: true }
  )
  // Watch
  watch(
    () => props.dialogInfoTradingAdd,
    (newVal) => {
      if (!newVal && formRef.value) {
        formRef.value?.resetFields()
        Object.assign(form, {})
      }
      if (newVal) {
        refusalType.value = props.myInfo.type
      }
    },
    { immediate: true }
  )
</script>

<style scoped lang="scss"></style>
