<template>
  <view class="content">
    <!-- 头部 -->
    <view class="header-con" :style="{background:appTheme}">
      <view class="header" v-if="token">
        <view class="left">
          <image :src="user.headimg" class="headimage mr-10" @click="handleDrawer"></image>
          <view>
            <view class="name" @click="handleDrawer">
              <text class="overflow">{{user.name}}</text>
              <icon class="iconfont icon-yqfqiehuan"></icon>
            </view>
            <view class="age">
              <view>
                性别:{{!user.sex?"未知":user.sex==1?'男':'女'}}
              </view>
              <view>
                年龄:{{user.mage?user.mage:"0岁"}}
              </view>
            </view>
          </view>
        </view>
        <view class="celiang_r" @click="handleBluetoothClick">
          <icon class="t-icon t-icon-tizhongcheng"></icon>
          <text>上秤测量</text>
        </view>
      </view>
      <view class="header2" v-else @click="handleLogin">
        <view class="text"><text>登录</text>查看更多信息</view>
      </view>
    </view>
    <!-- 工具 -->
    <view class="tools_l">
      <view v-for="(item,index) in toollist" :key="index" class="list" @click="clickTool(item.id)">
        <image :src="item.icon"></image>
        <view class="text">{{item.title}}</view>
      </view>
      <!-- 客服 -->
      <message v-if="token&&configBox.serviceappid"></message>
    </view>
    <!-- 报告 -->
    <view class="myinfo myinfoPage borderT15" v-if="MeasureResult&&infoList.length">
      <view class="h2">
        <view><text></text>健康评分</view>
      </view>
      <view class="box">
        <view class="left">
          <view class="circleprogress">
            <view class="wrapper">
              <view class="leftprogress" :style="{ width: MeasureResult.cmi + '%'}">
              </view>
            </view>
            <view class="fen">
              <view>{{MeasureResult.cmi}}</view>分
            </view>
          </view>
        </view>
        <view class="right">
          <view class="item">
            <view><text>{{MeasureResult.height}}</text>cm</view>
            <view class="tivon">身高</image>
            </view>
          </view>
          <view class="item">
            <view><text>{{MeasureResult.weight}}</text>kg</view>
            <view>体重</view>
          </view>
          <view class="item">
            <view><text>{{MeasureResult.bodyage}}</text>岁</view>
            <view>体龄</view>
          </view>
          <view class="item">
            <view><text class="f-15">{{MeasureResult.body}}</text></view>
            <view>体型</view>
          </view>
        </view>
      </view>
    </view>
    <view class="myinfo myinfoPage borderT15">
      <view class="h2">
        <view><text></text>健康分析</view>
        <view class="more" v-if="MeasureResult&&infoList.length">测量时间：{{user.lasthearttime}}</view>
      </view>
      <view v-if="MeasureResult&&infoList.length">
        <view class="box1">
          <view class="list" v-for="(item,index) in infoList" :key="index" @click="handleToggle(index)">
            <view class="block">
              <view class="name">
                <icon class="t-icon iconfont" :class="'t-icon-'+item.key"></icon>
                {{item.title}}
              </view>
              <view class="val" v-if="item.title!='肥胖等级'">
                {{item.fvalue?item.fvalue:'0'}}{{item.dw}}
              </view>
              <view class="val0" v-else>{{item.fevaluation}}</view>
              <view class="level" v-if="item.title!='肥胖等级'">
                <view class="btnf" :style="{backgroundColor:item.color}">{{item.fevaluation}}</view>
              </view>
              <view class="icon">
                <icon class="iconfont icon-arrow-down" v-if="item.desc"></icon>
              </view>
            </view>
            <view class="desc" v-if="item.showCon">
              <view v-if="item.desc">{{item.desc}}</view>
              <view class="statuevue" v-if="item.slist">
                <view class="bi" v-if="item.title!='基础代谢'">
                  <view class="item" v-for="(ite , ind) in item.slist" :key="ind" :style="{backgroundColor:ite.color}">
                    <view class="span1">{{ite.text}}</view>
                    <!-- 超高 -->
                    <view v-if="ite.text==item.fevaluation&&item.fvalue>ite.maxvalue" class="peobox" style="right: 5px">
                      <view class="xx"></view>
                    </view>
                    <!-- z正常 -->
                    <view v-if="ite.text==item.fevaluation&&item.fvalue<=ite.maxvalue"
                      :style="'left:'+item.leftval+'rem'" class="peobox">
                      <view class="xx"></view>
                    </view>
                    <view class="span" v-if="ind<item.slist.length-1">{{ite.maxvalue}}</view>
                  </view>
                </view>
                <view v-else>
                  <view class="kcalClass">
                    标准值:{{item.slist[0].maxvalue}}kcal
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view v-else class="nolist">
        <icon class="iconfont icon-zanwu"></icon>
      </view>
    </view>
    <view class="introction" v-if="MeasureResult&&infoList.length">
      <icon class="t-icon t-icon-tishi"></icon>
      <span>此测量数据仅供参考，不可代替医学专业测试！</span>
    </view>
    <!-- 提醒设置 -->
    <view class="tipList borderRadius borderT15 mb-15" v-if="tmplIdList.length">
      <view class="h2">
        <view><text></text>提醒设置</view>
      </view>
      <view class="item_box">
        <view class="item_box_tips" v-for="(text,id) in checkList" :key="id" @click="switch1Change(text.index)">
          {{text.title}}
          <image class="iconfont"
            :src="isShowEle == text.index?'../../static/switch-off.png':'../../static/switch-ON.png'" />
        </view>
      </view>
    </view>
    <!-- banner -->
    <view class="f_banner borderT15" v-if="fimages.length">
      <swiper class="swiper" indicator-dots="true" autoplay="true">
        <swiper-item v-for="(image, index) in fimages" :key="index" @click="detail(image)">
          <image :src="image.headimg" />
        </swiper-item>
      </swiper>
    </view>
    <view class="endtext mt-15" v-if="!lastPage || page >= lastPage">—— 到底了，看看别的吧 ——</view>
    <!-- denglu -->
    <userLogin></userLogin>
    <!-- 手动记录 -->
    <manuaRecord></manuaRecord>
    <!-- 左侧 -->
    <leftdrawer></leftdrawer>
  </view>
</template>

<script>
  import {
    mapState
  } from "vuex";
  import userLogin from '@/components/userLogin.vue'
  import leftdrawer from "@/components/drawer/drawer.vue"
  import message from "@/components/message.vue"
  import manuaRecord from '@/components/target/manuaRecord.vue';
  export default {
    components: {
      leftdrawer,
      userLogin,
      message,
      manuaRecord
    },
    computed: {
      ...mapState(["user", "MeasureResult", "configBox", "appTheme", "devHomePram"]),
    },
    async onLoad(options) {
      let that = this;
      uni.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: that.appTheme,
      });
      that.token = uni.getStorageSync('token')
      console.log("首页收参", options, )
      if (options && options.userid) {
        that.userId = options.userid
      }
      // if (options && options.t) {
      //   that.$store.commit("changeDevType", options);
      // }
      await that.login()
    },
    onShow() {
      this.token = uni.getStorageSync('token')
    },
    onTabItemTap() {
      this.$store.commit("changeDrawe", false)
      this.$store.commit("changeRecord", false);
    },
    watch: {
      MeasureResult() {
        console.log("MeasureResult更新", this.MeasureResult)
        this.handleToggle(0)
      },
      appTheme() {
        uni.setNavigationBarColor({
          frontColor: '#ffffff',
          backgroundColor: this.appTheme,
        });
      }
    },
    methods: {
      login() {
        let that = this
        console.log('userId', that.userId)
        uni.login({
          success(res) {
            if (res.code) {
              if (res.errMsg = "login:ok") {
                that.$model.onlogin({
                  code: res.code,
                  userid: that.userId
                }).then(res => {
                  if (res.code == 2) {
                    that.token = null
                    uni.clearStorageSync()
                    that.$store.commit("changeLogout", false);
                    uni.setStorageSync('tenantid', res.data.tenantid)
                    uni.setStorageSync('sessionid', res.data.sessionid)
                    uni.setStorageSync('iswxphone', res.data.iswxphone)
                    that.$store.dispatch("getConfig", {
                      tenantId: uni.getStorageSync('tenantid')
                    })
                    return
                  }
                  if (res.code == 0) {
                    that.token = res.data.token
                    uni.setStorageSync('token', res.data.token)
                    uni.setStorageSync('userid', res.data.userid)
                    uni.setStorageSync('tenantid', res.data.tenantid)
                    uni.setStorageSync('sessionid', res.data.sessionid)
                    uni.setStorageSync('iswxphone', res.data.iswxphone)
                    uni.setStorageSync('refreshtoken', res.data.refreshtoken)
                    that.$store.dispatch("getConfig", {
                      tenantId: uni.getStorageSync('tenantid')
                    })
                    that.getFamilyList()
                  }
                }).catch(e => {})
              }
            }
          }
        })
      },
      getFamilyList() {
        let that = this
        let isfamily
        let id = uni.getStorageSync('familyid')
        that.$model.getFamilyList({}).then(res => {
          that.$store.commit("changeFamilay", res)
          if (id) {
            if (!isNaN(id) && typeof id === "number") {
              isfamily = true
            } else {
              isfamily = false
            }
          } else {
            isfamily = true
          }
          that.$model.getUserInfo({
            familyid: isfamily ? res[0].familyid : uni.getStorageSync('familyid')
          }).then(res => {
            that.$store.commit('changeUser', res.data)
            if (!res.data.height || !res.data.mage || !res.data.birthday) {
              uni.redirectTo({
                url: `/pageTwo/login/userinfo`
              })
              return
            }
            that.$store.dispatch("getResult", {
              birthday: res.data.birthday,
              familyid: res.data.familyid,
              height: res.data.height,
              sex: res.data.sex,
            })
            that.GetTplList()
            that.GetSubscribeInfo()
            that.getBannerList()
          });
        }).catch(e => {})
      },
      //消息模板列表
      GetTplList() {
        let that = this
        that.$model.GetTplList({}).then(res => {
          if (res.code == 0) {
            console.log("消息模板列表", res.data)
            res.data.forEach(item => {
              that.tmplIdList.push(item.id)
            })
          }
        })
      },
      //消息订阅状态
      GetSubscribeInfo() {
        let that = this
        that.$model.GetSubscribeInfo({}).then(res => {
          console.log("消息模板状态", res)
          if (res.code == 0) {
            that.isShowEle = res.data.type
          }
        })
      },
      //消息提醒
      switch1Change(ind) {
        let that = this
        if (that.isShowEle != ind) { //允许提醒
          wx.requestSubscribeMessage({
            tmplIds: that.tmplIdList,
            success(res) {
              let list = {}
              let subList = []
              that.tmplIdList.forEach(item => {
                list = {
                  "tplId": item,
                  "status": res[item],
                }
              })
              subList.push(list)
              that.$model.GetSubscribe({
                type: ind,
                list: subList,
              }).then(res => {
                console.log("res", res)
                if (res.code != 0) return
                that.isShowEle = ind
              })
            },
            fail(res) {
              that.$tools.msg("订阅失败")
            }
          })
        } else { //取消提醒
          that.$model.Getunsubscribe({
            type: 1,
          }).then(res => {
            if (res.code == 0) {
              that.$tools.msg("取消提醒成功")
              that.isShowEle = 0
              return
            }
          })
        }
      },
      // 轮播
      getBannerList() {
        this.$model.getBannerList({}).then(res => {
          this.fimages = res.data
        })
      },
      // 上称测量
      handleBluetoothClick() {
        let that = this
        if (!that.token) {
         uni.redirectTo({
         	url: '/pageTwo/login/login'
         })
         // that.$store.commit("changeUserLogin", true)
          return
        }
        uni.openBluetoothAdapter({
          success: e => {
            that.$store.commit("changeBluetooth", true);
            // if (that.devHomePram && that.devHomePram.t && that.devHomePram.sn) {
            //   that.$tools.handlePages(that.devHomePram.t, that.devHomePram.sn)
            //   return
            // }
            uni.navigateTo({
              url: "/pages/search/devType"
            })
            console.log('初始化蓝牙成功:' + e.errMsg);
          },
          fail: err => {
            console.log('初始化蓝牙失败:' + err.errMsg);
            return this.$tools.getBluetoothAdapter(err)
          }
        });
      },
      // 切换
      handleToggle(index) {
        let that = this
        if (!that.MeasureResult) return
        let str = this.weightInfo.infoList(that.MeasureResult).slice(1, 14)
        for (var i = 0; i < str.length; i++) {
          if (i == index) {
            if (index == 0 && str[0].showCon == false) {
              str[0].showCon = true
            } else {
              str[i].showCon = !str[i].showCon
            }
          } else {
            str[i].showCon = false
          }
        }
        that.infoList = this.weightInfo.infoList(that.MeasureResult).slice(1, 14)
      },
      // 工具
      clickTool(ind) {
        let that = this
        if (!that.token) {
          uni.redirectTo({
          	url: '/pageTwo/login/login'
          })
          // that.$store.commit("changeUserLogin", true)
          return
        }
        if (ind == 0) {
          that.$store.commit("changeRecord", true)
          return
        }
        if (ind == 1) {
          uni.navigateTo({
            url: "/pageTwo/survey/survey"
          })
          return
        }
        if (ind == 2 && that.configBox.referappid) {
          console.log("跳转儿童小程序", uni.getStorageSync('userid'))
          uni.navigateToMiniProgram({
            appId: that.configBox.referappid,
            path: 'pages/index/index?userid=' + uni.getStorageSync('userid'),
            // envVersion: "develop",
            extraData: {},
          })
          return
        }
        if (ind == 3) {
          uni.navigateTo({
            url: "/pageTwo/me/history"
          })
          return
        }
      },

      detail(e) {
        if (e.type == 1) {
          uni.navigateTo({
            url: "/pageTwo/zixun/detail?id=" + e.id
          })
          return
        }
        if (e.type == 2) {
          uni.navigateTo({
            url: "/pageTwo/zixun/detail?url=" + e.content
          })
          return

        }
        if (e.type == 3) {
          uni.navigateToMiniProgram({
            appId: e.content,
            path: e.path,
            extraData: {},
          })
          return
        }
      },
      // 登录
      handleLogin() {
        uni.redirectTo({
        	url: '/pageTwo/login/login'
        })
        // that.$store.commit("changeUserLogin", true)
      },
      handleDrawer() {
        this.$store.commit("changeDrawe", true);
      },
    },
    data() {
      return {
        fimages: [],
        userId: null,
        token: null,
        deviceId: "",
        isShowEle: 0,
        infoList: [],
        tmplIdList: [],
        toollist: [{
            icon: '/static/tool1.png',
            title: '手动记录',
            id: 0
          }, {
            icon: '/static/tool2.png',
            title: '体质评估',
            id: 1
          },
          {
            icon: '/static/tool3.png',
            title: '儿童测量',
            id: 2
          },
          {
            icon: '/static/tool4.png',
            title: '历史记录',
            id: 3
          },

        ],
        checkList: [{
            title: '每周提醒',
            index: 1,
          },
          {
            title: '每月提醒',
            index: 2,
          },
          {
            title: '半年提醒',
            index: 3,
          },
          {
            title: '一年提醒',
            index: 4,
          }
        ],
      }
    },
  }
</script>

<style scoped lang="scss">
  .content {
    margin-top: 115px;
    background-color: #f7f7f7;
    padding-bottom: 15px;

    // 工具
    .tools_l {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      padding-top: 10px;
      background: #fff;
      justify-content: space-between;

      .list {
        width: 25%;
        text-align: center;
        font-size: 14px;
        margin-bottom: 15px;

        .text {
          margin-top: 5px;
          color: #666;
          font-size: 12px;
        }
      }

      image {
        width: 35px;
        height: 35px;
      }
    }

    .myinfo {
      background: #fff;
      margin-top: 15px;
    }

    // 消息提醒

    .tipList {
      background: #fff;
      margin-top: 10px;

      .item_box {
        display: flex;
        align-items: center;
        align-content: center;
        flex-wrap: wrap;
        margin: 0 15px;
      }

      .item_box_tips {
        width: 50%;
        display: flex;
        align-items: center;
        justify-content: start;
        margin-bottom: 10px;

        .t-icon,
        .iconfont {
          width: 35px;
          height: 35px;
          margin-left: 10px;
        }
      }

      :nth-child(even).item_box_tips {
        text-align: right;
        justify-content: flex-end;
      }
    }

    // 标题
    .h2 {
      color: #333;
      font-weight: bold;
      padding: 10px 15px;
      font-size: 32rpx;
      display: flex;
      justify-content: space-between;

      text {
        display: inline-block;
        background: $btncolor;
        width: 8px;
        height: 12px;
        margin-right: 5px;
        font-size: 32rpx;
      }

      .more {
        font-size: 14px;
        font-weight: 500;
        color: #666;
      }
    }

    // banner
    .f_banner {
      width: 100%;
      height: 330rpx;
      margin-top: 30rpx;
      bottom: 52px;

      /deep/swiper {
        height: 330rpx;
      }

      image {
        width: 100%;
        height: 100%;
        background-size: 100%;
      }
    }

    .unusual {
      font-size: 14px;
      border-radius: 8px;
      text-align: center;
      color: #e83a1e;
      background: #f7e4c8;
      padding: 5px 0;
    }

    .introction {
      display: flex;
      margin-top: 10px;
      margin-left: 15px;
      font-size: 12px;
      color: #666;

      .t-icon {
        width: 15px;
        height: 15px;
        margin-right: 5px;

      }
    }

    .val0 {
      position: absolute;
      left: 40%;
      margin-left: 3px;
    }
  }
</style>
