<template>
  <view class="container">
    <view class="header">
      <u-upload @afterRead="afterReadImg" :deletable="false" :maxCount="1">
        <image class="avatar_pic" :src="avatarInfo.url" alt="" />
      </u-upload>
      <view class="header_desc">点击更换头像</view>
    </view>
		<view class="main">
			<view class="tabel">
				<view class="left">姓名</view>
				<view class="right">
					<input
						type="text"
						placeholder="请填写昵称"
						:value="name"
						data-name="name"
						@input="headerInputClick"
					/>
				</view>
			</view>
			<view class="tabel">
				<view class="left">性别</view>
				<view class="right">
					<radio
						value="2"
						:checked="sex == 2"
						@click="headerRadioClick(2)"
					/>女
					<view class="right_radio">
						<radio
							value="1"
							:checked="sex == 1"
							@click="headerRadioClick(1)"
						/>男
					</view>
				</view>
			</view>
			<view class="tabel">
				<view class="left">Email</view>
				<view class="right no_border">
					<input
						type="text"
						placeholder="请填写邮箱地址"
						:value="eMail"
						data-name="eMail"
						@input="headerInputClick"
					/>
				</view>
			</view>
		</view>
		<view class="btn" @click="headerSubmitClick">保存设置</view>
		<view class="main">
			<view class="tabel1" @click="headerRefreshClick">
				<view class="left">刷新登录</view>
				<view class="right">
					<u-icon name="arrow-right" />
				</view>
			</view>
			<button
				class="login-btn"
				open-type="getPhoneNumber"
				style="display: none;"
				@click="headerLoginClick"
				@getphonenumber="getPhoneNumber"
				id="hiddenLoginBtn"
			></button>

			<view class="tabel1 no_border" @click="headerSettingClick">
				<view class="left">设置授权</view>
				<view class="right">
					<u-icon name="arrow-right" />
				</view>
			</view>
		</view>
		<view class="btn logout-btn" @click="headerLogoutClick">退出登录</view>
    <nav-footer :current="4"/>
  </view>
</template>

<script>
import { request, picUrl, upload, validateEmail } from "../../../utils/index";
import { apiArr } from "../../../api/login";
import { apiArr as apiArr2 } from "../../../api/v2User";
export default {
  data() {
    return {
      avatarInfo: {},
      name: "",
      mobile: "",
      eMail: "",
      sex: 0,
    };
  },
  methods: {
    // 上传图片
    async afterReadImg(e) {
      const { file } = e;
      upload(file.url, (res) => {
        this.avatarInfo = {
          url: picUrl + res.data.path,
          picUrl: res.data.path,
        };
      });
      uni.showToast({
        title: "上传成功",
        icon: "success",
      });
    },

		headerRefreshClick() {
			uni.showLoading({
				title: '刷新中',
				mask: true
			})
			// 清楚缓存信息
			uni.removeStorageSync('ctoken');
			uni.removeStorageSync('userId');
			uni.removeStorageSync('openId');
			uni.removeStorageSync('phone');
			uni.removeStorageSync('is_deal');
			uni.removeStorageSync('is_dev');
			uni.removeStorageSync('is_shop');
			uni.removeStorageSync('is_merchant');
			uni.removeStorageSync('is_worker');
			uni.removeStorageSync('shopId');
			uni.removeStorageSync('order_dispatch_permission');
			uni.removeStorageSync('work_order_permission');

			const button = uni.createSelectorQuery().select('#hiddenLoginBtn');
			button.boundingClientRect().exec();
		
			// 执行原headerLoginClick逻辑
			this.headerLoginClick();
		},

		headerLoginClick() {
			let that = this;
			uni.login({
				onlyAuthorize: true,
				success: (res) => {
					request(apiArr.login, 'POST', {
						code: res.code,
						phone: '',
						password: '',
					}, { silent: false }).then((loginRes) => {
						// 存储用户信息
						uni.setStorageSync('ctoken', loginRes.token);
						uni.setStorageSync('is_deal', loginRes.is_deal);
						uni.setStorageSync('is_dev', loginRes.is_dev);
						uni.setStorageSync('is_shop', loginRes.is_shop);
						uni.setStorageSync('is_merchant', loginRes.is_merchant);
						uni.setStorageSync('is_worker', loginRes.is_worker);


						// 获取用户信息
						request(apiArr.loginInfo, 'POST', {
							token: loginRes.token
						}, { silent: false } ).then((res2) => {
							if (res2.error) return;
							// 保存userId 后续接口使用
							uni.setStorageSync('userId', res2.user_id);
							uni.setStorageSync('openId', res2.open_id);
							uni.setStorageSync('shopId', res2.wshop_id);
							that.init(true)

						})
					}, (err) => {
						uni.hideLoading();
						console.log('登录接口错误', err);
					})
				}
			})
		},

		// 小程序登录获取手机号接口
		getPhoneNumber(event) {
			console.log('小程序登录获取手机号', event);
		},

    headerInputClick(e) {
      const { name } = e.currentTarget.dataset;
      const { value } = e.detail;
      this[name] = value;
    },

		headerSettingClick() {
			uni.openSetting({
				success(res) {
					console.log(res.authSetting)
				}
			});
		},

		// 退出登录
		headerLogoutClick() {
			uni.showModal({
				title: '提示',
				content: '确定要退出登录吗？',
				success: (res) => {
					if (!res.confirm) return;
					// 清除全部登录态缓存
					const keys = [
						'ctoken', 'userId', 'openId', 'phone', 'is_deal', 'is_dev',
						'is_shop', 'is_merchant', 'is_worker', 'shopId',
						'order_dispatch_permission', 'work_order_permission',
						'nickName', 'headPhoto', 'changeCommData', 'currentRoomNo'
					];
					keys.forEach(k => uni.removeStorageSync(k));
					uni.showToast({
						title: '已退出登录',
						icon: 'success',
						mask: true,
						duration: 1500,
						success: () => {
							setTimeout(() => {
								uni.reLaunch({ url: '/pages/login/login' });
							}, 1500);
						}
					});
				}
			});
		},

    headerRadioClick(item) {
      this.sex = item;
    },

		async headerSubmitClick() {
			if(this.eMail && !validateEmail(this.eMail)){
				uni.showToast({
					title: '请输入正确邮箱地址',
					icon: 'none'
				})
				return
			};
			const res = await request(apiArr2.userInfoUpdate, 'POST', {
				gender: this.sex,
				avatar: this.avatarInfo.picUrl,
				nick_name: this.name,
				email: this.eMail,
				// mobile
			});
			uni.showToast({
				title: '保存成功',
				mask: true
			});
			setTimeout(() => {
				uni.navigateBack({
					delta: 1
				})
			}, 2000)
		},

    async init(item = false) {
      const res = await request(apiArr2.getUserInfo, "POST", {}, {silent: item === true ? false : true});
      this.avatarInfo = {
        url: res.avatar
          ? picUrl + res.avatar
          : "https://static.hshuishang.com/person/Group_309.png",
        picUrl: res.avatar,
      };
      this.name = res.nick_name;
      this.mobile = res.mobile;
      this.sex = res.gender;
      this.eMail = res.email;
			if (item) {
					const { community_worker } = res;
					uni.setStorageSync('order_dispatch_permission', community_worker && community_worker[0].order_dispatch_permission == 1 || false);
					uni.setStorageSync('work_order_permission', community_worker && community_worker[0].work_order_permission == 1 || false);
					uni.setStorageSync('phone', res.account);
					uni.hideLoading();
					uni.showToast({
						title: '刷新成功',
						icon: 'success',
						mask: true,
						duration: 2000,
					})
				}
    },
  },

  onLoad() {
    this.init();
  },
};
</script>

<style>
@import url("./index.css");
</style>
