<template>
    <view style="width: 100vw;text-align: center;">
        <!-- https://image.jxc4.com/image/42c1adf2f3fb7b913cfde602f3b9e98f.jpg -->
        <image
                class="logo"
                src="../../static/jxHorizon.png"
                mode="scaleToFill"
            />
    </view>
    
  <view class="center-root">
    <view class="tab-root">
      <text class="icon">|</text>
      <text
        class="tab-item"
        v-for="(item, i) in loginTypeList"
        :key="i"
        :class="{ active: i == activeItem }"
        @tap="activeItem = i"
        >{{ item.title }}</text
      >
    </view>

    <swiper
        :duration="200"
      class="swiper"
      @change="change"
      :current="activeItem">
      <swiper-item>
        <view class="form-root">
          <CodeLogin @codeLogin="codeLogin" />
        </view>
      </swiper-item>
      <swiper-item>
        <view class="form-root">
          <PasWordLogin @pwdLogin="pwdLogin" />
        </view>
      </swiper-item>
    </swiper>
    <!-- <view class="form-root">
        <view class="pwd-from-root">
            <jx-input>
            <template #left>
                <jx-icon icon="shoujihao" color="#aaa" :size="60"></jx-icon>
            </template>
            <template #middle>
                <uni-easyinput
                    primaryColor="#aaa"
                    :inputBorder="false"
                    class="input"
                    type="text"
                    v-model="phone"
                    placeholder="请输入用户名"
                />
            </template>
            </jx-input>
        </view>

        <view class="pwd-from-root" style="margin-top: 20rpx;">
            <jx-input>
                <template #left>
                    <jx-icon icon="mima" color="#aaa" :size="60"></jx-icon>
                </template>
                <template #middle>
                    <uni-easyinput
                        primaryColor="#aaa"
                        :inputBorder="false"
                        class="input"
                        type="password"
                        v-model="pwd"
                        placeholder="请输入密码"
                    />
                </template>
            </jx-input>
        </view>
    </view> -->
    <!-- @getphonenumber="weixiniLogin" -->
    <button 
      class="btn" 
      @tap="clickLogin" 
      v-if="!store.getters['serveInfo/isAgreement']"
      >
      <jx-icon icon="yijianshouquan" color="#fff" :size="44"></jx-icon>
      <text>一键登录</text>
    </button>
    <button
      class="btn" 
      @tap="noNeedBind"
      v-if="store.getters['serveInfo/isAgreement'] && !store.getters['serveInfo/isBindMobile'].need"
      >
      <jx-icon icon="yijianshouquan" color="#fff" :size="44"></jx-icon>
      <text>一键登录</text>
    </button>
    <button
      v-if="store.getters['serveInfo/isAgreement'] && store.getters['serveInfo/isBindMobile'].need"
      class="btn"
      open-type="getPhoneNumber"
      @getphonenumber="getPhoneNum"
    >
      <jx-icon icon="yijianshouquan" color="#fff" :size="44"></jx-icon>
      <text>一键登录</text>
    </button>
    <!-- <view class="other_login">
        <text>其它方式登录？</text>
    </view> -->
    

    <view class="copyright-root" style="position: absolute;bottom: 140rpx;">
    <view  class="center"  >
         <label>
        
        <checkbox-group @change="agreement">
          <checkbox
            :checked="store.getters['serveInfo/isAgreement']"
            value="cb"
            color="#2dd091"
            style="transform: scale(0.7); border-radius: 50%"
          />我已阅读并同意
        </checkbox-group>
      </label>
      <text class="text" @tap="user">《用户协议》</text>
      <text class="text" @tap="privacy">《隐私协议》</text>
      <view
        class="lab"
        
        >请勾选同意后在进行登录</view
      >
    </view>
  </view>

    <view class="info">欢迎进入惊喜视界</view>
</view>

  <!-- <uni-popup ref="wxPopup" type="bottom">
    <view class="wxPopup-root">
      <view class="text">
        <view class="agreement-title">用户协议及隐私协议</view>
        <view class="content">
          本协议系您与京西(成都)科技有限公司就京西菜市帐号的注册和使用而订立的。京西(成都)科技有限公司（如下简称“京西菜市”）在此特别提醒您认真阅读、充分理解本协议各条款，特别是涉及服务费用条款，免除或者限制京西菜市责任的条款，对您的权利限制条款，争议解决和法律适用条款等，此类条款将以加粗的形式提示您注意。请您审慎阅读并选择接受或不接受本协议（限制民事行为能力人应在监护人或法定代理人陪同下阅读）。除非您接受本协议所有条款，否则您无权注册、使用京西菜市帐号。您的注册和使用京西菜市帐号行为将视为您已充分理解本协议（即本协议及后续更新版本或开通或使用某项服务的单项协议），并同意接受本协议各项条款的约束。
        </view>
        <view class="agreement">
          点击同意即代表您已阅读并同意
          <text class="text" @tap="user">《用户协议》</text>
          <text class="text" @tap="privacy">《隐私协议》</text>
        </view>
      </view>
      <view class="btn">
        <view class="reject" @tap="wxPopup.close()">拒绝</view>
        <button
          class="resolve"
          open-type="getPhoneNumber"
          @getphonenumber="weixiniLogin"
        >
          同意
        </button>
      </view>
    </view>
  </uni-popup> -->
</template>

<script lang="ts" setup>
import CodeLogin from './codeLogin/codeLogin.vue'
import PasWordLogin from './paswordLogin/paswordLogin.vue'
import { computed, ref, Ref } from 'vue'
import { md5 } from 'js-md5'
import toast from '@/utils/toast'
import login from '@/api/https/login'
import useGlobalFunc from "@/composables/useGlobalFunc";
import { store } from '@/store'
import { getStorage, setStorage } from '@/utils/storage'
import { onLoad } from '@dcloudio/uni-app';

    const {
        // setUserInfo,
        isUserAgreementFn
    } = useGlobalFunc()

onLoad(() => {
    // console.log('页面初始化',store.state)
})

const phone: Ref<string> = ref('')
const pwd: Ref<string> = ref('')

interface LoginType {
    title: string;
}
const loginTypeList: Ref<LoginType[]> = ref([
    { title: "验证码登录" },
    { title: "密码登录" },
]);
const activeItem: Ref<number> = ref(0);

async function pwdLogin() {
    if (phone.value == '') return toast('请输入用户名')
    if (pwd.value.length == 0) return toast('密码不规范')
    let data = {
        authType: 'pwd',
        authIDType: 'mobile',
        authID: phone.value,
        authSecret: md5(pwd.value),
    }
    let res = await login.applets_login(data)
    if (res.code == 0) {
        console.log('登录成功')

    } else {
        toast(res.desc)
    }
}

/**
 * 新用户,解密手机号并绑定
 */
async function getPhoneNum(e:AnyObject){
    console.log('获取手机号',e.detail)
    let userInfo = uni.getStorageSync('userInfo')
    if(e.detail.errMsg === 'getPhoneNumber:ok'){
        let res = await login.decryUser({
            sessionKey:userInfo.session_key,
            iv:e.detail.iv,
            encryptedData:e.detail.encryptedData,
            type:'phone'
        })
        if(res.data == 0){
            // 绑定成功
            // setUserInfo(res.data)
             uni.navigateTo({ url: '/pages/index/index' })
        }
    }
}

/*************************************************
 * 切换登录信息
*/
function change(res: AnyObject) {
    activeItem.value = res.detail.current
}


/**
 * 微信登录
 */
function clickLogin(){
    if (!store.state.serveInfo.isAgreement) {
        isUserAgreementFn()
        return false
    }
}

/**
 * 验证码登录
 */
function codeLogin(data: AnyObject) {
    // setUserInfo(data)
    // saveUserType()
}

// 非首次登录 不需要绑定手机号
function noNeedBind (){
    if(store.getters['serveInfo/isBindMobile'].need) return     // 不需要绑定
    silenceLogin()
}


/**
 * 登录 e?: AnyObject
 */
 async function silenceLogin() {
    await store.dispatch('serveInfo/wxLogin',{authType:'wx'})
    // let data = uni.getStorageSync('userInfo') // getStorage('userInfo')
    // console.log('11111111',data)
    
        // let userInfoDecry = await login.decryUser({
        //     sessionKey:data.session_key, 
        //     iv:'微信用户', // 昵称
        //     encryptedData:'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132', // 头像
        //     type:'name'
        // })


    //  uni.getUserProfile({
    //     desc:'用于个性化头像展示',
    //     success:async (userInfo) => {
    //         let data = uni.getStorageSync('userInfo') // getStorage('userInfo')
    //         // https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132
    //         // 微信用户
    //         console.log(data,'111111111111，存储的信息',userInfo)
    //         let userInfoDecry = await login.decryUser({
    //             sessionKey:JSON.parse(JSON.parse(data.extraInfo)).session_key, 
    //             iv:userInfo.userInfo.nickName, // 昵称
    //             encryptedData:userInfo.userInfo.avatarUrl, // 头像
    //             type:'name'
    //         })
    //         // console.log('解密后的信息',userInfoDecry)
    //         // let getCode = await login.get_jx_code();
    //         // if (getCode) {
    //         //     let data = {
    //         //         authType: "wx",
    //         //         authSecret: getCode.code,
    //         //     };
    //         //     let res = await login.applets_login(data);
    //         //     if (res.code == 0) {
    //         //         // 登录成功
    //         //         console.log('登录成功',res.data)
    //         //         // en2tNW9y6rn8tM9KXI720Q==
    //         //         setUserInfo(res.data,userInfo);
                    
    //         //         // if (userInfo.data.tokenType == 1) {
    //         //         //     setUserInfo(userInfo.data);
    //         //         //     saveUserType()
    //         //         // }

    //         //         // // 首次登录绑定用户手机号
    //         //         // if (userInfo.data.tokenType != 1) {
    //         //         //     setStorage('token', userInfo.data.token)
    //         //         //     bangdingMobile(e!, userInfo.data.token)
    //         //         // }
    //         //     } else {
    //         //         toast("登录失败", 2);
    //         //     }
    //         // }
    //     }
    // })
    
}

// // 存储用户信息
// async function saveUserType() {
//     // let res = await login.get_self_info()
//     // if (res.code == 0) {
//     //     setStorage('userType', res.data.type)
//     // } else {
//     //     setStorage('userType', 0)
//     // }
// }

// // 绑定手机号码
// async function bangdingMobile(e: AnyObject, token: AnyObject) {
//     let data = {
//         "data": e.detail.encryptedData,
//         "iv": e.detail.iv,
//         "appID": 'wx08a5c2a8581414ff'
//     }
//     // let resData = await login.getUser_by_mini_info(data)
//     // if (resData.code == 0) {
//     //     // 有手机号码，绑定
//     //     if (resData.data.isExist) {
//     //         let data = {
//     //             authToken: token,
//     //             mobile: resData.data.mobile,
//     //         }
//     //         let ress = await login.add_auth_bind(data)
//     //         if (ress.code == 0) {
//     //             setStorage('token', '85e60d6a-f1f8-4837-9c7d-d7072b0ba1c6')
//     //             let infoData = await login.get_token_info()
//     //             setStorage('token', infoData.data.token)
//     //             setStorage('userID', infoData.data.userID)
//     //             bindsns(resData.data.mobile)
//     //         } else {
//     //             toast('登录失败', 2)
//     //         }
//     //     }

//     //     // 没手机号码
//     //     if (!resData.data.isExist) {
//     //         let oldData = {
//     //             "userID2": resData.data.mobile,
//     //             "name": resData.data.mobile,
//     //             "avatar": 'https://image.jxc4.com/jxwhite.png',
//     //             "mobile": resData.data.mobile
//     //         }
//     //         let data = {
//     //             authToken: getStorage('token'),
//     //             payload: JSON.stringify(oldData)
//     //         }
//     //         let res = await login.register_user(data)
//     //         if (res.code == 0) {
//     //             setStorage('token', res.data.token)
//     //             setStorage('token', '85e60d6a-f1f8-4837-9c7d-d7072b0ba1c6')
//     //             let infoData = await login.get_token_info()
//     //             setStorage('token', infoData.data.token)
//     //             setStorage('userID', infoData.data.userID)
//     //             bindsns(false)
//     //         } else {
//     //             toast('登录失败', 2)
//     //         }
//     //     }
//     // } else {
//     //     toast('登录失败', 2)
//     // }
// }


// // 获取新信息
// function bindsns(mobile: string | boolean) {
//     if (mobile) {
//         uni.navigateTo({
//             url: `/subPages/login/bindSNS/bindSNS?mobile=${mobile}`
//         })
//     } else {
//         uni.navigateTo({
//             url: '/subPages/login/bindSNS/bindSNS'
//         })
//     }

// }


// 微信登录弹窗实例
// const wxPopup = ref<any>(null)
// 微信登录
// async function weixiniLogin(e: AnyObject) {
//     wxPopup.value.close()
//     if (e.detail.errMsg == "getPhoneNumber:ok") {
//         silenceLogin(e)
//     }
// }


/*************************************************
 * 是否同意协议
*/
const isAgreement = ref<boolean>(false)
/**
 * 勾选
 */
function agreement(e: AnyObject) {
    if (e.detail.value.length) {
        // 同意
        isAgreement.value = true
        store.commit('serveInfo/setIsAgreement', true)
        store.commit('serveInfo/setIsAgreementIf', false)
    } else {
        // 不同意
        store.commit('serveInfo/setIsAgreement', false)
        isAgreement.value = false
    }
}

/**
 * 用户协议
 */
function user(){
    uni.navigateTo({ url: '/subPages/agreement/user' })
}

/**
 * 隐私协议
 */
function privacy(){
    uni.navigateTo({ url: '/subPages/agreement/privacy' })
}
</script>

<style lang="scss" scoped>
// @import './index.scss';
// .loginCss{
//     width: 100vw;
//     height: 100rpx;
//     line-height: 100rpx;
//     border-bottom: 1rpx solid #eee;
//     text-align: center;
// }
::v-deep .uni-easyinput__content-input {
    background-color: #efefef !important;
    // font-size: 44rpx;
}

::v-deep .uni-easyinput__content,.uni-easyinput__content > .content-clear-icon{
    background-color: #efefef !important;

    // .content-clear-icon{
    //     background-color: #efefef;
    // }
}

// ::v-deep .uni-easyinput__placeholder-class{
//     font-size: 44rpx;
// }

.pwd-from-root{
    border-bottom:1rpx solid #d8d8d8;
}

.btn{
    background-color: #5ef3e5;
    border-radius: 100rpx;
    margin-top: -20rpx;
    font-size: 36rpx;
    height: 92rpx;
    color: #fff;
    line-height: 92rpx;
    width: 90%;
}
.pwd-login-btn {
  width: 90%;
  border-radius: 100rpx;
  margin-top: 60rpx;
  color: rgb(255, 255, 255);
  background-color: $jx-login;
}
.logo {
    width: 350rpx;
    height: 350rpx;
    margin: 50rpx 0;
}

.center-root {
    box-sizing: border-box;
    padding: 30rpx 0rpx;
    width: 750rpx;

    .tab-root {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-evenly;
        color: #aaa;
        margin-bottom: 50rpx;

        .icon {
            order: 2;
        }

        .tab-item:first-child {
            order: 1;
        }

        .tab-item:last-child {
            order: 3;
        }

        .tab-item {
            padding: 10rpx 40rpx;
            border-radius: 50rpx;
            font-weight: bold;
            font-size: 40rpx;
        }

        .active {
            color: #fff;
            font-weight: bold;
            color: $jx-login;
        }
    }

    .form-root {
        box-sizing: border-box;
        width: 100%;
        padding: 0 50rpx;
    }

    .weixin-login-root {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-top: 100rpx;
        margin-bottom: 100rpx;

        .text-root {
            display: flex;
            align-items: center;
            justify-content: center;

            .hr {
                width: 400rpx;
                border-bottom: 1rpx solid #e6e6e6;
                z-index: 0;
                width: 150rpx;
                border-bottom: 1rpx solid #e6e6e6;
                background-color: #e6e6e6;
            }

            .weixin-text {
                position: relative;
                padding: 0 10rpx;
                color: #bbbbbb;
            }
        }

        button {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 110rpx;
            width: 110rpx;
            background-color: $jx-login  !important;
            border-radius: 50%;
            margin-top: 20rpx;
        }
    }
}

.other_login{
    width: 100%;
    margin-top: 30rpx;
    text-align: center;
}

.info {
    position: absolute;
    width: 100%;
    text-align: center;
    bottom: 60rpx;
    color: rgb(126, 126, 126);
    font-size: 36rpx;
    // font-weight: bold;
}


.copyright-root {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    text-align: center;
    // font-size: 26rpx;
    font-size: 32rpx;

    .text {
        color: $jx-login;
    }

    .center {
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;

        .lab {
            position: absolute;
            padding: 7rpx 10rpx;
            background-color: #656a70;
            color: #fff;
            left: 0rpx;
            top: 60rpx;
            border-radius: 10rpx;
            opacity: 0;
            transition: all 0.2s;
        }

        .lab::after {
            content: '';
            position: absolute;
            width: 0;
            height: 0;
            border-left: 11rpx solid transparent;
            border-right: 11rpx solid transparent;
            border-bottom: 12rpx solid #656a70;
            left: 12rpx;
            top: -11rpx;
        }

        .lab-active {
            opacity: 1 !important;
        }
    }

    .center-active {
        animation: identifier 0.2s;
    }
}


.swiper {
    height: 450rpx;
}

@keyframes identifier {
    0% {
        transform: translateX(20rpx);
    }

    20% {
        transform: translateX(0rpx);
    }

    40% {
        transform: translateX(20rpx);
    }

    60% {
        transform: translateX(0rpx);
    }

    40% {
        transform: translateX(20rpx);
    }

    100% {
        transform: translateX(0rpx);
    }
}
</style>