<template>
  <view class="personal-data">
    <view class="wrapper">
      <view class="wrapList">
        <view class="item acea-row row-between-wrapper on">
          <view class="picTxt acea-row row-between-wrapper">
            <view class="pictrue" @tap="chooseImage">
              <div class="pictrue">
                <img :src="avatar" />
              </div>
              <!-- <image :src="`${$VUE_APP_RESOURCES_URL}/images/alter.png`" class="alter" /> -->
            </view>
            <view class="text">
              <view class="name line1">{{ userInfo.nickname }}</view>
              <view class="phone">
                绑定手机号:
                <text v-if="userInfo.phone">{{ userInfo.phone }}</text>
                <text v-else>未绑定</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="list">
      <view class="item acea-row row-between-wrapper">
        <view>昵称</view>
        <view class="input">
          <input type="text" disabled v-model="userInfo.nickname" />
        </view>
      </view>
			<view class="item acea-row row-between-wrapper">
			  <view>真实姓名</view>
			  <view class="input">
			    <input type="text"  placeholder="请填写真实姓名" placeholder-style="color:#EA533E" v-model="userInfo.realName" />
			  </view>
			</view>
			<view class="item acea-row row-between-wrapper">
			  <view>身份证号码</view>
			  <view class="input">
			    <input type="idcard" placeholder="请填写真实身份证号码" maxlength="18" v-model="userInfo.idCard" />
			  </view>
			</view>
      <!-- <view class="item acea-row row-between-wrapper">
        <view>ID号</view>
        <view class="input acea-row row-between-wrapper">
          <input type="text" :value="userInfo.uid" disabled class="id" />
          <text class="iconfont icon-suozi"></text>
        </view>
      </view> -->
      <view class="item acea-row row-between-wrapper">
        <view>手机号</view>
        <view class="input">
          <input type="text" v-if="userInfo.phone" v-model="userInfo.phone" />
          <input type="text" v-else placeholder="未绑定" v-model="userInfo.phone" disabled class="id" />
        </view>
      </view>
			<view class="item acea-row row-between-wrapper">
			  <view>验证码</view>
			  <view class="acea-row row-middle ">
			  	<view class="input-box acea-row row-middle row-right">
			  		<input type="text" v-model="verifyCode" maxlength="6" placeholder="请输入短信验证码" />
			  	</view>
			  	<view class="countdown" :class="disabled ? 'default' : ''" @click="sendCode">
			  		{{disabled ? second + '秒后重新发送' : '发送验证码'}}
			  	</view>
			  </view>
			</view>
			<view class="item acea-row row-between-wrapper">
			  <view>区域</view>
			  <view class="input">
			    <picker @change="bindPickerChange"  mode="region" :range="array">
							<view class="uni-input">{{city}}</view>
					</picker>
			  </view>
			</view>
      <!-- 
        <view class="item acea-row row-between-wrapper" @click="goChangePassword()">
          <view>密码</view>
          <view class="input acea-row row-between-wrapper">
            <text>点击修改密码</text>
            <text class="iconfont icon-suozi"></text>
          </view>
        </view>
      -->
    </view>
		<view class="tips">会员信息仅用于身份确认,不做他用。</view>
    <view class="modifyBnt" @click="submit">保存修改</view>
    <!-- #ifndef MP-WEIXIN -->
    <view
      class="logOut cart-color acea-row row-center-wrapper"
      @click="logout"
    >退出登录</view>
    <!-- #endif -->
  </view>
</template>
<script>
import { mapGetters } from "vuex";
import { trim, isWeixin, chooseImage } from "@/utils";
import { getVerificationCode } from "@/api/serverTeacher"
import { VUE_APP_API_URL } from "@/config";
import {
  postUserEdit,
  getLogout,
  switchH5Login,
  getUserInfo,
} from "@/api/user";
import cookie from "@/utils/store/cookie";
import store from "@//store";
import dayjs from "dayjs";

export default {
  name: "PersonalData",
  components: {
    // VueCoreImageUpload
  },
  data: function () {
    return {
      avatar: "",
      isWeixin: false,
      currentAccounts: 0,
      switchUserInfo: [],
      userIndex: 0,
			disabled: false,
			second: 60,
			time: null,
			city: '省/市/区',
			verifyCode:''
    };
  },
  computed: mapGetters(["userInfo"]),
  mounted: function () {
    this.avatar = this.userInfo.avatar;
    this.isWeixin = isWeixin();
    this.getUserInfo();
		this.userInfo.city ? this.city = this.userInfo.city : this.userInfo.city = '省/市/区';
  },
  methods: {
		bindPickerChange(e){
			this.city = e.detail.value.join(' ')
		},
		sendCode(){
			var reg=/^1[3456789]\d{9}$/;
			if (this.userInfo.phone === '') {
				uni.showModal({
					title: '手机号码不能为空',
					type: 'none'
				});
				return 
			} else if(!reg.test(this.userInfo.phone)){
				uni.showModal({
					title: '请输入有效的手机号码',
					type: 'none'
				});
				return 
			} else{
				getVerificationCode({phone:this.userInfo.phone}).then((res)=>{
					if(res.success){
						uni.showToast({
							title:'短信已发送!'
						})
						if(this.disabled == false){
							clearInterval(this.timer)
							this.disabled = true;
							this.timer = setInterval(()=>{   //设置延迟执行
								this.timeup()
							},1000);
						}
					} else{
						uni.showToast({
							title:res.msg,
							icon:'none'
						})
					}
				})
			}
		},
		timeup(){
			this.second = this.second - 1;
			if (this.second == 0) {
				this.second = 60;
				this.disabled = false
				clearInterval(this.timer)
				return;
			}
		},
    goChangePassword() {
      this.$yrouter.push("/pages/user/ChangePassword/index");
    },
    switchAccounts: function (index) {
      let that = this;
      this.userIndex = index;
      let userInfo = this.switchUserInfo[this.userIndex];
      if (this.switchUserInfo.length <= 1) return true;
      if (userInfo === undefined) {
        uni.showToast({
          title: "切换的账号不存在",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      if (userInfo.user_type === "h5") {
        switchH5Login()
          .then(({ data }) => {
            uni.hideLoading();
            const expires_time = dayjs(data.expires_time);
            store.commit("login", data.token, expires_time);
            that.$emit("changeswitch", false);
            location.reload();
          })
          .catch((err) => {
            uni.hideLoading();
            uni.showToast({
              title:
                err.msg || err.response.data.msg || err.response.data.message,
              icon: "none",
              duration: 2000,
            });
          });
      } else {
        cookie.set("loginType", "wechat", 60);
        uni.hideLoading();
        this.$store.commit("logout");
        this.$emit("changeswitch", false);
      }
    },
    getUserInfo: function () {
      let that = this;
      getUserInfo().then((res) => {
        // let switchUserInfo = res.data.switchUserInfo;
        // for (let i = 0; i < switchUserInfo.length; i++) {
        //   if (switchUserInfo[i].uid == that.userInfo.uid) that.userIndex = i;
        //   if (
        //     !that.isWeixin &&
        //     switchUserInfo[i].user_type != "h5" &&
        //     switchUserInfo[i].phone === ""
        //   )
        //     switchUserInfo.splice(i, 1);
        // }
        // that.$set(this, "switchUserInfo", switchUserInfo);
      });
    },
    chooseImage() {
      chooseImage((img) => {
        console.log(img);
        this.avatar = img;
      });
    },

    submit: function () {
      let userInfo = this.userInfo;
			console.log(userInfo)
			if(userInfo.realName == '' || userInfo.realName == null){
				uni.showToast({
					title:'请填写真实姓名',
					icon: "none"
				})
				return 
			}
			if(this.verifyCode == ''){
				uni.showModal({
					title: '请输入手机短信验证码',
					type: 'none'
				});
				return 
			}
      postUserEdit({
        nickname: trim(this.userInfo.nickname),
        avatar: this.avatar,
				realName: trim(this.userInfo.realName),
				idCard: this.userInfo.idCard,
				code: this.verifyCode,
				phone: this.userInfo.phone,
				city: this.city
      }).then(
        (res) => {
					if(res.success){
						this.$store.dispatch("userInfo", true);
						uni.showToast({
						  title: res.msg,
						  icon: "none",
						  duration: 2000,
						});
						setTimeout(()=>{
							this.$yrouter.back();
						},2000)
					} else{
						uni.showToast({
						  title: res.msg,
						  icon: "none",
						  duration: 2000,
						});
					}
        },
        (err) => {
          uni.showToast({
            title:
              err.msg || err.response.data.msg || err.response.data.message,
            icon: "none",
            duration: 2000,
          });
        }
      );
    },
    logout: function () {
      uni.showModal({
        title: "提示",
        content: "确认退出登录?",
        success: (res) => {
          if (res.confirm) {
            getLogout()
              .then((res) => {
                this.$store.commit("logout");
                this.$yrouter.replace({
                  path: "/pages/user/Login/index",
                  query: {},
                });
              })
              .catch((err) => {});
          } else if (res.cancel) {
            // console.log("用户点击取消");
          }
        },
      });
    },
  },
};
</script>
<style scoped lang="less">
	.modifyBnt{
		height: 80rpx !important;
		line-height: 80rpx !important;
		font-size: 32rpx !important;
		background: #F99C10;
	}
	.countdown{
		min-width: 140rpx;
		height: 58rpx;
		padding: 0 10rpx;
		font-size: 24rpx;
		background-color: #F99C10;
		color: #fff;
		line-height: 58rpx;
		text-align: center;
		border-radius: 10rpx;
	}
	.tips{
		color: #F99C10;
		font-size: 28rpx;
		line-height: 34rpx;
		padding: 24rpx;
		box-sizing: border-box;
	}
	.default{
		background: #999;
		color: #fff;
	}
	.input-box{
		text-align: right;
		input{
			width: 80%;
			margin-right: 10rpx;
		}
	}
</style>