<template>
  <view class="container">
    <div class="userinfo">
      <div class="icon" @click="goBack">
        <uni-icons type="back" size="25" color="white"></uni-icons>
      </div>
      <div class="Header">
        <span>个人信息</span>
      </div>
    </div>

    <uni-list class="info">
      <uni-list-item title="头像" show-arrow="true" clickable class="listContainer" @click="showActionSheet(default_src)">
        <template v-slot:footer>
          <image class="slot-image" :src="default_src" mode="aspectFill"></image>
        </template>
      </uni-list-item>
      <uni-list-item v-for="(item, index) in userListShow" :key="index" clickable :title="item.name"
        class="listContainer" @click="modifyValue(item)">
        <template v-slot:footer>
          <div class="item" @click.stop="changeItemInfo(item,index)">
            <text>{{item.info}}</text>
          </div>
        </template>
      </uni-list-item>
    </uni-list>
    <button type="primary" class="button" @click="save">保存</button>
  </view>


</template>

<script>
  let modify = false
  //访问数据
  const userList = uni.getStorageSync('value')
  let userListShow = [{
    name: '手机号码',
    info: userList.phonenumber
  }, ]

  export default {
    data() {
      return {
        userList: userList,
        userListShow: userListShow,
        modify: modify,
        default_src: uni.getStorageSync('avatar'),
        phone: userList.phonenumber,
      }
    },
    mounted() { //挂载时重新获取一次Storage数据
      this.userList = uni.getStorageSync('value')
      this.userListShow[0].info = this.userList.phonenumber
    },
    methods: {
      goBack() {
        uni.navigateBack()
      },
      showActionSheet(default_src) { //修改头像
        uni.showActionSheet({
          itemList: ['拍照/上传照片'],
          success: (res) => {
            console.log('选择了第' + (res.tapIndex + 1) + '个选项');
            if (res.tapIndex === 0) { //拍照上传照片
              uni.chooseImage({
                count: 1,
                sizeType: ['origin', 'compressed'],
                sourceType: ['camera', 'album'],
                success: (res) => {
                  const tempFilePaths = res.tempFilePaths;
                  console.log('--------拍照上传照片--------', res);
                  this.default_src = tempFilePaths[0]
                  uni.uploadFile({
                    url: uni.$http.baseUrl + '/gunshiApp/tsg/system/user/profile/avatar',
                    fileType: 'image',
                    filePath: tempFilePaths[0],
                    name: 'avatarfile',
                    header: {
                      'Authorization': 'Bearer ' + uni.getStorageSync('Gs-Token')
                    },
                    success: (res) => {
                      const imgUrl = JSON.parse(res.data).imgUrl;
                      this.getImgFlow(imgUrl)
                      // uni.setStorageSync("imgUrl",imgUrl)
                     uni.$showMsg("上传成功")
                    },
                  })

                }
              })
            }
          },
          fail: (err) => {
            console.log('弹窗取消');
          }
        });
      },

      getImgFlow(imgUrl) {
				uni.request({
					url: uni.$http.baseUrl +
						`/gunshiApp/tsg/common/download/resource?resource=${imgUrl}`,
					responseType: 'arraybuffer',
					success: (res) => {
						// 将arraybuffer转换为Base64编码
						let base64 = uni.arrayBufferToBase64(res.data);
						const p = 'data:image/png;base64,' + base64;
						 uni.setStorageSync("avatar",p)
					}
				})
			},
      modifyValue(item) {
        console.log(item);

      },
      changeItemInfo(item, index) { //修改电话
        uni.showModal({
          title: "修改" + item.name,
          editable: true,
          placeholderText: item.info,
          confirmText: "确认",
          cancelText: "取消",
          success: (res) => {
            const phoneReg = /^[1][3-9]\d{9}$/;
            if (res.confirm) {
              if (phoneReg.test(res.content)) {
                this.userListShow[index].info = res.content
                this.phone = res.content
                uni.showToast({
                  title: "修改成功，请保存",
                  icon: "none",
                  duration: 1000,
                })
              } else {
                uni.showToast({
                  title: "请输入正确手机号码",
                  icon: "none",
                  duration: 1000,
                })
              }
            }

          },
          fail: (err) => {
            console.log('取消');
          }
        })
      },
      async save() {
        try {
          let new_userList = uni.getStorageSync('value')
          new_userList.phonenumber = this.phone;
          const 
            {data}
           =await uni.$http.put('/gunshiApp/tsg/system/user/profile', new_userList);
          if (data.code == 200) {
            uni.setStorageSync('value', new_userList)
            uni.reLaunch({
              url: '/pages/mypage/mypage'
            })
          }
          uni.$showMsg("保存成功")
        } catch (error) {
          uni.$showMsg()
        }




      }
    }
  }
</script>

<style>
  .userinfo {
    border-radius: 5px;
    display: flex;
    flex-direction: row;
    margin-top: 5vh;
    margin-left: 2vw;
    margin-bottom: 2vh;
    align-items: center;
    width: 95%;
    height: 6vh;
    background-color: #007afd;

  }

  .icon {
    width: 6vw;
    height: 6vh;
    align-items: center;
    line-height: 6vh;
  }

  .Header {
    display: flex;
    flex-direction: row;
    flex: 0.95;
    justify-content: center;
    color: white;
    font-size: 20px;
  }

  .info {
    margin: 1vh;

  }

  .listContainer {
    height: 6vh;
    line-height: 8vh;
  }

  .button {
    margin-top: 60vh;
    border-radius: 10px;
    display: flex;
    flex-direction: column-reverse;
    width: 92%;
    height: 6vh;
    font-size: 20px;
    color: white;
    background-color: #007afd;
  }

  .slot-image {
    margin-top: 12px;
    width: 40px;
    height: 40px;
    border-radius: 50%;
  }
</style>