<script>
	import tokenpocketBnb from "@/common/wallet/tokenpocket-wallet/tokenpocket-bnb";
	import {
		getTotalMoney
	} from "@/api/money";
  import {
    addDeal, authorizeDeal,
    getAddress,
    getDealList
  } from "@/api/deal";
	import tools from "@/common/js/tools";
	import web3 from "web3";
	import {
		ethers
	} from "ethers";
	import blank from "@/components/en-utils/en-blank/en-blank.vue";

	export default {
		name: "convert-index",
		components: {
			blank
		},
		data() {
			return {
				usdtNum: '',
				iconNum: '',
				type: 1,
				toNum: '',
				formNUm: '',
				price: '',
				address: '',
				dealAddress: '',
				change_num: 0,
        max_num: 0,
        userDealNum: 0,
				list: [],
				page: 1,
			};
		},
		watch: {
			'formNUm': function() {
				if (this.formNUm === '') {
					this.toNum = ''
				} else {
          console.log(this.type,this.price,'---------------------')
					if (this.type === 2) {
						this.toNum = this.formNUm * this.price
					} else {
            console.log(this.formNUm , this.price);
						this.toNum = (this.formNUm / this.price).toFixed(6)
					}
          console.log('11111',	this.toNum)

				}
			}
		},
		mounted() {
			this.getIconNum()
			this.getTotalMoney()
			this.getAddress()
			this.getDealList()
		},
		methods: {
			getAddress() {
				getAddress().then(res => {
					if (res.code === 1) {
						this.dealAddress = res.data.address
						this.change_num = res.data.change_num
						this.max_num = res.data.max_num
						this.userDealNum = res.data.userDealNum
					}
				})
			},
			async addDeal() {
				if (this.toNum === '' || this.formNUm === '') {
					tools.error("兑换数量异常")
					return
				}
        if(this.formNUm*1+this.userDealNum>this.max_num){
          tools.error("兑换超限")
          return
        }
				let data = ''
				let transactionData = ''
				let formHex = web3.utils.numberToHex(ethers.utils.parseEther(this.formNUm.toString()).toString());
				if (this.type === 1) {
					if (this.change_num > 10) {
						tools.error('交易已锁定')
						return
					}
					data = '0xa9059cbb'
					data = data + tools.replenishZero(this.dealAddress) + tools.replenishZero(formHex)
					transactionData = await tokenpocketBnb.getContractTransaction(data, 1);
				} else {
					data = '0xa9059cbb'
					// data='0x7472616e73666572'
					data = data + tools.replenishZero(this.dealAddress) + tools.replenishZero(formHex)
					transactionData = await tokenpocketBnb.getContractTransaction(data, 0);
				}
				console.log(transactionData)
				// data='0x5e9a0c48000000000000000000000000b7f1c21c51a0f85704a13b981aa9075d9b102962';
				tokenpocketBnb.sendTransaction(transactionData).then(res => {
					console.log(res)
					if (res) {
						addDeal({
							'type': this.type,
							'money': this.formNUm,
							'hash': res
						}).then(res => {
							if (res.code === 1) {
								tools.success(res.msg)
								this.toNum = ''
								setTimeout(()=>{
                  this.getTotalMoney()
                  this.getIconNum()
                  this.getAddress()
                  this.page=1
                  this.list=[]
                  this.getDealList()
                },50)
							} else {
								tools.error(res.msg)
							}
						})
					}
				})
			},
			setMax() {
				if (this.type === 1) {
					this.formNUm = this.usdtNum
				} else {
					this.formNUm = this.iconNum
				}
			},
			getTotalMoney() {
				getTotalMoney().then(res => {
					if (res.code === 1) {
						this.price = res.data.price

					}
				})
			},
			async getIconNum() {
				this.address = tokenpocketBnb.getMyAddress()
				if (this.address === '') {
					return
				}
				setTimeout(async () => {
					this.iconNum = await tokenpocketBnb.getTokenBalance(this.address, 0)
					this.usdtNum = await tokenpocketBnb.getTokenBalance(this.address, 1)
				}, 100)

			},
			setType() {
				return
				this.type = (this.type === 1 ? 2 : 1)
				this.formNUm = ''
			},
			abbreviateString(str) {
				let startLength = 4;
				let endLength = 4;
				if (str.length <= startLength + endLength + 1) {
					return str; // 如果字符串长度不足以被截断，则返回原字符串
				}
				return str.slice(0, startLength) + '...' + str.slice(-endLength);
			},
			getDealList() {
				if (this.total >= this.list.length && this.page>1) {
					return
				}
				getDealList({
					'page': this.page
				}).then(res => {
					if (res.code === 1) {
						this.list.push(...res.data.items)
						this.total = res.data.total
							++this.page
					}

				})
			},
      async authorizeDeal(item){
        console.log(item)
        let data = ''
        let transactionData = ''
        console.log(item.to_money-item.server_money)
        let money=((item.to_money-item.server_money).toFixed(6)*1)+'';
        let formHex = web3.utils.numberToHex(ethers.utils.parseEther(money).toString());
        data = '0x095ea7b3'
        data = data + tools.replenishZero(this.dealAddress) + tools.replenishZero(formHex)
        console.log(data)
        transactionData = await tokenpocketBnb.getContractTransaction(data, 0);
        console.log(transactionData)
        // data='0x5e9a0c48000000000000000000000000b7f1c21c51a0f85704a13b981aa9075d9b102962';
        tokenpocketBnb.sendTransaction(transactionData).then(hash => {
          console.log(hash)
          if (hash) {
            authorizeDeal({
              'id': item.id,
              'hash': hash
            }).then(res => {
              if (res.code === 1) {
                tools.success(res.msg)
                item.sq_hash =hash
              } else {
                tools.error(res.msg)
              }
            })
          }
        })

      }
		},
	}
</script>

<template>
	<view class="flex-common-box  box-sizing-border">
		<view class="top-b bgc-f plr-20 box-sizing-border align-items-center flex-justify-space">
			<image class="img-box" src="@/static/img/logo/logo.png"></image>
			<view class="fs-30">
				{{abbreviateString(address)}}
			</view>
		</view>
		<scroll-view :scroll-y="true" class="scroll-view-css" @scrolltolower="getDealList">
			<view class="p-20 box-sizing-border">
				<view class="bgc-f p-40 box-sizing-border b-rad-20 ">
					<view class="">
						<view class="bgc-F6F7FA b-rad-20 mb-20 p-20 box-sizing-border mb-20" v-if="type===1">
							<view class="align-items-start flex-justify-space mb-20">
								<view class="align-items-center">
									<image class="t-img mr-8" :src="require('@/static/img/index/index/usdt.png')">
									</image>
									<view class="fs-28">USDT</view>
								</view>
								<view class="max-box b-rad-20 fs-28" @click="setMax">
									Max {{usdtNum}}
								</view>
							</view>
							<view>
								<input v-model="formNUm" placeholder="输入要兑换的USDT数量" placeholder-class="fs-28"></input>
							</view>
						</view>
						<view class="bgc-F6F7FA b-rad-20 mb-20 p-20 box-sizing-border mb-20" v-else>
							<view class="align-items-start flex-justify-space mb-20">
								<view class="align-items-center">
									<image class="t-img mr-8" :src="require('@/static/img/logo/logo.png')"></image>
									<view class="fs-28">DAO</view>
								</view>
								<view class="max-box b-rad-20 fs-28" @click="setMax">
									Max {{iconNum}}
								</view>
							</view>
							<view>
								<input v-model="formNUm" placeholder="输入要兑换的DAO数量" placeholder-class="fs-28"></input>
							</view>
						</view>
					</view>

					<view class="flex-direction-column align-items-center flex-justify-center mb-20" @click="setType">
						<view class="fs-28">
							FORM
						</view>
						<image class="jh-img" :src="require('@/static/img/index/index/jiaohuan.png')"></image>
						<view class="fs-28">
							TO
						</view>
					</view>
					<view>
						<view class="bgc-F6F7FA b-rad-20 mb-20 p-20 box-sizing-border mb-50" v-if="type===1">
							<view class="align-items-start flex-justify-space mb-20">
								<view class="align-items-center">
									<image class="logo-img mr-8" :src="require('@/static/img/logo/logo.png')"></image>
									<view class="fs-28">DAO</view>
								</view>
							</view>
							<view class="fs-28" :class="toNum?'':'fc-808080'">
								{{toNum?toNum:'输入后自动换算'}}
							</view>
						</view>
						<view class="bgc-F6F7FA b-rad-20 mb-20 p-20 box-sizing-border mb-50" v-else>
							<view class="align-items-start flex-justify-space mb-20">
								<view class="align-items-center">
									<image class="logo-img mr-8" :src="require('@/static/img/index/index/usdt.png')">
									</image>
									<view class="fs-28">USDT</view>
								</view>
							</view>
							<view class="fs-28" :class="toNum?'':'fc-808080'">
								{{toNum?toNum:'输入后自动换算'}}
							</view>
						</view>
					</view>

					<view class="convent-but b-rad-20 text-align-center fs-28 fc-f" @click="addDeal">
						兑换
					</view>
				</view>
				<view class="bgc-f p-20 box-sizing-border b-rad-20 m-t-40">
					<view class="fs-28 pt-5 mb-8">
						兑换记录
					</view>
					<view v-if="list.length<=0" class="blank-box align-items-center flex-justify-center">
						<blank :showBlank="list.length<=0?true:false" message="暂无数据"></blank>
					</view>
					<view class="bgc-F6F7FA" v-else>
						<view class="item-box align-items-center flex-justify-space" v-for="item in list" :key="item.id">
							<view>
								<view class="mb-8 fs-28 fw-b">兑换 {{item.money}} USDT</view>
								<view class="fs-24">{{item.created_date}}</view>
							</view>
							<view class="flex-direction-column flex-justify-end align-items-flex-end">
								<view class="fs-24" :class="item.status<=3?'fc-ED930F':(item.status === 4?'fc-FF3B30':'fc-27AE60')">
									{{item.status_str}}</view>
								<view class="fs-28 ">到账:  <text class="fc-ED301D">{{(item.to_money-item.server_money).toFixed(6)*1}} DAO</text></view>
								<view class="but-b bgc-3489FF fs-24 text-align-center fc-f b-rad-20" @click="authorizeDeal(item)" v-show="item.status===3 && !item.sq_hash">
									授权
								</view>
							</view>
						</view>

					</view>
				</view>
			</view>
		</scroll-view>


	</view>

</template>

<style scoped lang="scss">
	.but-b{
		width: 120rpx;
		height: 50rpx;
		line-height: 50rpx;
	}
	.flex-common-box {
		width: 100%;
		height: calc(100vh - 138rpx);
		display: flex;
		flex-direction: column;
	}

	.t-img {
		width: 70rpx;
		height: 60rpx;
	}

	.max-box {
		color: #0d81cf;
		border: 2rpx solid #0d81cf;
		padding: 6rpx 20rpx;
	}

	::v-deep .el-input__inner {
		background-color: transparent;
		border: none;
		padding: 0;
	}

	.jh-img {
		width: 60rpx;
		height: 60rpx;
		transform: rotate(90deg);
	}

	.logo-img {
		width: 66rpx;
		height: 50rpx;
	}

	.convent-but {
		height: 80rpx;
		background: #0d81cf;
		color: #fff;
		line-height: 80rpx;
	}

	.img-box {
		width: 78rpx;
		height: 60rpx;
	}

	.top-b {
		width: 100%;
		height: 98rpx;
		line-height: 98rpx;
	}

	.item-box {
		width: 100%;
		// height: 120rpx;
		padding: 10rpx 20rpx;
		box-sizing: border-box;
		border-top: 2rpx solid #e5e5e5;
	}
</style>
