<template>
  <view class="mine-container" :style="{ height: `${windowHeight}px` }">
    <!--顶部个人信息栏-->
    <view class="header-section">
      <view class="flex padding justify-between">
        <view class="flex align-center">
          <view v-if="!avatar" class="cu-avatar xl round bg-white">
            <view class="iconfont icon-people text-gray icon"></view>
          </view>
          <image v-if="avatar" @click="handleToAvatar" :src="avatar" class="cu-avatar xl round" mode="widthFix">
          </image>
<!--          <view v-if="token" @click="handleToLogin" class="login-tip">
            点击登录
          </view> -->
          <view  class="user-info">
            <view class="u_title">
              iccid号：{{ iccid }}
            </view>
			<view class="u_title">
			  到期时间：{{ endTime }}
			</view>
			<view class="u_title">
			  当前套餐：{{ packageName }}
			</view>
          </view>
        </view>
      </view>
    </view>
	
	  <view class="package-box">
		  <view class="package-top">
		  	<view 
			  @click="handleLeftTab" 
		      :class="{ 'left-tab': true, active: leftTab.isActive }"
			>
		  		   {{leftTab.name}}
		  	</view>
		  	<view 
			  @click="handleRightTab" 
			  :class="{ 'right-tab': true, active: rightTab.isActive }"
			>
		  		   {{rightTab.name}}
		  	</view>
		  </view>
		   <view class="package-bottom">
                 <view v-for="(item, index) in packageList" :key="index" 
                       class="package-item" @click="selectPackage(index)">
					   <view class="package-title">
					   	  <text>{{ item.thaliGroupName }}</text>
					   </view>
					   <view class="package-price">
					   	  <text>{{ item.thaliPayPrice }}元</text>
					   </view>
                 </view>
		   </view>
	  </view>


    <view class="content-section">
      <view class="mine-actions grid col-4 text-center">
        <view class="action-item" @click="handleBind">
          <view class="iconfont icon-friendfill text-pink icon"></view>
          <text class="text">绑定充值卡</text>
        </view>
<!--        <view class="action-item" @click="handleGetCardInfo">
          <view class="iconfont icon-community text-blue icon"></view>
          <text class="text">获取充值卡信息</text>
        </view> -->
        <view class="action-item" @click="handleGetRealNameUrl">
          <view class="iconfont icon-service text-mauve icon"></view>
          <text class="text">点击实名</text>
        </view>
		<view class="action-item" @click="handleJump">
		  <view class="iconfont icon-community text-mauve icon"></view>
		  <text class="text">一键授权</text>
		</view>
      </view>

    </view>
  </view>
  <view>
	  <uni-popup ref="rechargePopup" type="dialog">
	    <uni-popup-dialog 
		  type="info" 
		  cancelText="关闭" 
		  confirmText="绑定"
	      title="" 
		  content="" 
	      @confirm="dialogConfirm"
	      @close="dialogClose">
			<input 
			  v-model="rechargeNum" 
			  class="input" 
			  type="text" 
			  placeholder="请输入充值号" 
			  maxlength="30" 
			/>
	    </uni-popup-dialog>
	  </uni-popup>
	  <uni-popup ref="confirmPopup" type="center" background-color="#fff" class="confirmPopup-box">
	  		<uni-popup-dialog
	  		  type="info" 
	  		  cancelText="关闭" 
	  		  confirmText="确认"
	  		  title="" 
	  		  content="" 
	  		  @confirm="confirmPurchase"
	  		  @close="cancelPurchase">
	  		  <text>确认购买 {{ selectedPackage.thaliGroupName }} 吗？</text>
	  		</uni-popup-dialog>
	  </uni-popup>
	  
	  <uni-popup ref="selectPopup" type="bottom" background-color="#fff" class="selectPopup-box">
           <view class="popup-content">
                <text>套餐名称: {{ selectedPackage.thaliGroupName }}</text>
                <text>价格: {{ selectedPackage.thaliPayPrice }}</text>
                <button @click="purchasePackage" class="buy-button">立即购买</button>
            </view>
	  </uni-popup>
	  

  </view>
</template>

<script setup>
import { ref, reactive,onMounted } from 'vue';
import modal from "@/plugins/modal";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { userBindRechargeNum,getRechargeNum ,getRealNameUrl, getGroupPackage, recharge, getPackageSort, getCardByUserId} from '@/api/card'
import { vxPay } from '@/api/vxPay'

import config from '@/config.js'
import useUserStore from '@/store/modules/user'
import pay from "@/pages/wechat/wxpayUtils";

const userStore = useUserStore()
const name = userStore.name;
const version = config.appInfo.version;

const avatar = ref(userStore.avatar);
const windowHeight = ref(uni.getSystemInfoSync().windowHeight - 50);
const rechargePopup = ref(null);
const selectPopup = ref(null);
const confirmPopup = ref(null);
const rechargeNum = ref('')
const token = ref('');
const iccid = ref('')
const endTime = ref('')
const packageName = ref('')
const thaliGroupId = ref('')
const packageList = ref([])
const selectedPackage = ref(null);
const orderNumber = ref('')

const leftTab = ref({
	name: undefined,
	thaliGroupId: undefined,
    isActive: true,
})

const rightTab = ref({
	name: undefined,
	thaliGroupId: undefined,
	isActive: false,
})
uni.$on('refresh', () => {
  avatar.value = userStore.avatar;
})



function handleToLogin() {
  uni.reLaunch({
    url: '/pages/login'
  });
};

function handleLogout() {
};
function dialogConfirm() {
  const data = rechargeNum.value
  if (rechargeNum.value) {
  	userBindRechargeNum(data).then(res => {
  		if(res.code === 200) {
			modal.showToast({
			  title: '绑定成功',
			  icon:'sucess',
			  duration: 1000
			});
		} else {
		   // 如果绑定失败，显示错误提示
			modal.showToast({
			  title: '绑定失败：' + res.msg, // 假设 res.msg 包含错误信息
			  icon: 'error',
			  duration: 1000
			});
		}
  	})
  } else {
  	    // 如果没有值，提示用户输入充值号
  	    modal.showToast({
  	      title: '请输入充值号',
  	      icon: 'none', // 或者使用其他适当的图标
  	      duration: 1000
  	    });
  }
};
function dialogClose() {
    
};

function handleAbout() {
	const data = {rechargeNum : '1442212701559'}
	
	getRealNameUrl(data).then(res => {
		console.log(res,9)
	})
};

// 绑定充值卡
function handleBind() {
	rechargePopup.value.open()
	// rechargeNum.value = ''
};

// 登录查询卡信息
function handleGetCardByUserId() {
	getCardByUserId().then(res => {
		console.log(res,1999)
		iccid.value = res.data.card.iccId
		endTime.value = res.data.card.createTime
		packageName.value = res.data.card.thaliName
		
	})
};

// 获取充值卡信息
function handleGetCardInfo() {
	const data = rechargeNum.value
	// const data = '89861591292320027863'
	getRechargeNum(data).then(res => {
		console.log(res,19)
		iccid.value = res.data.card.iccId
		endTime.value = res.data.card.createTime
		packageName.value = res.data.card.thaliName
		
	})
};

// 获取实名链接
function handleGetRealNameUrl() {
	const data = rechargeNum.value
		// const data = '89861591292320027863'
	getRealNameUrl(data).then(res => {
		if(res.code === 200) {
			const URL = res.data
			location.href = URL
		}
	})
};


function handleJump() {
	const appid = 'wx6aeb90e7fd5d434e'
	const redirect_uri = encodeURIComponent("https://trade.youpin5g.com/#/") 
	location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`

}


// function handleBuilding() {
//   const data = rechargeNum.value	
// 	getRechargeNum(data).then(res => {
// 	})
// }



// 获取套餐种类
function getPackageSortList() {
  const data = rechargeNum.value	
  // const data = '89861591292320027863'
	getPackageSort(data).then(res => {
		leftTab.value.name = res.rows[0].groupName;
		leftTab.value.thaliGroupId = res.rows[0].id;

		rightTab.value.name = res.rows[1].groupName;
		rightTab.value.thaliGroupId = res.rows[1].id;
		
	})
}

function handleLeftTab() {
	leftTab.value.isActive = true;
	rightTab.value.isActive = false;
	
    const data = leftTab.value.thaliGroupId;
    getGroupPackage(data).then(res => {
        packageList.value = res.data.map(item => {
            return {
                thaliGroupName: item.thaliGroupName,
                thaliPayPrice: item.thaliPayPrice,
				thaliId:item.id,
            };
        });
    }).catch(error => {
        console.error("API请求失败:", error);
    });
}

function handleRightTab() {
	leftTab.value.isActive = false;
    rightTab.value.isActive = true;
	
	const data = rightTab.value.thaliGroupId
	getGroupPackage(data).then(res => {
	    packageList.value = res.data.map(item => {
	        return {
	            thaliGroupName: item.thaliGroupName,
	            thaliPayPrice: item.thaliPayPrice,
				thaliId:item.id,
	        };
	    });
	}).catch(error => {
	    console.error("API请求失败:", error);
	});
}


function selectPackage(index) {
  console.log("选中的套餐:", packageList.value[index]);
  selectedPackage.value = packageList.value[index];
  selectPopup.value.open();
}

// 创建订单,预支付
function purchasePackage() {
	const formData = new FormData();
	formData.append('rechargeNum', rechargeNum.value); 
	formData.append('thaliId', selectedPackage.value.thaliId);
	  
	
	const data = {
		rechargeNum: rechargeNum.value,
		thaliId: selectedPackage.value.thaliId
	}
	console.log(data,901)
    recharge(data).then(res =>{
		orderNumber.value = res.data
		console.log('创建订单成功:', res);
		confirmPopup.value.open();
	})

}

function confirmPurchase() {
  const openId = uni.getStorageSync('openid');
  const paymentData = {
    "totalPrice": selectedPackage.value.thaliPayPrice, // 假设价格是字符串类型
    "goodsName": selectedPackage.value.thaliGroupName,
    "openId": openId,
    "orderNumber": orderNumber.value,
  };

    vxPay(paymentData).then(res => {
		pay(res.data,()=>{
				alert("支付成功！")
		})
		// 处理支付成功后的逻辑，如关闭弹窗、提示支付成功等
		selectPopup.value.close();
		confirmPopup.value.close();
	})

}

  import { onLoad } from '@dcloudio/uni-app';

onLoad(()=> {
			let curPage = getCurrentPages();
			let route = curPage[curPage.length - 1].route; //获取当前页面的路由
			console.log(route,999)
	})
onMounted(() => {
  
  handleGetCardInfo()
  getPackageSortList()
  
  setTimeout(() => {
    handleLeftTab();
  }, 1000);
  
  handleGetCardByUserId()

});
</script>

<style lang="scss">
page {
  background-color: #f5f6f7;
}

.mine-container {
  width: 100%;
  height: 100%;


  .header-section {
    padding: 15px 15px 45px 15px;
    background-color: #3c96f3;
    color: white;

    .login-tip {
      font-size: 18px;
      margin-left: 10px;
    }

    .cu-avatar {
      border: 2px solid #eaeaea;

      .icon {
        font-size: 40px;
      }
    }

    .user-info {
      margin-left: 15px;

      .u_title {
        font-size: 14px;
        line-height: 30px;
      }
    }
  }
  
  .package-box {
	  margin: 15px 15px;
	  padding: 20px 20px;
	  border-radius: 8px;
	  background-color: white;
	  display: flex;
	  flex-direction: column;
	  
	  
	  .package-top {
		  display: flex;
		  flex-direction: row;
		  justify-content: space-around;
		  
		  .left-tab,
		  .right-tab {
		    display: flex;
		    align-items: center;
		    justify-content: center;
		    height: 30px;
		    width: 140px;
		    border-radius: 3px;
		    color: #fff;
		    cursor: pointer;
		    transition: background-color 0.3s;
		  }
		  
		  .left-tab.active,
		  .right-tab.active {
		    background-color: #e57335; /* 激活时的颜色 */
		  }
		  
		  .left-tab:not(.active),
		  .right-tab:not(.active) {
		    background-color: #d0d0d0; /* 非激活时的颜色 */
		  }
	  }

	  
	  .package-bottom {
	      display: flex;
		  flex-direction: row;
		  justify-content: space-around;
	      flex-wrap: wrap;
	      gap: 10px;
		  padding-top: 30rpx;
		  
		  .package-title {
			  display: flex;
			  justify-content: center;
		  }
		  .package-price {
			  display: flex;
			  justify-content: center;
			  color: gray;
		  }
	  }
	  
	  .package-item {
	      border: 1px solid orange;
		  width: 130px;
	      padding: 15px;
	      cursor: pointer;
		  border-radius: 8px;
	  }
	  
	  .package-item:hover {
	      border-color: darkorange;
	  }
  }

  .content-section {
    position: relative;
    // top: -50px;

    .mine-actions {
      margin: 15px 15px;
      padding: 20px 0px;
      border-radius: 8px;
      background-color: white;

      .action-item {
        .icon {
          font-size: 28px;
        }

        .text {
          display: block;
          font-size: 13px;
          margin: 8px 0px;
        }
      }
    }
  }
}


.popup-content {
  padding: 20px;
  height: 400rpx;
  text-align: center;
  
  .buy-button {
    background-color: #e57335;
    color: white;
    padding: 10px;
    margin-top: 20px;
  }
}

.popup-box {
  padding: 20px;
  height: 400rpx;
  text-align: center;
  
}

.confirm-button {
  background-color: #4CAF50;
  color: white;
  margin-right: 10px;
}

.cancel-button {
  background-color: #f44336;
  color: white;
}


.selectPopup-box {
	z-index: 1;
}


.confirmPopup-box {
	z-index: 1000;
}

</style>
