<template>
  <el-drawer
    v-model="visible"
    :title="addType === 'kyc_upload' ? '上传KYC附件' : $t('Marketing.Email')"
    :size="'25%'"
    :before-close="close"
    class="review-email-drawer"
    :wrapper-closable="true"
    :modal-append-to-body="false"
    :append-to-body="true"
  >
    <div class="drawer-content">
      <el-form
        ref="formRef"
        :rules="rules"
        :model="form"
        label-width="120px"
        class="review-email-form"
      >
        <template v-if="addType === 'kyc_upload'">
          <el-form-item :label="$t('Ucard.Business.t8')" required>
            <el-select
              v-model="form.kycUploadForm.type"
              :placeholder="$t('Ucard.Business.t9')"
              style="width: 100%"
            >
              <el-option :label="$t('Ucard.Business.t10')" :value="1" />
              <el-option :label="$t('Ucard.Business.t11')" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('Ucard.Business.t12')" required>
            <el-upload
              class="custom-upload-rect full-width-upload"
              :http-request="handleKycFileUpload"
              :show-file-list="false"
              :before-upload="() => true"
              :action="Config.Host85 + '/ucard/upload/file'"
              list-type="text"
            >
              <template v-if="!form.kycUploadForm.data">
                <div class="custom-upload-rect-trigger">
                  <span class="custom-upload-rect-plus">+</span>
                </div>
              </template>
              <template v-else>
                <div class="custom-upload-rect-preview">
                  <img :src="form.kycUploadForm.data" class="custom-upload-rect-img" />
                  <span class="custom-upload-rect-delete" @click.stop="removeKycFile">×</span>
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item prop="email" :label="$t('Marketing.Email') + '：'">
            <el-input v-model.trim="form.email" :placeholder="$t('Placeholder.Input')"></el-input>
          </el-form-item>
        </template>

        <div class="button-container">
          <el-button @click="close">{{ $t('Btn.Cancel') }}</el-button>
          <el-button type="primary" @click="confirm">{{ $t('Btn.Confirm') }}</el-button>
        </div>
      </el-form>
    </div>
  </el-drawer>
</template>

<script setup>
  import { ref, reactive, watch, inject, computed } from 'vue'
  import { ElMessage as Message } from 'element-plus'
  import Service from '@/service/marketing'
  import UcardService from '@/service/ucard'
  import Config from '@/config/index'
  import { useI18n } from 'vue-i18n'

  const { t } = useI18n()
  const { Code } = Config
  const pigeon = inject('pigeon')
  // Props
  const props = defineProps({
    dialogInfoTradingAdd: {
      type: Boolean,
      default: false,
    },
    editor: {
      default: '',
    },
    myInfo: {
      default: '',
    },
    formList: {
      default: '',
    },
    addType: {
      type: String,
      default: '',
    },
  })

  const visible = computed(() => props.dialogInfoTradingAdd)

  // Emits
  const emit = defineEmits(['closeAdd', 'confirmToReload'])

  // Refs
  const formRef = ref(null)
  const flag = ref(false)
  const loading = ref(false)

  // Reactive data
  const form = reactive({
    email: '',
    kycUploadForm: {
      type: '',
      data: '',
    },
    uniqueId: '',
  })

  const SourceList = ref([])

  // Rules
  const rules = reactive({
    email: [
      {
        required: true,
        message: t('vaildate.input.empty'),
        trigger: 'blur',
      },
    ],
  })

  // Methods
  const selectChange = () => {
    // Vue3 中通常不需要强制更新
  }

  //关闭
  const close = () => {
    emit('closeAdd', false)
  }

  //提交成功后回调
  const confirmToReload = () => {
    emit('confirmToReload', true)
  }

  //提交
  const confirm = () => {
    if (props.addType === 'kyc_upload') {
      submitKycUpload()
    } else {
      formRef.value.validate((valid) => {
        if (valid) {
          toConfirm()
        } else {
          return false
        }
      })
    }
  }

  const toConfirm = () => {
    if (!props.editor) {
      emailAdd()
    } else if (props.editor) {
      emailUpdate()
    }
  }

  //add
  const emailAdd = async () => {
    loading.value = true
    try {
      let res = await Service.emailAdd({
        ...form,
      })
      if (res.code == Code.StatusOK) {
        confirmToReload()
        formRef.value.resetFields()
        pigeon.MessageOK(t('Msg.Success'))
      } else {
        pigeon.MessageError(res.msg)
      }
    } finally {
      loading.value = false
    }
  }

  //update
  const emailUpdate = async () => {
    loading.value = true
    try {
      let res = await Service.emailUpdate({
        ...form,
      })
      if (res.code == Code.StatusOK) {
        confirmToReload()
        close()
        formRef.value.resetFields()
        pigeon.MessageOK(t('Msg.Success'))
      } else {
        pigeon.MessageError(res.msg)
      }
    } finally {
      loading.value = false
    }
  }

  //来源列表
  const getSourceList = async () => {
    let res = await Service.emailList({})
    if (res.code == Code.StatusOK) {
      SourceList.value = res.data
    } else {
      pigeon.MessageError(res.msg)
    }
  }

  const handleKycFileUpload = async (option) => {
    const formData = new FormData()
    formData.append('file', option.file)
    try {
      const res = await UcardService.ucardUpload(formData)
      if (res.code === 200 && res.data) {
        form.kycUploadForm.data = res.data
        Message.success(t('Ucard.Business.ms11'))
        option.onSuccess(res, option.file)
      } else {
        Message.error(res.msg)
        option.onError()
      }
    } catch (e) {
      Message.error(t('Ucard.Business.ms12'))
      option.onError()
    }
  }

  const submitKycUpload = async () => {
    if (!form.uniqueId) {
      Message.error(t('Ucard.Business.ms13'))
      return
    }
    if (!form.kycUploadForm.type || !form.kycUploadForm.data) {
      Message.error(t('Ucard.Business.ms14'))
      return
    }
    loading.value = true
    try {
      const params = {
        uniqueId: form.uniqueId,
        type: form.kycUploadForm.type,
        data: form.kycUploadForm.data,
      }
      const res = await UcardService.kycUpload(params)
      if (res.code === 200) {
        Message.success(res.msg || t('Ucard.Business.ms15'))
        form.kycUploadForm = { type: '', data: '' }
        close()
        confirmToReload()
      } else {
        Message.error(res.msg || t('Ucard.Business.ms16'))
      }
    } catch (e) {
      Message.error('KYC附件上传失败')
    } finally {
      loading.value = false
      Message.error(t('Ucard.Business.ms16'))
    }
  }

  const removeKycFile = () => {
    form.kycUploadForm.data = ''
  }

  // Watchers
  watch(
    () => props.dialogInfoTradingAdd,
    (type) => {
      if (type == false && formRef.value) {
        formRef.value.resetFields()
      }
    }
  )

  watch(
    () => props.formList,
    (formData) => {
      if (formData) {
        Object.assign(form, formData)
        if (formData.kycUploadForm) {
          Object.assign(form.kycUploadForm, formData.kycUploadForm)
        }
      }
    },
    { immediate: true }
  )
</script>

<style lang="scss" scoped>
  .review-email-drawer {
    :deep(.el-drawer) {
      display: flex;
      flex-direction: column;
    }

    :deep(.el-drawer__header) {
      margin-bottom: 0;
      padding: 16px 20px;
    }

    :deep(.el-drawer__body) {
      flex: 1;
      overflow: hidden;
      padding: 0;
      position: relative;
    }
  }

  .drawer-content {
    position: relative;
    min-height: 100%;
    padding: 24px 32px 0 32px;
    background: #fff;
    max-height: calc(100vh - 40px);
    overflow-y: auto;
    padding-bottom: 64px;
  }

  .review-email-form {
    .el-form-item {
      margin-bottom: 24px;
    }

    .el-input,
    .el-select {
      width: 100%;
    }

    .el-form-item__label {
      white-space: nowrap;
      text-align: right;
      font-weight: 400;
      color: #222;
      font-size: 15px;
      padding-right: 8px;
    }

    .el-form-item__content {
      font-size: 15px;
    }

    .el-input__inner,
    .el-select .el-input__inner {
      height: 40px;
      font-size: 15px;
    }

    .el-select .el-input__inner {
      padding-right: 30px;
    }

    .el-select .el-input__icon {
      right: 10px;
    }

    .el-form-item.is-required .el-form-item__label:before {
      color: #eb3f57;
      margin-right: 4px;
    }

    .el-form-item__error {
      font-size: 13px;
      color: #eb3f57;
      margin-top: 2px;
    }
  }

  .button-container {
    text-align: right;
    background: #fff;
    padding: 24px 0 0 0;
    max-width: 420px;
    margin-left: auto;
    margin-right: 0;

    .el-button {
      width: auto !important;
      min-width: 120px;
      margin-top: 0;
    }

    .el-button + .el-button {
      margin-left: 24px;
    }
  }

  // 完全仿照截图的自定义上传卡片样式
  .custom-upload-rect {
    width: 320px;
    height: 180px;
    background: #fafbfc;
    border: 1.5px dashed #e5e6eb;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: border-color 0.2s;
  }

  .custom-upload-rect:hover {
    border-color: #409eff;
  }

  .custom-upload-rect-trigger {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .custom-upload-rect-plus {
    font-size: 48px;
    color: #c0c4cc;
    font-weight: 400;
    line-height: 1;
  }

  .custom-upload-rect-preview {
    position: relative;
    width: 100%;
    height: 100%;

    .custom-upload-rect-img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: 8px;
      background: #fff;
      display: block;
    }

    .custom-upload-rect-delete {
      position: absolute;
      top: 8px;
      right: 12px;
      background: rgba(0, 0, 0, 0.5);
      color: #fff;
      border-radius: 50%;
      width: 22px;
      height: 22px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 18px;
      cursor: pointer;
      z-index: 2;
      transition: background 0.2s;
    }

    .custom-upload-rect-delete:hover {
      background: #eb3f57;
    }
  }

  .full-width-upload {
    width: 100% !important;
    max-width: 100%;
    .custom-upload-rect-trigger,
    .custom-upload-rect-preview {
      width: 100%;
      min-height: 120px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .custom-upload-rect-img {
      width: 100%;
      max-width: 100%;
      object-fit: contain;
      border-radius: 8px;
      background: #fff;
      display: block;
    }
  }
</style>
