<template>
	<view class="container cashier">
        <tui-skeleton v-if="skeletonShow" backgroundColor="#fafafa" borderRadius="10rpx" :isLoading="true" :loadingType="5" />
        <template v-else>
            <!-- <custom :navbar-data='nvabarData' /> -->
            <view class="container-banner" :style="{ paddingTop:CustomBar + 115 +'px' }">
                <view class="container-title">{{ voteTitle }}</view>
                <view class="login-input">
                	<input type="text" 
                		   v-model="params.ticket"
                		   maxlength="20" 
                           disabled="true"
                		   class="input"  
                	/>
                </view>
                <view class="login-input">
                	<input type="text" 
                		   v-model="params.name"
                		   maxlength="6" 
                		   class="input" 
                		   placeholder="您的姓名"
                           :disabled="!isBundled"
                	/>
                </view>
                <view class="login-input">
                	<input type="text" 
                		   v-model="params.mobile"
                		   maxlength="11" 
                		   class="input" 
                		   placeholder="您的联系电话"
                           :disabled="!isBundled"
                	/>
                </view>
                <view class="login-input code" v-show="isBundled">
                	<input type="text" 
                		   v-model="params.smsCode"
                		   maxlength="6" 
                		   class="input code" 
                		   placeholder="手机验证码"
                	/>
                    <view class="code-btn" :class="[isMobileDisabled ? 'disabled' : '']">
                        <button
                            class="code-button"
                            type="button"
                            @click.stop="getMobileCodeFn"
                            :disabled="isMobileDisabled"
                        >
                            {{ mobileCodeText }}
                        </button>
                    </view>
                </view>
                <view class="login-input">
                	<input type="text" 
                		   v-model="params.idCard"
                		   maxlength="20" 
                		   class="input" 
                		   placeholder="证件号码(身份证/港澳台通行证/护照)"
                           :disabled="!isBundled"
                	/>
                </view>
                <view class="login-input">
                	<input type="text" 
                		   v-model="params.work"
                		   maxlength="10" 
                		   class="input" 
                		   placeholder="您的职业"
                           :disabled="!isBundled"
                	/>
                </view>
                <view class="login-btn"  v-show="isBundled" @click="handleEntry">激活门票</view>
                <view class="login-text">注：</view>
                <view class="login-text">1、门票绑定的证件号码是作为进入大会会场的凭证。</view>
                <view class="login-text">2、到采美专区签到打卡，可领取超值礼包，更多惊喜和福利等你来解琐。</view>
            </view>
        </template>
        <!-- 提示弹窗 -->
        <tui-modal
        	:show="modal"
        	@click="handleClick"
        	:content="contentModalText"
        	:button="modalButton"
        	color="#333"
        	:size="32"
        	shape="circle"
        	:maskClosable="false"
        />
        <activity-model :show="isShowModel" @cancel="hideModel"/>
	</view>
</template>

<script>
    import { mapState, mapMutations } from 'vuex'
    import authorize from '@/common/config/authorize.js'
    import wxLogin from '@/common/config/wxLogin.js'
    import activityModel from './components/activity-model.vue'
	export default{
        components:{
            activityModel
        },
		data(){
			return{
                nvabarData: {		//顶部自定义导航
                	haveBack:false,
                	haveHome:true,
                	showCapsule:1, // 是否显示左上角图标  1表示显示  0表示不显示,
                	showSearch: 0,
                	title: '',  // 导航栏 中间的标题
                	textLeft:this.$store.state.isIphone
                },
				isIphoneX:this.$store.state.isIphoneX,
				CustomBar:this.CustomBar,// 顶部导航栏高度
                skeletonShow:true,
                isShowModel:false,
				params:{
                    unionId:'',
                    name:'',
                    idCard:'',
                    ticket:'',
                    mobile:'',
                    smsCode:'',
                    work:'',
                    userId:''
                },
                voteTitle:'',
                modal: false,
                contentModalText: '', //操作文字提示语句
                modalButton: [
                    {
                    	text: '联系客服',
                    	type: 'gray',
                    	plain: true //是否空心
                    },
                	{
                		text: '确认激活',
                		customStyle: {
                			color: '#fff',
                			bgColor: '#e10078'
                		},
                		plain: false
                	}
                ],
                modalType:0,
                isMobileDisabled: false, //手机验证码按钮控制
                mobilCount: '', //倒计时
                mobileCodeText: '获取验证码',
                mobilTime: null,
                isBundled:true
			}
		},
		onLoad(option) {
            wxLogin.wxLoginAuthorize()
            setTimeout(()=>{
                this.initData(option)
            },2000)
		},
        computed: {
            ...mapState(['hasLogin', 'userInfo', ])
        },
		methods:{
            // 初始化
            async initData(option) {
            	const userInfo = await this.$api.getStorage()
                this.params.ticket = option.ticket
                this.voteTitle = option.voteType*1 === 1 ? '大会通票' : '学术套票'
                console.log('userInfo',userInfo)
                if(userInfo.userId){
                    this.params.userId = userInfo.userId
                    this.contentModalText = `您的采美帐号资料为【${userInfo.name}】,请确认并激活！`
                }
                this.getTicketDetails({ ticket: option.ticket ,userId: this.params.userId})
            },
            // 查询门票信息
            async getTicketDetails(params){
            	try{
            		const res = await this.UserService.getTicketDetails(params)
                    const data = res.data
                    if(data && data.ticketFlag === 1){
                        this.modalType = 1
                        this.contentModalText = '您已激活过门票，请勿重复激活!'
                        this.modalButton = [
                        	{
                        		text: '知道了',
                        		customStyle: {
                        			color: '#fff',
                        			bgColor: '#e10078'
                        		},
                        		plain: false
                        	}
                        ]
                        this.modal = true
                    }else{
                        if(data.userId){
                            this.isBundled = false
                            this.params = {...this.params ,...data}
                            this.params.idCard = data.idCard.substring(0, 4) + '**********' + data.idCard.substring(data.idCard.length - 4)
                            this.params.name = this.exceptSurname(data.name)
                            this.params.mobile = this.excePhoneNumber(data.mobile)
                        }else{
                            this.isBundled = true
                        }
                        this.skeletonShow = false
                    }
            	}catch(error){
                    console.log('获取门票详情异常~')
                    
            	}
            },
            //点击绑定
            handleEntry(){
                if(!this.params.name){
                    this.$util.msg('请输入您的姓名~', 2000)
                    return
                }
                if(!this.params.idCard){
                    this.$util.msg('请输入您的证件号码~', 2000)
                    return
                }
                if(!this.params.mobile){
                    this.$util.msg('请输入您的联系电话~', 2000)
                    return
                }
                if (this.params.smsCode == '') {
                    this.$util.msg('请输入手机验证码', 2000)
                    return
                }
                if(!this.params.work){
                    this.$util.msg('请输入您的职业~', 2000)
                    return
                }
                
                if(this.hasLogin){
                    this.modal = true
                }else{
                    this.params.unionId = uni.getStorageSync('unionId')
                    this.userTicketCheck({ mobile:this.params.mobile, smsCode:this.params.smsCode })
                }
            },         
            // 校验
			async userTicketCheck(params){
				try{
					const res = await this.UserService.userTicketCheck(params)
                    if(res.data && res.data.userId){
                        this.params.userId = res.data.userId
                        this.contentModalText = `您的采美帐号资料为【${userInfo.name}】,请确认并激活！`
                        this.modal = true
                    }else{
                        this.userTicketBind(this.params)
                    }
				}catch(error){
					this.$util.msg(error.msg,2000)
				}
			},
            //确认操作
            handleClick(e) {
                if(this.modalType === 0){
                    if (e.index == 1) {
                        if(this.modalType === 0){
                            this.userTicketBind(this.params)
                        }else{
                            this.$api.navigateTo('/pages/h5/activity/activity-entry-list')  
                        }
                    }else{
                        // 拨号
                        uni.makePhoneCall({
                            phoneNumber: '15338851365' //仅为示例
                        })
                    }
                }else{
                    this.$api.navigateTo('/pages/h5/activity/activity-entry-list')  
                }
            	this.modal = false
            },
            // 绑定门票
			async userTicketBind(params){
				try{
					await this.UserService.userTicketBind(params)
                    wxLogin.wxLoginAuthorize()
                    this.isShowModel = true
                    this.params.idCard = ''
				}catch(error){
					this.$util.msg(error.msg,2000)
				}
			},
            getMobileCodeFn() {
                if (this.params.mobile == '') {
                    this.$util.msg('请输入手机号', 2000)
                    return
                }
                if (!this.$reg.isMobile(this.params.mobile)) {
                    this.$util.msg('请输入正确的手机号', 2000)
                    return
                }
                let params = {
                    mobile: this.params.mobile,
                    isCheckCaptcha: 1,
                    activateCodeType: 16,
                    platformType: 2
                }
                this.isMobileDisabled = true
                this.getMobileCode(params)
            },
            async getMobileCode(params){
                try{
                    const TIME_COUNT = 60
                    await this.PublicService.GetRegisterMobileCode(params)
                    this.$util.msg('验证短信已发送', 2000)
                    if (!this.mobilTime) {
                       this.mobilCount = TIME_COUNT
                       this.isMobileDisabled = true
                       this.mobilTime = setInterval(() => {
                           if (this.mobilCount > 1 && this.mobilCount <= TIME_COUNT) {
                               this.mobilCount--
                               this.mobileCodeText = this.mobilCount + '秒后重发'
                           } else {
                               this.isMobileDisabled = false
                               clearInterval(this.mobilTime)
                               this.mobilTime = null
                               this.mobileCodeText = '获取验证码'
                           }
                       }, 1000)
                    } 
                }catch(error){
                   this.$util.msg('获取短信验证码异常~', 2000)
                   this.isMobileDisabled = false
                }
            },
            hideModel(){
                this.isShowModel = false
                this.getTicketDetails({ticket:this.params.ticket})
            },
            exceptSurname(fullName) {  
              const parts = fullName.split('')  
              if (parts.length > 1) {  
                // 只替换名字的第一个字符  
                parts[0] = '*' + parts[0].slice(1)  
                return parts.join('')  
              } else {  
                // 如果只有一个名字（或姓），则替换第一个字符  
                return '*' + fullName.slice(1)  
              }  
            },
            excePhoneNumber(phoneNumber) {  
                // 假设phoneNumber是一个有效的手机号字符串  
                // 保留手机号的前三位和后四位，中间用星号(*)替换  
                // 检查手机号长度，确保是11位（中国大陆手机号标准）  
                if (phoneNumber.length === 11) {  
                  // 提取前三位和后四位  
                  const prefix = phoneNumber.substring(0, 3)  
                  const suffix = phoneNumber.substring(7)  
                  // 生成中间部分的星号（*），长度为原手机号长度减去前后保留的长度  
                  const middle = '*'.repeat(phoneNumber.length - prefix.length - suffix.length)  
                  // 拼接脱敏后的手机号  
                  return prefix + middle + suffix  
                } else {  
                  // 如果手机号长度不是11位，可以返回原始手机号或进行其他处理  
                  console.warn('手机号长度不是11位，可能不是有效的手机号')  
                  return phoneNumber // 或者返回 null, '' 等，根据实际需求  
                }  
              }  
		},
		onShow() {
			
		}
	}
</script>

<style lang="scss">
	page{
        background-color: #3d68eb;
		height: auto !important;
	}
    .container-banner{
        width: 100%;
        height: 1142rpx;
        background: url(https://static.caimei365.com/app/img/bg/ziluo_bg.jpg) no-repeat;
        background-size: contain;
        box-sizing: border-box;
        padding: 0 110rpx;
        .container-title{
            height: 120rpx;
            line-height: 120rpx;
            font-size: $font-size-48;
            font-weight: 600;
            text-align: center;
            color: #FFFFFF;
        }
        .login-title{
            font-size: $font-size-28;
            line-height: 58rpx;
            color: #ffffff;
        }
        .login-input{
        	width: 100%;
        	height: 88rpx;
        	padding:0 24rpx;
        	margin: 0 auto;
        	margin-bottom: 40rpx;
        	background: #FFFFFF;
            box-sizing: border-box;
            border-radius: 50rpx;
            position: relative;
            &.code{
                padding-right: 180rpx;
            }
        	.input{
        		width: 100%;
        		height: 100%;
        		background: #FFFFFF;
        		font-size: $font-size-28;
        		line-height: 88rpx;
        		color: #333333;
                border-radius: 50rpx;
                 &.code{
                     width: 300rpx;
                 }
        	}
            .code-btn{
                width: 180rpx;
                height: 64rpx;
                float: left;
                background: #e10078;
                padding: 0;
                border-radius: 32rpx;
                position: absolute;
                right: 10rpx;
                top:10rpx;
                .code-button {
                    width: 180rpx;
                    height: 64rpx;
                    line-height: 64rpx;
                    padding: 0;
                    color: #ffffff;
                    background: #e10078;
                    text-align: center;
                    border-radius: 32rpx;
                    font-size: $font-size-24;
                }
                &.disabled {
                    background: #f7f7f7;
                    .code-button {
                        background: #f7f7f7;
                        color: #999999;
                        font-size: 24rpx;
                    }
                }
            }
        }
        .login-btn {
        	width: 100%;
        	height: 88rpx;
        	font-size: $font-size-30;
            font-weight: 600;
            letter-spacing: 3rpx;
        	line-height: 88rpx;
        	color: #ffffff;
        	margin: 0 auto;
        	text-align: center;
        	background-color: #e10078;
        	border-radius: 50rpx;
            margin-bottom: 10rpx;
        }
        .login-text{
            font-size: $font-size-22;
            line-height: 36rpx;
            color: #ffffff;
            margin-top: 10rpx;
        }
    }
	
</style>
