<template>
  <div class="registe-user-infos-container">
    <div class="nav-bar">
      <NavBar
        :title="navBarTitle"
        @on-click-left="onNavBack"
        :leftText="leftText"
        :leftArrow="leftText !== ''"
      ></NavBar>
    </div>
    <div class="main">
      <div class="list">
        <div class="avatar">
          <div class="avatar-con" @click="chooseImage">
            <div class="avatar-img">
              <img :src="imagePath" alt="" />
            </div>
            <div class="avatar-text">
              <span>设置头像</span>
            </div>
          </div>
        </div>
        <div class="item">
          <div class="left importance">
            <span class="title gray">用户昵称:</span>
          </div>
          <div class="right" @click="onClick">
            <input type="text" maxlength="6" v-model.trim="personData.nickName" placeholder="请输入昵称" />
            <img :src="rightIcon" alt="" />
          </div>
        </div>
        <div class="item">
          <div class="left importance">
            <span class="title gray">性别:</span>
          </div>
          <div class="right" @click="onClick('gender')">
            <span>{{ unshiftGender(personData.gender) || '请输入' }}</span>
            <img :src="rightIcon" alt="" />
          </div>
        </div>

        <div class="item">
          <div class="left importance">
            <span class="title gray">身高(cm):</span>
          </div>
          <div class="right" @click="onClick('height')">
            <!-- <span>{{ height }}</span> -->
            <input
              type="number"
              placeholder="请输入身高"
              oninput="if(value.length>3)value=value.slice(0,3)"
              onKeypress="return(/[\d]/.test(String.fromCharCode(event.keyCode)))"
              v-model.trim="personData.height"
            />
            <img :src="rightIcon" alt="" />
          </div>
        </div>

        <div class="item">
          <div class="left importance">
            <span class="title gray">体重(kg):</span>
          </div>
          <div class="right" @click="onClick('weight')">
            <input
              type="number"
              placeholder="请输入体重"
              oninput="if(value.length>3)value=value.slice(0,3)"
              onKeypress="return(/[\d]/.test(String.fromCharCode(event.keyCode)))"
              v-model.trim="personData.weight"
            />
            <img :src="rightIcon" alt="" />
          </div>
        </div>

        <div class="item">
          <div class="left importance">
            <span class="title gray">出生日期:</span>
          </div>
          <div class="right" @click="onClick('bornDate')">
            <span>{{ formatBorndate(handleData(personData.bornDate)) || '请输入' }}</span>
            <img :src="rightIcon" alt="" />
          </div>
        </div>

        <div class="item">
          <div class="left importance">
            <span class="title gray">职业:</span>
          </div>
          <div class="right" @click="onClick('profession')">
            <span>{{ calcProfession(personData.profession) || '请选择' }}</span>
            <img :src="rightIcon" alt="" />
          </div>
        </div>

        <div class="item isHasBlood">
          <div class="left importance">
            <span class="title gray">是否有高血压史:</span>
          </div>
          <div class="right">
            <!-- <img :src="rightIcon" alt=""> -->
            <van-radio-group v-model="personData.ishypertension" direction="horizontal">
              <van-radio name="1" :checked-color="$green">有过</van-radio>
              <van-radio name="0" :checked-color="$green">没有</van-radio>
            </van-radio-group>
          </div>
        </div>

        <div class="item isHasBlood">
          <div class="left importance">
            <span class="title gray">作息是否规律:</span>
          </div>
          <div class="right">
            <van-radio-group v-model="personData.regularity" direction="horizontal">
              <van-radio name="1" :checked-color="$green">是</van-radio>
              <van-radio name="0" :checked-color="$green">否</van-radio>
            </van-radio-group>
          </div>
        </div>

        <div class="item isHasBlood">
          <div class="left importance">
            <span class="title gray">是否受到慢性病困扰:</span>
          </div>
          <div class="right">
            <van-radio-group v-model="personData.chronicDisease" direction="horizontal">
              <van-radio name="1" :checked-color="$green">是</van-radio>
              <van-radio name="0" :checked-color="$green">否</van-radio>
            </van-radio-group>
          </div>
        </div>
      </div>
      <div class="bottom-btn">
        <div class="btn" @click="onSubmit">{{ btnText }}</div>
      </div>
    </div>

    <!-- 时间选择器弹窗 -->
    <van-dialog v-model="isDateShow" :show-confirm-button="false" :close-on-click-overlay="true">
      <template #title>
        <div class="title">
          <span>出生日期</span>
        </div>
      </template>
      <template #default>
        <div class="date-dialog-container">
          <div class="date-bottom">
            <van-datetime-picker
              v-model="currentDate"
              type="date"
              :min-date="minDate"
              :max-date="maxDate"
              :visible-item-count="4"
              :show-toolbar="false"
            />
          </div>
          <div class="button-box">
            <!-- <div class="button" @click="onCancel">
                            <span>关闭</span>
                        </div> -->
            <div class="button">
              <div class="btn-item" @click="onCancelDate"><p class="cancel">返回</p></div>
              <div class="btn-item" @click="onConfirmDate"><p class="confirm">完成</p></div>
            </div>
          </div>
        </div>
      </template>
    </van-dialog>

    <!-- 性别选择弹窗 -->
    <van-dialog v-model="isConfirmShow" cancelButtonText="返回" show-cancel-button :show-confirm-button="false">
      <template #title>
        <div class="title">
          <span>{{ dialogTitle }}</span>
        </div>
      </template>
      <template #default>
        <div class="dialog-container">
          <div class="selectConfirm">
            <div class="con">
              <van-cell v-for="(item, index) in confirmData" :key="`selectVPT${index}`" @click="onSelect(item)">
                <div class="text">
                  <div v-html="item.text"></div>
                </div>
                <em :class="['circle', { on: selectConfirmActive == index }]"></em>
              </van-cell>
            </div>
          </div>
        </div>
      </template>
    </van-dialog>
  </div>
</template>

<script>
import APIDevice from '@/api/device';
import APIWx from '@/api/wx';
import APIHealthUser from '@/api/health-user';
import { isNotNull, isNull } from '@/services/utils-service';
import AppId from '@/config/appId';
import DialogService from '@/services/dialog-service';
import ToastService from '@/services/toast-service';
import NavBar from '@/components/NavBar.vue';
let wx = require('weixin-js-sdk');
export default {
  name: '',
  components: { NavBar },
  data() {
    return {
      isHasBlood: '1',
      userName: '',
      bornDate: '',
      gender: '男',
      height: '',
      weight: '',
      rightIcon: require('../../../assets/myself/health/right_more.png'),
      imagePath: '' || require('../../../assets/com-imges/55_03.png'),
      isDateShow: false,
      currentDate: '',
      minDate: '',
      maxDate: '',
      isConfirmShow: false,
      currentGender: '',
      genderConfirmData: [
        {
          text: '男',
          model: 0,
          checked: false,
          value: true
        },
        {
          text: '女',
          model: 1,
          checked: false,
          value: false
        }
      ],
      professionConfirmData: [
        {
          text: '互联网行业',
          model: 0,
          checked: false,
          value: '1'
        },
        {
          text: '教培行业',
          model: 1,
          checked: false,
          value: '2'
        },
        {
          text: '医警教行业',
          model: 2,
          checked: false,
          value: '3'
        },
        {
          text: '护理行业',
          model: 3,
          checked: false,
          value: '4'
        },
        {
          text: '法律行业',
          model: 4,
          checked: false,
          value: '5'
        },
        {
          text: '销售行业',
          model: 5,
          checked: false,
          value: '6'
        },
        {
          text: '封闭隔离行业',
          model: 6,
          checked: false,
          value: '7'
        },
        {
          text: '学生',
          model: 7,
          checked: false,
          value: '8'
        },
        {
          text: '小学生',
          model: 8,
          checked: false,
          value: '81'
        },
        {
          text: '初中生',
          model: 9,
          checked: false,
          value: '82'
        },
        {
          text: '高中生',
          model: 10,
          checked: false,
          value: '83'
        },
        {
          text: '自由职业',
          model: 11,
          checked: false,
          value: '9'
        },
        {
          text: '待业',
          model: 12,
          checked: false,
          value: '10'
        },
        {
          text: '其它',
          model: 13,
          checked: false,
          value: '11'
        }
      ],
      confirmData: [],
      selectConfirmActive: 0,
      personData: {
        Uid: '',
        DeviceSn: '',
        bornDate: '',
        height: null,
        weight: null,
        gender: null,
        profession: '',
        regularity: '1',
        chronicDisease: '0',
        ishypertension: '0'
      },
      btnText: '' || '下一步',
      currentDiallogName: '',
      dialogTitle: '',
      profession: '',
      uid: '',
      navBarTitle: '',
      params: {}
    };
  },
  computed: {
    leftText() {
      return this.params.from == 'login' ? '' : '返回';
    }
  },
  created() {
    this.loadParams();
    this.setMaxDate();
    this.getWxAutograph();
    this.navBarTitle = this.$route.query.from === 'psychologicalSetting' ? '登记佩戴者信息' : '添加成员';
  },
  mounted() {
    /* this.getPersonData(); */
  },
  methods: {
    // 加载微信jssdk
    getWxAutograph() {
      APIWx.createJSSDK({
        userId: this.$store.getters.userId,
        sUrl: window.location.href.split('#')[0],
        appId: AppId
      })
        .then(res => {
          let item = res.data.data;
          wx.config({
            debug: false,
            appId: item.appId,
            timestamp: item.timeStamp,
            nonceStr: item.nonceStr,
            signature: item.signature,
            jsApiList: ['chooseImage', 'uploadImage']
          });

          wx.ready(() => {});
        })
        .catch(err => {
          console.log(err);
        });
    },
    loadParams() {
      let params = this.$route.query;
      if (params) {
        this.params = { ...params };
        if (params.from === 'watchSetting' || params.isShowSubmit) {
          this.btnText = '保存';
        }
      }
    },
    setMaxDate() {
      let maxDate = new Date().setFullYear(new Date().getFullYear());
      let minDate = new Date().setFullYear(new Date().getFullYear() - 150);
      this.maxDate = new Date(maxDate);
      this.minDate = new Date(minDate);
      this.currentDate = new Date(maxDate);
    },
    getPersonData() {
      APIDevice.getPersonInfo({
        userId: this.$store.getters.userId,
        deviceId: this.$store.getters.deviceId || '398b4b34-221b-4fc9-a9fb-e7bec8876248'
      }).then(res => {
        console.log('用户信息', res);
        let data = res.data;
        this.personData = data;
        this.currentDate = data.bornDate ? new Date(data.bornDate) : this.currentDate;
        this.personData.height = data.height === 0 ? '' : data.height;
        this.personData.weight = data.weight === 0 ? '' : data.weight;
        this.personData.ishypertension = String(data.ishypertension);
        this.personData.chronicDisease = String(data.chronicDisease);
        this.personData.regularity = String(data.regularity);
        this.personData.profession = String(data.profession);
        this.currentGender = data.gender;
        this.uid = data.uid;
        /* ToastService.success({
                message: '数据加载完成'
            }) */
      });
    },
    onNavBack() {
      let toRouter = this.$route.query.toRouter;
      this.$router.push({
        name: toRouter ? toRouter : 'Index',
        notJump: true
      });
    },
    onClick(name) {
      this.currentDiallogName = name;
      if (name === 'bornDate') {
        this.isDateShow = true;
      } else if (name === 'gender') {
        this.confirmData = this.genderConfirmData;
        this.dialogTitle = '性别';
        this.selectConfirmActive = this.confirmData.findIndex(item => {
          return item.value == this.personData.gender;
        });
        this.isConfirmShow = true;
      } else if (name === 'profession') {
        this.confirmData = this.professionConfirmData;
        this.dialogTitle = '职业选择';
        this.selectConfirmActive = this.confirmData.findIndex(item => {
          return item.value == this.personData.profession;
        });
        this.isConfirmShow = true;
      }
    },
    onSubmit() {
      let data = this.personData;
      let intReg = /^[1-9]\d*$/;
      if (isNull(data.nickName)) {
        return DialogService.confirm({
          message: '昵称不能为空'
        });
      } else if (isNull(data.height) || data.height == 0 || !intReg.test(data.height)) {
        return DialogService.confirm({
          message: '身高不能为空,不能为0,\n不能存在小数点,只能是整数'
        });
      } else if (isNull(data.weight) || data.weight == 0 || !intReg.test(data.weight)) {
        return DialogService.confirm({
          message: '体重不能为空,不能为0,\n不能存在小数点,只能是整数'
        });
      } else if (isNull(data.bornDate)) {
        return DialogService.confirm({
          message: '出生日期不能为空'
        });
      } else if (isNull(data.profession) || data.profession === '0') {
        return DialogService.confirm({
          message: '职业不能为空'
        });
      }

      this.savePersonInfo();
    },
    savePersonInfo() {
      let personForm = { ...this.personData };
      let reqBody = {
        sourceType: 1,
        nickName: personForm.nickName,
        avatar: this.imagePath,
        level: 0,
        gender: personForm.gender == 'false' ? 0 : 1,
        height: Number(personForm.height),
        weight: Number(personForm.weight),
        birth: personForm.bornDate,
        education: Number(personForm.profession),
        isHypertension: personForm.ishypertension == '1',
        isScheduleRegular: personForm.regularity == '1',
        isChronicDisease: personForm.chronicDisease == '1'
      };
      console.log('请求的参数', reqBody);
      // eslint-disable-next-line no-unreachable
      ToastService.loading({
        message: '保存中'
      });
      APIHealthUser.addPerson(reqBody)
        .then(res => {
          ToastService.clear();
          console.log(res.data);
          if (res.data.stateCode == 1) {
            ToastService.success({
              message: '保存成功'
            });
            let from = this.params.from;
            if (from === 'watchSetting') {
              setTimeout(() => {
                this.$router.push({
                  name: 'watchSetting'
                });
              }, 1500);
            } else if (from === 'psychologicalSetting') {
              setTimeout(() => {
                this.$router.push({
                  name: 'psychologicalSetting',
                  from: 'watchSetting'
                });
              }, 1500);
            } else if (from === 'login' || from === 'Index') {
              setTimeout(() => {
                this.$router.push({
                  name: 'deviceBinding'
                });
              }, 1500);
            }
          } else {
            DialogService.confirm({
              title: res.data.message
            });
          }
        })
        .catch(e => {
          ToastService.clear();
          DialogService.confirm({
            title: e.message || '服务器异常'
          });
        });
    },
    onCancelDate() {
      this.isDateShow = false;
      //this.currentDate = new Date(this.$own.formatTime(this.personData.bornDate)).Format("yyyy-MM-dd");
    },
    // 通过职业的value值展示职业的中文昵称
    calcProfession(value) {
      let result = '';
      if (value !== '0' || value !== 0 || isNotNull(value) || value != '') {
        let index = this.professionConfirmData.findIndex(item => {
          return value === item.value;
        });
        if (index >= 0) {
          result = this.professionConfirmData[index].text;
        }
      }
      return result;
    },
    onConfirmDate() {
      this.isDateShow = false;
      this.personData.bornDate = new Date(this.currentDate).Format('yyyy-MM-dd');
    },
    onSelect(item) {
      this.personData[this.currentDiallogName] = item.value;
      if (this.currentDiallogName === 'profession') {
        this.profession = item.text;
      }
      this.personData[this.currentDiallogName] = item.value;
      this.selectConfirmActive = item.model;
      this.isConfirmShow = false;
    },
    unshiftGender(gender) {
      let sex = null;
      if (isNotNull(gender)) {
        if (gender == true) {
          sex = '男';
        } else {
          sex = '女';
        }
      } else {
        sex = '';
      }
      return sex;
    },
    handleData(val) {
      return val == null || val == '' || val == undefined || val == 'Unknown' ? '' : val;
    },
    formatBorndate(date) {
      return date == '' ? '' : new Date(this.$own.formatTime(date)).Format('yyyy-MM-dd');
    },
    chooseImage() {
      let that = this;
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: function (res) {
          var localIds = res.localIds[0];
          that.imagePath = localIds; //显示图片的
          wx.getLocalImgData({
            localId: localIds,
            success: function (res) {
              let localData = res.localData;
              if (localData.indexOf('data:image') < 0) {
                localData = 'data:image/jpeg;base64,' + localData;
              }
              localData = localData.replace(/\r|\n/g, '').replace('data:image/jgp', 'data:image/jpeg');
              that.imagePath = localData;
            }
          });
        }
      });
    }
  }
};
</script>
<style scoped lang="scss">
.registe-user-infos-container {
  height: 100vh;
  overflow: hidden;
  .main {
    height: calc(100vh - 100px);
    padding-top: 100px;
    background-color: #fff;
    .list {
      height: calc(100vh - 300px);
      position: relative;
      background-color: #fff;
      border-radius: 8px;
      overflow: scroll;
      .avatar {
        position: relative;
        height: 240px;
        @include center();
        .avatar-con {
          @include center();
          flex-direction: column;
          .avatar-img {
            height: 120px;
            width: 120px;
            border: 2px solid #333;
            border-radius: 50%;
            margin-bottom: 10px;
            img {
              height: inherit;
              width: inherit;
            }
          }
          .avatar-text {
            font-size: 36px;
            font-weight: bold;
          }
        }
      }
      .item {
        position: relative;
        height: 50px;
        padding: 20px 40px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #e5e5e5;
        .left {
          @include center();
          span {
            color: #282828;
            font-size: 32px;
          }
          .title {
            font-weight: 450;
            &.gray {
              color: #000;
            }
          }
          &.importance {
            span {
              &:after {
                content: '*';
                position: absolute;
                left: 10px;
                top: 40px;
                @include colorAndFont($red, 34);
                z-index: 1000;
              }
            }
          }
        }
        .right {
          width: 40%;
          display: flex;
          justify-content: flex-end;
          align-items: center;
          input {
            display: flex;
            width: 220px;
            height: 59px;
            color: #aaaaaa;
            font-size: 36px;
            text-indent: 10px;
            text-align: right;
            &::-webkit-input-placeholder {
              color: #aaaaaa;
              font-size: 30px;
            }
          }
          img {
            height: 35px;
            width: 35px;
          }
          span {
            font-size: 32px;
            margin-right: 10px;
            color: #aaaaaa;
          }
        }
        &.left-gray {
          padding-left: 30px;
          /* color: gray; */
        }
        &.isHasBlood {
          /* height: 120px; */
          display: flex;
          justify-content: space-between;
          align-items: center;
          .left {
          }
          .right {
            width: 50%;
            display: flex;
            justify-content: flex-end;
            align-items: flex-end;
            font-size: 32px;
          }
        }
      }
    }
    .bottom-btn {
      position: absolute;
      bottom: -60px;
      left: 0;
      height: 100px;
      width: 100%;
      @include center();
      z-index: 999;
      clear: both;
      .btn {
        position: relative;
        height: 90px;
        width: 560px;
        background-color: $green;
        color: #fff;
        font-size: 48px;
        border-radius: 50px;
        @include center();
      }
    }
  }
  .dialog-container {
    padding: 30px 40px 0 40px;
    font-size: 32px;
    .selectConfirm {
      flex: 1;
      width: 100%;
      overflow: scroll;
      padding: 0;
      .con {
        flex: 1;
        max-height: 550px;
        width: 100%;
        overflow: scroll;
      }
    }
  }
  .date-dialog-container {
    padding: 30px 40px 0 40px;
    font-size: 32px;
    .selectConfirm {
      height: 550px;
      width: 100%;
      overflow: scroll;
      padding: 0;
    }
    .con {
      height: 550px;
      width: 100%;
      overflow: scroll;
      padding-bottom: 20px;
      border-bottom: 1px solid #999;
      .con-item {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding: 20px 0;
        label {
          margin-right: 15px;
        }
        .cloose {
          height: 40px;
          padding: 10px;
          background-color: $green;
          font-size: 28px;
          color: #fff;
          /* border-radius: 20px; */
          border-bottom-left-radius: 15px;
          border-top-left-radius: 15px;
          @include center();
        }
        .birthday {
          height: 60px;
          width: 220px;
          background-color: $background;
          border-bottom-right-radius: 15px;
          border-top-right-radius: 15px;
          @include center();
        }
        input {
          margin-left: 15px;
          display: flex;
          width: 200px;
          height: 72px;
          text-indent: 15px;
          border-bottom: 1px solid #000;
        }
      }
      .select-con {
        height: 400px;
        overflow: scroll;
        padding: 15px 0;
      }
      .tips {
        margin: 15px 0;
      }
    }
    .button {
      height: 80px;
      @include center();
      p {
        font-size: 32px;
        color: #000;
      }
    }
    .input-con {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      label {
        color: #000;
      }
      input {
        // width: 100%;
        margin-left: 15px;
        display: flex;
        width: 80px;
        height: 72px;
        text-indent: 15px;
        border-bottom: 1px solid #000;
      }
    }
    p {
      font-size: 32px;
      margin: 15px 0;
      color: #999;
    }
    .error-tips {
      color: red;
    }
    .button-box {
      position: absolute;
      bottom: 0;
      height: 90px;
      width: 100%;
      z-index: 999;
      background-color: #fff;
      @include center();
      .button {
        width: 100%;
        display: flex;
        justify-content: space-around;
        align-items: center;
        .btn-item {
          width: 200px;
          p {
            font-size: 32px;
            height: 80px;
            width: 100%;
            color: #000;
            @include center();
          }
          .confirm {
            color: $green;
          }
          .delete {
            color: red;
          }
          .cancel {
            color: #000;
          }
        }
      }
    }
    .button {
      display: flex;
      justify-content: space-around;
      align-items: center;
      p {
        width: 40%;
        color: #000;
        @include center();
      }
      .confirm {
        color: $green;
      }
    }
  }
  .title {
    font-size: 32px;
  }
  .selectConfirm {
    padding: 0;
    .con {
      .van-cell {
        height: 60px;
        .van-cell__value {
          em {
            font-style: normal;
            position: absolute;
            top: 0;
            right: 0;
            @include colorAndFont(#999, 24);
            &.circle {
              width: 20px;
              height: 20px;
              border: 2px solid #bfbfbf;
              border-radius: 50%;
              position: absolute;
              right: 15px;

              &.on {
                border-color: $green;

                &:before {
                  content: '';
                  position: absolute;
                  left: 50%;
                  top: 50%;
                  transform: translate(-50%, -50%);
                  width: 14px;
                  height: 14px;
                  background: $green;
                  border-radius: 50%;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
