<template>
  <view class="mine-container" :style="{ height: `${windowHeight}px` }">
    <!--顶部个人信息栏-->
    <view class="header-section">
      <view class="justify-between" style="display: flex;">
        <view class="align-center" style="display: flex;">
          <view v-if="!avatar" class="cu-avatar xl round bg-white">
            <view class="iconfont icon-people text-gray icon"></view>
          </view>
          <image v-if="avatar" @click="handleToAvatar" :src="avatar" class="cu-avatar xl" mode="heightFix"
            style="border-radius: 5px;">
          </image>
          <view v-if="!username" @click="handleToLogin" class="login-tip">
            点击登录
          </view>
          <view v-if="username" @click="handleToInfo" class="user-info">
            <view class="u_title">
              {{ username }}
            </view>
            <view>
              {{ nick }}
            </view>
            <!-- <view v-for="(item, index) in roleGroup" :key="index">
              {{ item }}
            </view> -->
          </view>
        </view>
        <!--  <view @click="handleToInfo" class="flex align-center">
          <text>个人信息</text>
          <view class="iconfont icon-right"></view>
        </view> -->
      </view>
    </view>

    <view class="content-section">
      <view class="menu-list">
        <!-- <view class="list-cell list-cell-arrow" @click="handleToEditInfo">
          <view class="menu-item-box">
            <image class="menu-img" src="../../static/images/message/zljh@2x.png" mode=""></image>
            <view style="font-size: 29rpx;">待办</view>
          </view>
        </view> -->
        <!-- <view class="list-cell list-cell-arrow" @click="handleHelp">
          <view class="menu-item-box">
            <image class="menu-img" src="../../static/images/mine/pencil@2x.png" mode=""></image>
            <view>签名管理</view>
          </view>
        </view> -->
        <!-- 		<view class="list-cell list-cell-arrow" @click="handlesignUrl">
					<view class="menu-item-box">
						<image class="menu-img" src="../../static/images/mine/pencil@2x.png" mode=""></image>
						<view>手写签名</view>
					</view>
				
				</view> -->
        <!--    <view class="list-cell list-cell-arrow" @click="handlecaiji">
          <view class="menu-item-box">
            <image class="menu-img" src="../../static/images/mine/gengxin.png" mode=""></image>
            <view>数据采集</view>
          </view>
        </view> -->
        <view class="list-cell list-cell-arrow" @click="handleAbout">
          <view class="menu-item-box">
            <image class="menu-img" src="../../static/mine/lock@2x.png" mode=""></image>
            <view>修改密码</view>
          </view>
        </view>
        <view class="list-cell list-cell-arrow" @click="handleToSetting">
          <view class="menu-item-box">
            <image class="menu-img" src="../../static/mine/clean@2x.png" mode=""></image>
            <view>清理缓存</view>
          </view>
        </view>
        <!-- 	<view class="list-cell list-cell-arrow" @click="getxinapphost"> -->

        <view class="list-cell list-cell-arrow">
          <view class="menu-item-box">
            <view class="menu-item-box">
              <image class="menu-img" src="../../static/mine/gengxin.png" mode=""></image>
              <view>检查更新</view>
            </view>
            <view style="margin-right:30rpx;">V{{ appVersion }}</view>

          </view>
        </view>



        <view class="list-cell list-cell-arrow" @click="handleLogout">
          <view class="menu-item-box">
            <image class="menu-img" src="../../static/mine/quit@2x.png" mode=""></image>
            <view>退出登录</view>
          </view>
        </view>
      </view>

    </view>

    <view class="progress-container" v-if="isShowProgress">
      <view class="progress-box">
        <view class="text">文件下载中，请稍后 {{ progress }}%</view>
      </view>
    </view>

  </view>
</template>

<script>
  // 获取 module,里面填插件名刚刚安卓的dcloud_uniplugins.json文件注册的插件名称
  //var sc = uni.requireNativePlugin("Uni-PDA-Sdk");
  import useUserStore from '@/store/user';


  export default {
    components: {

    },
    data() {
      return {
        isShowProgress: false,
        progress: '',
        signUrl: '',
        user: {
          userId: "",
          userName: "",
          avatar: "",
          createBy: "",
          createTime: "",
          dept: {
            deptName: "",
          },
          deptId: "",
          email: "",
          nickName: "",
          phonenumber: "",
          remark: "",
        },
        roleGroup: "",
        appVersion: '',
        erweimaurl: '',
        //	name: this.$store.state.user.name,
        //  name: this.$store.getters.name,
        // version: getApp().globalData.config.appInfo.version
        version: ''
      }
    },
    computed: {
      nick() {
        // debugger
        // return  userStore.username
        const userStore = useUserStore();
        return userStore.nick
      },
      username() {
        // debugger
        // return  userStore.username
        const userStore = useUserStore();
        return userStore.username
      },
      avatar() {
        //debugger
        const userStore = useUserStore();
        return userStore.avatar
      },
      windowHeight() {
        return uni.getSystemInfoSync().windowHeight - 50
      }
    },
    // 监听页面返回
    onBackPress() {
      //debugger
      uni.redirectTo({
        url: '/pages/index/index'
      });
      // 阻止界面返回默认操作， 这一步主要是为了防止界面出现异常，uniapp有对onBackPress的详细讲解
      return true;
    },

    onShow() {
      // // #ifdef APP-PLUS
      // this.appVersion = plus.runtime.version;

      // // #endif
      // #ifdef APP-PLUS
      this.xitongxinxi();
      // 获取系统信息
      // #endif
    },
    onLoad() {
      // this.getUser()
    },
    methods: {
      // update() {
      //     var _this = this;
      //     uni.request({
      //     url: `${this.$store.state.apiBaseUrl}/users/versions`,  //请求接口
      //     method: 'POST',
      //     success: result => {
      //         if (result.data.code == 1) {
      //             plus.runtime.getProperty(plus.runtime.appid, function(inf) {
      //                 if(inf.version != result.data.data.versions){
      //                     uni.showModal({
      //                         title: "发现新版本",
      //                         content: "确认下载更新",
      //                         success: (res) => {
      //                             if (res.confirm == true) {//当用户确定更新，执行更新
      //                                 _this.doUpData();
      //                             }
      //                         }
      //                     })
      //                 }
      //             });
      //         }
      //     },
      //     })
      // },

      // doUpData() {
      //     uni.showLoading({
      //         title: '更新中……'
      //     })
      //     uni.downloadFile({//执行下载
      //         url: '***', //下载地址
      //         success: downloadResult => {//下载成功
      //             uni.hideLoading();
      //             if (downloadResult.statusCode == 200) {
      //                 uni.showModal({
      //                     title: '',
      //                     content: '更新成功，确定现在重启吗？',
      //                     confirmText: '重启',
      //                     confirmColor: '#EE8F57',
      //                     success: function(res) {
      //                         if (res.confirm == true) {
      //                             plus.runtime.install(//安装
      //                                 downloadResult.tempFilePath, {
      //                                     force: true
      //                                 },
      //                                 function(res) {
      //                                     utils.showToast('更新成功，重启中');
      //                                     plus.runtime.restart();
      //                                 }
      //                             );
      //                         }
      //                     }
      //                 });
      //             }
      //         }
      //     });
      // },
      getxinapphost() {
        //获取新的app地址文件并获取版本号
        let shebeitype = uni.getSystemInfoSync().osName; //判断是否Android或ios 'android', 'ios'
        if (shebeitype != 'android') {
          uni.showToast({
            title: "ios版暂不支持在线更新", //标题
            duration: 2000 //显示时间
          })
          return false;
        }

        let _self = this;
        getConfigKey('HandAppHost').then(res => {
          // debugger
          if (res) {
            _self.erweimaurl = res.msg || '';
            let msgdatalist = _self.erweimaurl.split('v');
            if (msgdatalist.length < 1) return; //如果数组长度小于1 说明地址为空
            let appversionnumber = msgdatalist[1].split('.apk')[0];
            //判断是否有最新版本
            const segs = this.appVersion.split('.');
            const normalizedVersion = segs.map(seg => parseInt(seg)).join('.');
            // 判断当前应用程序是否最新版本
            if (this.compareVersion(normalizedVersion, appversionnumber) < 0) {
              console.log('当前应用程序不是最新版本');
              uni.showModal({
                title: "发现新版本",
                content: "确认下载更新",
                success: (res) => {
                  if (res.confirm == true) { //当用户确定更新，执行更新
                    _self.xiazaigengxin(); //去下载更新
                  }
                }
              })
            } else {
              uni.showToast({
                title: "已是最新版本", //标题
                duration: 2000 //显示时间
              })
            }
          }
        });

      },
      compareVersion(v1, v2) {
        //判断版本号大小是否最新
        const v1Arr = v1.split('.');
        const v2Arr = v2.split('.');
        const len = Math.max(v1Arr.length, v2Arr.length);
        for (let i = 0; i < len; i++) {
          const v1Seg = parseInt(v1Arr[i] || '0');
          const v2Seg = parseInt(v2Arr[i] || '0');
          if (v1Seg > v2Seg) {
            //	debugger
            return 1;
          } else if (v1Seg < v2Seg) {
            //	debugger
            return -1;
          }
        }
        return 0;
      },
      xiazaigengxin() {
        //去下载更新
        let _self = this;
        let systype = uni.getSystemInfoSync().osName; //判断是否Android或ios
        let androidurl = _self.erweimaurl; //安卓包地址
        let iosurl = _self.erweimaurl.replace('android', 'ios'); //ios 包地址替换成ios
        iosurl = iosurl.replace('apk', 'ipa'); //ios 包地址替换成ios
        //	debugger
        // uni.showLoading({
        // 	title: '更新中……'
        // })
        const downloadTask = uni.downloadFile({ //执行下载
          url: systype == 'android' ? androidurl : iosurl, //下载地址
          success: downloadResult => { //下载成功
            //uni.hideLoading();
            this.isShowProgress = false;
            if (downloadResult.statusCode == 200) {
              uni.showModal({
                title: '',
                content: '更新成功，确定现在重启吗？',
                confirmText: '重启',
                showCancel: false, //没有取消按钮的弹框
                confirmColor: '#EE8F57',
                success: function(res) {
                  if (res.confirm == true) {
                    plus.runtime.install( //安装
                      downloadResult.tempFilePath, {
                        force: true
                      },
                      function(res) {
                        utils.showToast('更新成功，重启中');
                        plus.runtime.restart();
                      }
                    );
                  }
                }
              });
            }
          }
        });
        downloadTask.onProgressUpdate((res) => {
          if (res.progress > 0) {
            this.isShowProgress = true;
          }
          this.progress = res.progress;
          //	console.log('下载进度：' + res.progress);
          //	console.log('已下载长度：' + res.totalBytesWritten);
          //console.log('文件总长度：' + res.totalBytesExpectedToWrite);
        })
      },
      async handleToUpgrade() {
        //检查更新
        //debugger
        let _self = this;
        let resdata = await getConfigKey('apphost');
        _self.erweimaurl = resdata.msg;
        if (!_self.erweimaurl) return false;
        uni.showLoading({
          title: '更新中……'
        })
        uni.downloadFile({ //执行下载
          url: _self.erweimaurl, //下载地址
          success: downloadResult => { //下载成功
            uni.hideLoading();
            if (downloadResult.statusCode == 200) {
              uni.showModal({
                title: '',
                content: '更新成功，确定现在重启吗？',
                confirmText: '重启',
                showCancel: false, //没有取消按钮的弹框
                confirmColor: '#EE8F57',
                success: function(res) {
                  if (res.confirm == true) {
                    plus.runtime.install( //安装
                      downloadResult.tempFilePath, {
                        force: true
                      },
                      function(res) {
                        utils.showToast('更新成功，重启中');
                        plus.runtime.restart();
                      }
                    );
                  }
                }
              });
            }
          }
        });


      },
      xitongxinxi() {
        // 获取系统信息
        //	const systemInfo = uni.getSystemInfoSync();
        // 应用程序版本号
        //	const version = systemInfo.version;
        // 规范化版本号
        //	const normalizedVersion = normalizeVersion(version);
        // plus.runtime.getProperty(plus.runtime.appid, (info) => {
        // 	// console.log(JSON.stringify(info));
        // 	this.appVersion = info.version;
        // })

        //	this.appVersion = normalizedVersion;
        plus.runtime.getProperty(plus.runtime.appid, (info) => {
          // console.log(JSON.stringify(info));
          this.appVersion = info.version;
          //	this.panduan();
          //	this.getxinapphost(); //获取新的app地址
        })
      },

      panduan() {
        //debugger
        const segs = this.appVersion.split('.');
        const normalizedVersion = segs.map(seg => parseInt(seg)).join('.');
        const latestVersion = '1.0.0';
        // 判断当前应用程序是否最新版本
        if (this.compareVersion(normalizedVersion, latestVersion) < 0) {
          // debugger
          console.log('当前应用程序不是最新版本');
        }
      },
      clearCache() {

        let that = this;
        uni.clearStorageSync();
        let os = plus.os.name;
        if (os == 'Android') {
          let main = plus.android.runtimeMainActivity();
          let sdRoot = main.getCacheDir();
          let files = plus.android.invoke(sdRoot, "listFiles");
          let len = files.length;
          for (let i = 0; i < len; i++) {
            let filePath = '' + files[i]; // 没有找到合适的方法获取路径，这样写可以转成文件路径  
            plus.io.resolveLocalFileSystemURL(filePath, function(entry) {
              if (entry.isDirectory) {
                entry.removeRecursively(function(entry) { //递归删除其下的所有文件及子目录  
                  uni.showToast({
                    title: '缓存清理完成',
                    duration: 2000
                  });
                  that.formatSize(); // 重新计算缓存  
                }, function(e) {
                  console.log(e.message)
                });
              } else {
                entry.remove();
              }
            }, function(e) {
              console.log('文件路径读取失败')
            });
          }
        } else { // ios  
          plus.cache.clear(function() {
            uni.showToast({
              title: '缓存清理完成',
              duration: 2000
            });
            that.formatSize();
          });
        }
      },
      formatSize() {
        let that = this;
        plus.cache.calculate(function(size) {
          let sizeCache = parseInt(size);
          if (sizeCache == 0) {
            that.fileSizeString = "0B";
          } else if (sizeCache < 1024) {
            that.fileSizeString = sizeCache + "B";
          } else if (sizeCache < 1048576) {
            that.fileSizeString = (sizeCache / 1024).toFixed(2) + "KB";
          } else if (sizeCache < 1073741824) {
            that.fileSizeString = (sizeCache / 1048576).toFixed(2) + "MB";
          } else {
            that.fileSizeString = (sizeCache / 1073741824).toFixed(2) + "GB";
          }
        });
      },
      getUser() {
        getUserProfile().then(res => {
          const data = res;
          this.user = data.data;
          this.signUrl = this.user.signUrl || '';
          this.roleGroup = data.roleGroup.split(",");
        })
      },
      handleToInfo() {
        this.$tab.navigateTo('/pages/mine/info/index')
      },
      handleToEditInfo() {
        this.$tab.navigateTo('/pages/mine/info/edit')
      },
      handleToSetting() {
        this.$modal.confirm('确定清理缓存吗？').then(() => {
          this.formatSize()
          this.clearCache()
          this.$modal.msgSuccess("清理缓存成功")
        })
      },
      handleToLogin() {
        this.$tab.reLaunch('/pages/login')
      },
      handleToAvatar() {
        this.$tab.navigateTo('/pages/mine/avatar/index')
      },
      handleLogout() {
        const userStore = useUserStore();
        this.$modal.confirm('确定注销并退出系统吗？').then(() => {
          userStore.logOut();
        })
      },
      // handleHelp() {
      //   this.$tab.navigateTo('/pages/mine/help/index')
      // },
      handlecaiji() {
        this.$tab.navigateTo('/pages/mine/shujucaiji/index')
      },
      handleAbout() {
        // this.$tab.navigateTo('/pages/mine/pwd/index')
        uni.goToPage({
          // url: 'pages/mine/setting/index',
          url: 'pages/mine/pwd/index',
          mode: 'navigateTo',
          params: {}
        });
      },
      handlesignUrl() {
        this.$tab.navigateTo('/pages/mine/signurl/index')
      },
      handleJiaoLiuQun() {
        this.$modal.showToast('QQ群：①133713780、②146013835')
      },
      handleBuilding() {
        this.$modal.showToast('模块建设中~')
      },

      previewImage: function(e) {
        var current = e.target.dataset.src
        uni.previewImage({
          current: current,
          urls: [this.signUrl]
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '@/scss/global.scss';
  @import '@/scss/colorui.css';

  page {
    background-color: #f5f6f7;
  }

  .mine-container {
    width: 100%;
    height: 100%;
    font-size: 30rpx;

    .header-section {
      padding: 15px 15px 41.67rpx 15px;
      background-color: #FFFFFF;
      color: black;

      .login-tip {
        font-size: 18px;
        margin-left: 10px;
      }

      .cu-avatar {
        border: 2px solid #eaeaea;
        height: 100%;

        .icon {
          font-size: 40px;
        }
      }

      .user-info {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        margin-left: 15px;

        .u_title {
          font-size: 18px;
          line-height: 30px;
          font-weight: 700;
        }
      }
    }

    .content-section {
      position: relative;
      top: 10px;
    }

    .menu-img {
      margin-right: 31.25rpx;
      width: 31.25rpx;
      height: 35.42rpx;
    }

    // .menu-item-box {
    // 	font-weight: 700;
    // }
  }

  .progress-container {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 99999;
    background: rgba(0, 0, 0, .2);
    width: 750rpx;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;

    .progress-box {
      background: #FFFFFF;
      border-radius: 20rpx;
      padding: 30rpx;

      .text {
        margin-bottom: 20rpx;
      }
    }
  }
</style>