<template>
  <div id="TradingDetailedInfoAdd" class="InfoBox" :class="{ active: dialogInfoTradingAdd }">
    <div class="header">
      <div>
        <span class="title">{{ t('R-Recharge-Btn3') }}</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="120PX">
      <el-form-item :label="t('Ucard.KycAuth.item8') + '：'">
        <el-input v-model="form.cId" disabled placeholder=""></el-input>
      </el-form-item>
      <el-form-item :label="t('Ucard.KycAuth.item9') + '：'">
        <el-row gutter="10">
          <el-col :span="12">
            <el-input v-model="form.lastName" disabled></el-input>
          </el-col>
          <el-col :span="12">
            <el-input v-model="form.firstName" disabled></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item :label="t('Ucard.KycAuth.item10') + '：'">
        <el-input v-model="form.email" disabled placeholder=""></el-input>
      </el-form-item>
      <el-form-item :label="t('Ucard.KycAuth.item11') + '：'">
        <el-input v-model="form.mobile" disabled placeholder=""></el-input>
      </el-form-item>
      <el-form-item prop="status" :label="t('Label.CheckResults') + '：'">
        <el-select
          v-model="form.status"
          class="crm_search_down"
          :placeholder="t('Placeholder.Choose')"
        >
          <el-option :label="t('Apply_info.VerifiedUser.Agree')" :value="2"></el-option>
          <el-option :label="t('Apply_info.VerifiedUser.Refused')" :value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="form.status == 3" prop="approveDesc" :label="t('Label.Descr') + '：'">
        <el-select
          v-model="form.approveDesc"
          filterable
          class="crm_search_down"
          :placeholder="t('Placeholder.Choose')"
          allow-create
        >
          <el-option
            v-for="item in reasons"
            :key="item.id"
            :label="Session.Get('lang') == 'cn' ? item.content : item.enContent"
            :value="item.id"
          ></el-option>
        </el-select>
      </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, inject, onMounted } from 'vue'
  import { useI18n } from 'vue-i18n'
  import type { FormInstance, FormRules } from 'element-plus'
  import Service2 from '@/service/apply'
  import Service from '@/service/ucard'
  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>()
  const reasons = ref([])
  // Reactive data
  const form = reactive({})
  const rules = ref<FormRules>({
    status: [
      {
        required: true,
        message: t('vaildate.select.empty'),
        trigger: 'blur',
      },
    ],
  })

  const user = computed(() => {
    return JSON.parse(Session.Get('user', true))
  })
  // Methods

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

    formRef.value.validate((valid) => {
      if (valid) {
        toConfirm()
      } else {
        return false
      }
    })
  }
  // 审核充值
  const rechargeApprove = async () => {
    try {
      const res = await Service.rechargeApprove({
        cardTypeId: form.cardTypeId,
        cardNumber: form.cardNumber,
        uniqueId: form.uniqueId,
        approveDesc: form.approveDesc,
        approveStatus: form.status,
        ids: [form.id],
        cId: user.value.cId,
      })

      if (res.code == Code.StatusOK) {
        ElMessage.success(t('Msg.Success12'))
        confirmToReload()
      } else {
        ElMessage.error(res.msg)
      }
    } catch (error) {
      console.error('充值审核失败:', error)
      ElMessage.error(t('Msg.SystemError'))
    }
  }

  const toConfirm = () => {
    Object.assign(form, {
      cardNumber: form.cardNumber.replace(/\s+/g, ''),
    })
    rechargeApprove()
  }

  const close = () => {
    emit('update:dialogInfoTradingAdd', false)
    emit('close')
  }
  // 获取原因列表
  const searchReasons = async () => {
    try {
      const res = await Service2.reasonsRefusalList({ type: 15 })

      if (res.code == Code.StatusOK) {
        reasons.value = res.data || {}
      } else {
        ElMessage.error(res.msg)
      }
    } catch (error) {
      console.error('获取原因列表失败:', error)
      ElMessage.error(t('Msg.SystemError'))
    }
  }
  onMounted(() => {
    searchReasons()
  })

  // Watch
  watch(
    () => props.formList,
    (newVal) => {
      if (newVal) {
        console.log(newVal)
        Object.assign(form, {
          ...newVal,
          status: '',
        })
      }
    },
    { immediate: true }
  )
  // Watch
  watch(
    () => props.dialogInfoTradingAdd,
    (newVal) => {
      if (!newVal && formRef.value) {
        console.log(1)
        formRef.value?.resetFields()
        Object.assign(form, {})
      }
    },
    { immediate: true }
  )
</script>

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