import { Recharge, EndOrder, CancelOrder ,CheckOrderByTxid,LastUseTxid} from "../../api/pay"
import { GetUserAccount } from "../../api/help"
export default {
  data() {
    return {
      formLabelAlign: {
        coin: '',
        chain: '',
        amount: ''
      },
      value: "",
      options: [{
        value: '10',
        label: '10'
      }, {
        value: '20',
        label: '20'
      }, {
        value: '50',
        label: '50'
      }, {
        value: '100',
        label: '100'
      }, {
        value: '200',
        label: '200'
      }, {
        value: '500',
        label: '500'
      }, {
        value: '1000',
        label: '1000'
      }],
      coinOptions: [{
        value: 'USDT',
        label: 'USDT',
        disabled: false
      }, {
        value: 'USDC',
        label: 'USDC'
      }, {
        value: 'BUSD',
        label: 'BUSD'
      }],
      chainOptions: [{
        value: 'TRX',
        label: 'TRX-TRC20'
      }, {
        value: 'ETH',
        label: 'ETH-ERC20'
      }, {
        value: 'BSC',
        label: 'BSC-BEP20',
        disabled: true
      }],
      outerVisible: false,
      innerVisible: false,
      transactionData: {
        orderId: "",
        address: ""
      },
      RechargeLoading: false,
      ConfirmationLoading: false,
      CloseTransferLoading: false,
      ProblemLoading: false,
      dialogVisibleSuccess: false,
      balances: {
        total: "",
        usdc: "",
        usdt: "", 
        userId: "",
        userName: ""

      },
      Confirmation: false,
      activeName: 'Recharge',
      params: {
        coin: '',
        chain: '',
        txid: ''
      },
      bthDisabled:false,
      hashLoading:false,
      btnText:"pay.confirmSubmission",
      codeTimer:null,
      txidLoading:false,
      dialogVisibleTxid:false,
      CountdownText:null

    }
  },
  mounted() {

    this.fetchlastUseTxid()


  },

  methods: {
    //请求提交充值
    async fetchRecharge(params) {
      this.RechargeLoading = true
      const { data } = await Recharge(params)
      console.log(data, "及哦飞机佛");
      if (data.code === 200) {
        this.outerVisible = true
        this.transactionData = data.data
      }

      this.RechargeLoading = false
    },
    // 订单支付确认
    async fetchEndOrder(id) {
      this.ConfirmationLoading = true
      let time
      const { data } = await EndOrder(id)

      if (time) {//清除定时器
        clearTimeout(time)
      }


      if (data.code === 200) {
        this.outerVisible = false
        this.dialogVisibleSuccess = true
        this.fetchUserAccount()//请求当前余额
        time = setTimeout(() => {
          this.dialogVisibleSuccess = false
          this.$router.push(`/personal`)
        }, 4000);
      } else if (data.code === 801) { //801为订单已被处理 禁用按钮
        this.Confirmation = true
      }

      this.ConfirmationLoading = false

    },
    //请求订单取消 关闭转账交易
    async fetchCancelOrder(params) {
      this.CloseTransferLoading = true
      const { data } = await CancelOrder(params)
      let timer
      if (timer) {//清除定时器
        clearTimeout(timer)
      }


      if (data.code === 200) {//关闭以后提示信息 并跳转到个人中心
        this.outerVisible = false
        this.$message({
          type: 'success',
          message: this.$t(`pay.closeTransfer`)
        });

        timer = setTimeout(() => {
          this.$router.push(`/personal`)
        }, 2000)

      }

      this.CloseTransferLoading = false
    },
    //请求当前余额
    async fetchUserAccount(params) {
      const { data } = await GetUserAccount(params)
      this.balances = data.data

    },

    //选择或输入金额
    handelAmount(value) {
      console.log(value, 65656);

    },
    //选择网络
    handelChain() {
      if (this.formLabelAlign.chain == "BSC") {
        this.coinOptions[0].disabled = true

      } else {
        // this.coinOptions[0].disabled = false
      }

    },
    //选择币种
    handelCoin() {
      if (this.formLabelAlign.coin == "USDT") {
        this.chainOptions[2].disabled = true

      } else {
        // this.chainOptions[2].disabled = false
      }
    },
    //提交充值
    handelRecharge() {


      for (const key in this.formLabelAlign) { //判空
        if (key !== `files` && this.formLabelAlign[key] == "") {

          switch (key) {
            case "coin":
                this.$message({
                message: this.$t(`pay.paymentCurrency`),
                type: "error",
              });
              break;
            case "chain":
              this.$message({
                message: this.$t(`pay.paymentNetwork`),
                type: "error",
              });
              break;
            case "address":
              this.$message({
                message: this.$t(`pay.paymentAddress`),
                type: "error",
              });
              break;
            case "emailCode":
              this.$message({
                message: this.$t(`pay.paymentCode`),
                type: "error",
              });
              break;
            case "amount":
              this.$message({
                message: this.$t(`pay.paymentAmount`),
                type: "error",
              });
              break;


            default:
              break;
          }

       
          return
        }
      }
      let pattern = /^\d+$/; //只能是数字正则表达
      if (!pattern.test(this.formLabelAlign.amount)) {
        this.$message({
          message: this.$t(`pay.rechargeAmount`),
          type: "error",
        });

        return
      }


      this.fetchRecharge(this.formLabelAlign)
    },
    //点击确认已转账
    handelConfirmation() {
      this.fetchEndOrder({ orderId: this.transactionData.orderId })

    },
    //关闭转账交易
    handelCloseTransfer() {

      this.fetchCancelOrder({ orderId: this.transactionData.orderId })
    },
    //转账遇到问题
    handelProblem() {
      this.innerVisible = true
    },
    //点击联系客服
    handelCustomerService() {
      this.$router.push(`/help`)
    },
    //y验证TXID
    handelTXID() {
      // this.$router.push(`/TXID`)

      this.activeName = "Txid"
      this.outerVisible=false
      this.innerVisible=false
    },
    //点击充值页面
    Jump() {
      this.outerVisible = false
    },
    //请求按钮状态是否禁用 及倒计时
    async fetchlastUseTxid() {
      this.hashLoading = true
      const { data } = await LastUseTxid()
      this.bthDisabled = !data.data.result
      let tim = data.data.time






      //判断定时器是否存在
      if (this.codeTimer) {
        clearInterval(this.codeTimer);
      }
      //倒计时
      this.codeTimer = setInterval(() => {
        tim--
        if (tim <= 0) {
          clearInterval(this.codeTimer)
          this.btnText = "pay.confirmSubmission"
          this.bthDisabled = false
        } else {
          this.btnText = `${this.$t(`pay.Disabled`)}`
          this.bthDisabled = true
          let times= this.getTime(tim)
          this.CountdownText = `${this.$t(`pay.hash1`)} ${times[1]} ${this.$t(`pay.hash2`)} ${times[2]} ${this.$t(`pay.hash3`)} ${times[3]} ${this.$t(`pay.hash4`)}`
        }

      }, 1000)


      this.hashLoading = false

    },


    //请求查询Txid
    async fetchTxid(params) {
      this.txidLoading = true
      let timer
      const { data } = await CheckOrderByTxid(params)
      if (data.data) {
        this.balances = data.data //接口无数据测试 后端告知与余额数据结构一致
       
      }

      this.fetchlastUseTxid()

      if (timer) {
        clearTimeout(timer)
      }


      if (data.code == 200) {
        this.dialogVisibleTxid = true

        timer = setTimeout(() => {
          this.dialogVisibleTxid = false
          this.$router.push(`/personal`)
        }, 2000)

      }


      this.txidLoading = false


      console.log(this.txidLoading, 456556);
    },
    //点击确认查询Txid
    handelTxid() {
     
      for (const key in this.params) { //判空
        if (this.params[key] == "") {
          if (key=="coin") {
            this.$message({
              message: this.$t(`pay.paymentCurrency`),
              type: "error",
            });
          }else if(key=="chain"){
            this.$message({
              message: this.$t(`pay.paymentNetwork`),
              type: "error",
            });
          }
          else if(key=="txid"){
            this.$message({
              message: this.$t(`pay.hashError`),
              type: "error",
            });
          }
          
          return
        }
      }

      // const regex = /^0x[a-fA-F0-9]{64}$/; //验证交易hash 固定64位 只允许英文字母和数字 前两位固定为字符串0x、
      // const isValid = regex.test(this.params.txid);
      // if (!isValid) {       
      //   this.$message({
      //     message: this.$t(`pay.hashError`),
      //     type: "error",
      //   });
      //   return
      // }


      
     


      this.fetchTxid(this.params)

    },
    Jump1() {
      this.$router.push(`/Help`)
    },
    //秒数转换成时分秒
    getTime(time) {
      // 转换为式分秒
      let d= parseInt(time / 60 / 60 / 24) //天
      let h = parseInt(time / 60 / 60 % 24)//小时
      // h = h < 10 ? '0' + h : h
      let m = parseInt(time / 60 % 60)//分钟
       m = m < 10 ? '0' + m : m
      let s = parseInt(time % 60)//秒
       s = s < 10 ? '0' + s : s
      // 作为返回值返回
      return [d,h, m, s]
  }


  }
}