<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="500px"
    @close="close"
  >
    <el-form ref="formRef" label-width="80px" :model="form" :rules="rules" label-position="top">
      <el-form-item label="是否通知新地址" prop="isNew">
        <el-switch v-model="isNew"/>
      </el-form-item>
      <el-form-item v-if="isNew" label="回调地址" prop="url">
        <el-input v-model="form.url"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { defineComponent, getCurrentInstance, reactive, toRefs } from 'vue';
import { makeAddress, triggerNotify }                            from '@/apis/address';
import { ElMessage }                                             from "element-plus";

export default defineComponent( {
  name : 'EthRecordTrigger',
  setup ( props, { emit } ) {
    const { proxy } = getCurrentInstance();

    const state = reactive( {
      formRef           : null,
      form              : {
        tx  : '',
        url : '',
      },
      isNew             : false,
      rules             : {
        url : [{ required : true, trigger : 'blur', message : '请输入通知地址' }],
      },
      title             : '',
      dialogFormVisible : false,
    } );

    const show  = ( row ) => {
      state.title             = '回调';
      state.form              = {
        tx  : row.tx,
        url : '',
      };
      state.dialogFormVisible = true;
    };
    const close = () => {
      state[ 'formRef' ].resetFields();
      state.isNew             = false;
      state.form              = {
        tx  : '',
        url : '',
      };
      state.dialogFormVisible = false;
    };
    const save  = async () => {
      if ( state.isNew && !state.form.url ) {
        return ElMessage.warning( '请输入通知链接' );
      }
      const res = await triggerNotify( {
        tx        : state.form.tx,
        url       : state.isNew ? state.form.url : '',
        coin_type : 'tron',
      } );
      if ( res.status === 200 ) {
        ElMessage.success( '通知成功' );
        close();
      } else {
        ElMessage.error( '通知失败' );
      }
    };

    return {
      ...toRefs( state ),
      show,
      close,
      save,
    };
  },
} );
</script>
