<template>
    <view class="box" v-if="detail">
        <view class="buy-box">
            <view class="uni-flex uni-column">
                <view class="info">
                    <view class="uni-flex-item name">產品信息</view>
                    <item :detail="detail" />
                     <view class="uni-flex-item name">
                         {{detail.optionType === 'PUT'?'可用餘額':'可交易數量'}}
                     </view>
                    <view class="balance">
                        <view class="uni-flex uni-column">
                            <!-- <view class="uni-flex-item" v-for="coin in coinType" :key="coin">
                                {{coin}}&nbsp;:&nbsp;&nbsp;<label class="coinB">{{balabces[coin]}}</label>
                            </view> -->
                             <view v-if="detail.optionType !== 'PUT'" class="uni-flex-item">{{detail.investCoin}}&nbsp;:&nbsp;&nbsp;<label class="coinB">{{Number(balabces[detail.investCoin])}}</label></view>
                             <view v-else class="uni-flex-item">USDT&nbsp;:&nbsp;&nbsp;<label class="coinB">{{Number(balabces.USDT)}}</label></view>
                        </view>
                    </view>
                    <view class="uni-flex-item name">交易數量</view>
                    <view class="uni-flex-item">
                        <input :class="{'disabled' :!detail.canPurchase || !isTrue()}"  :disabled="!detail.canPurchase || !isTrue()" v-model="value" class="input" placeholder="請輸入" />
                    </view>
                </view>
            </view>
        </view>
        <view style="margin-top: 32px;" v-if="detail.canPurchase">
             <button type="primary" :disabled="!detail.canPurchase || !isTrue()"  @click="buy" class="btn" :class="{'disabled' :!detail.canPurchase || !isTrue()}" >確 定 交 易</button>
        </view>
         <u-toast ref="uToast"></u-toast>
    </view>
</template>

<script>
    import item from '@/components/smarttrading/item.vue';
    import { _buy } from "@/request/aiInvestApi.js"
    import { _pushBuyInfo } from "@/request/api.js"
    
    export default {
        components: {
            item
        },
        data() {
            return {
                value: 1,
                id: '',
                detail: null,
                min:{'BNB':'0.2','ETH':'0.01','BTC':'0.001','USDT':100},
                coinType:['BNB','ETH','BTC'],
                balabces:{},
                userInfo:{},
            }
        },
        async onLoad(options) {
            
            await this.syncBuyInfos()
            uni.showLoading({mask: true})
            this.balabces = JSON.parse(uni.getStorageSync('balabces'))
            this.userInfo = JSON.parse(uni.getStorageSync('infos'))
            // 獲取傳遞的參數
            this.id = options.id;
            setTimeout(() => {
                const obj = JSON.parse(uni.getStorageSync(this.id))
                this.value = obj.optionType === 'PUT'? this.min.USDT: this.min[obj.investCoin]
                this.detail = {...obj}
                uni.hideLoading()
            }, 600)
        },
        onUnload() {
            uni.removeStorageSync(this.id)
        },
        methods: {
            isTrue(){
                let val = this.balabces.USDT
                if(this.detail.optionType === 'CALL'){
                    val = this.balabces[this.detail.investCoin] 
                }
                return Number(val) > 0 && Number(val) >= this.value
            },
            async syncBuyInfos(){
                 const buyInfos = uni.getStorageSync('bInfo') || null 
                 if(buyInfos){
                      uni.removeStorageSync('bInfo')
                      uni.showLoading({ mask: true ,title:'正在檢測數據...'})
                       const arr = JSON.parse(buyInfos)
                       let pall = []
                       arr.map(item =>{
                           pall.push(_pushBuyInfo(item))
                       })
                       Promise.all(pall).then(res =>{
                           const noSave = res.filter(r => {return r.code !== 1})
                           uni.setStorageSync('bInfo',JSON.stringify(noSave))
                       })
                        uni.hideLoading()
                 }
            },
			checkTypeAndValue(type,value){
				let obj = {
					message:"",
					isCross:false
				};
				switch(type){
					case "BNB":
						if(value >= 0.2){
							obj.isCross = true
						}else{
							obj.message = "BNB類型最低購買0.2";
							obj.isCross = false;
						}
					break;
					case "ETH":
						if(value >= 0.01){
							obj.isCross = true
						}else{
							obj.message = "ETH類型最低購買0.01";
							obj.isCross = false;
						}
					break;
					case "BTC":
						if(value >= 0.001){
							obj.isCross = true
						}else{
							obj.message = "BTC類型最低購買0.001";
							obj.isCross = false;
						}
					break;
					case "USDT":
						if(value >= 100){
							obj.isCross = true
						}else{
							obj.message = "USDT類型最低購買100";
							obj.isCross = false;
						}
					break;
				}
				return obj
			},
            async buy() {
				if(!Number(this.userInfo.miner_G) >= 1){
					uni.showToast({
					    title: '購買1G以上算力才可交易',
						icon:"none"
					})
					return
				}
				let cobj = this.checkTypeAndValue(this.detail.investCoin,this.value)
				if(!cobj.isCross){
					uni.showToast({
					    title: cobj.message,
						icon:"none"
					})
					return
				}
                uni.showLoading({ mask: true })
                const data = {
                    id: this.detail.id,
                    orderId: this.detail.orderId,
                    type: this.detail.optionType,
                    name:this.userInfo.email,
                    money:this.value,
                    money_wallet:this.userInfo.wallet.address
                }
                _buy(data).then( (res)=>{
                     if(res.status === 200){
                         let _res = res.data
                         _res.id = data.id
                         _res.money = data.money
                         _res.createTimes = this.$moment().valueOf()
                         this.$refs.uToast.show({
                              type: "success",
                              position:'bottom',
                              message: "購買成功",
                         });
                         _pushBuyInfo(_res).then().catch(err=>{
                             let buyInfos = uni.getStorageSync('bInfo') || null
                             if(buyInfos){
                                 buyInfos.push(_res)
                                 uni.setStorageSync('bInfo',JSON.stringify(buyInfos))
                             }
                             
                         }).finally(e=>{
                             uni.$emit('updateView',{})
                             uni.hideLoading()
                             uni.navigateBack()
                         })
                             
                     }
                }).catch(err => {
                    // const error = JSON.parse(err.response.data.error.replace("HTTP 错误:",""))
                     this.$refs.uToast.show({
                          type: "error",
                          position:'bottom',
                          duration:3000,
                          message:'當前產品火熱搶購中，下單失敗，請選擇其他產品購買.',
                          // message: `錯誤碼${error.code},${error.msg}`,
                          complete:()=>{
                               uni.$emit('updateView',{})
                               uni.hideLoading()
                               uni.navigateBack()
                          }
                     });
                })
                
            },
        }
    }
</script>

<style lang="scss" scoped>
    .box {
        .balance{
            background-color: rgba(0, 0, 0, .1);
            border-radius: 8px;
            color: #666;
            box-sizing: border-box;
            width: 100%;
            height: 48px;
            margin-top: 12px;
            text-indent: 12px;
            line-height: 48px;
            .coinB{
                display: inline-block;
                color: #1ABA84; 
                line-height: 48px;
            }
        }
        background-color: #000033;
        height: 100vh;
        padding: 32rpx;
        box-sizing: border-box;
        width: 100%;

        .name {
            text-indent: 8px;
            font-weight: 800;
            line-height: 36px;
            margin-top: 24rpx;
        }

        .label {
            display: inline-block;
            border: 1px solid #909399;
            padding: 2px 0;
            width: 60%;
            border-radius: 12px;
        }

        .btn {
            background-color: #4F5AD7;
            border-radius: 32px;
            font-weight: 800;
        }

        .input {
            border: 0px;
            border-bottom: 1rpx solid #999;
            font-size: 36px;
            text-align: center;
            margin-bottom: 24rpx;
        }
        .buy-box {
            box-sizing: border-box;
            width: 100%;
            min-height: 20vh;
            background-color: #fff;
            border-radius: 12px;
            padding:24rpx;

            .info {
                background-color: #F4F6F8;
                border-radius: 8px;
                padding: 0 12px;
            }
        }
    }
</style>

