<template>
  <div class="location-monitor-container">
    <!-- nav -->
    <div class="nav-bar">
      <van-nav-bar title="血压监测" left-text="返回" @click-left="onNavBack" left-arrow>
        <template #right>
          <!-- <div class="setupClock_save" @click="onSubmit">保存</div> -->
          <van-button type="primary" @click="onSubmit" size="small">保存</van-button>
        </template>
      </van-nav-bar>
    </div>
    <!-- main -->
    <div class="main" v-if="isLoading">
      <!-- 血压 -->
      <div class="list">
        <div class="item" v-show="true">
          <div class="left">
            <span class="title">开启血压监测:</span>
          </div>
          <div class="right">
            <!-- <img :src="rightIcon" alt=""> -->
            <van-switch v-model="bloodConfig.bloodPressenabled" :active-color="$green" />
          </div>
        </div>

        <div class="item left-gray" v-show="bloodConfig.bloodPressenabled">
          <div class="left">
            <span class="title gray">检测周期:</span>
          </div>
          <div class="right" @click="onClick('bloodPressinteval')">
            <span>{{ formatInteval(bloodConfig.bloodPressinteval) }}</span>
            <img :src="rightIcon" alt="" />
          </div>
        </div>

        <div class="item left-gray" v-show="bloodConfig.bloodPressenabled">
          <div class="left">
            <span class="title gray">告警阈值-收缩压:</span>
          </div>
          <div class="right" @click="onClick('systolicmaxvalue')">
            <span>{{ bloodConfig.systolicmaxvalue }}</span>
            <img :src="rightIcon" alt="" />
          </div>
        </div>
        <div class="item alarmType left-gray" v-show="bloodConfig.bloodPressenabled">
          <div class="left">
            <span class="title gray">告警方式:</span>
          </div>
          <div class="right">
            <div class="checkbox-group">
              <van-checkbox
                name="bloodPressvibrateenabled"
                v-model="bloodConfig.bloodPressvibrateenabled"
                shape="square"
                direction="horizontal"
                >震动</van-checkbox
              >
              <van-checkbox
                name="bloodPresslcdenabled"
                v-model="bloodConfig.bloodPresslcdenabled"
                shape="square"
                direction="horizontal"
                >亮屏</van-checkbox
              >
            </div>
          </div>
        </div>
        <div class="item" v-show="false">
          <div class="left">
            <span class="title">修改登记信息</span>
          </div>
          <div class="right" @click="onUpdateInfos()">
            <span>修改</span>
            <img :src="rightIcon" alt="" />
          </div>
        </div>
      </div>
    </div>

    <!-- 弹窗 -->
    <van-dialog v-model="dialog.isDialogshow" show-cancel-button cancel-button-text="返回" :show-confirm-button="false">
      <template #title>
        <div class="title">
          <span>设置</span>
        </div>
      </template>
      <template #default>
        <div class="dialog-container">
          <div class="selectConfirm">
            <div class="con">
              <van-cell v-for="(item, index) in dialog.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 ToastService from '@/services/toast-service';
import DialogService from '@/services/dialog-service';
import APIHealthy from '@/api/heathly';
import APIDevice from '@/api/device';
import { isNull } from '@/services/utils-service';
export default {
  name: '',
  data() {
    return {
      rightIcon: require('../../../assets/img/health/right_more.png'),
      checked: false,
      sampleinteval: '', //上报频率-定位检测
      temperatureAlarmType: ['temperaturevibrateenabled', 'temperaturelcdenabled', 'temperaturereportenabled'], //体温告警方式
      heartrateAlarmType: ['heartratevibrateenabled', 'heartratelcdenabled', 'heartratereportenabled'], //心率
      spo2AlarmType: ['spo2vibrateenabled', 'spo2lcdenabled', 'spo2reportenabled'], //血氧
      dialog: {
        isDialogshow: false,
        title: '上报频率',
        confirmData: []
      },
      bloodConfig: {
        imei: '',
        bloodPressenabled: 0, //血压使能   0禁用  1启用
        bloodPressinteval: 360, //血压检测周期，单位分钟，最小10分钟，最大1400分钟，默认360分钟。设置时以10分钟为颗粒度
        systolicminvalue: 0, //血压收缩压告警的最小值，
        systolicmaxvalue: 140, //血压收缩压告警的最大值，
        diastolicminvalue: 0, //血压舒张压告警的最小值
        diastolicmaxvalue: 0, //血压舒张压告警的最大值
        bloodPressvibrateenabled: 0, //血压异常时是否震动 0禁用  1启用
        bloodPresslcdenabled: 0, //血压异常时是否亮屏 0禁用  1启用
        bloodPressreportenabled: 1 //血压异常时是否上报数据 0禁用  1启用
      },
      // todo 以下这些弹窗列表可以用函数生成
      //    检测周期时间数据
      // 15、30、60、120
      monitorList: [
        {
          text: '10分钟',
          model: 6,
          checked: false,
          value: 10
        },
        {
          text: '15分钟',
          model: 0,
          checked: false,
          value: 15
        },
        {
          text: '30分钟',
          model: 1,
          checked: false,
          value: 30
        },
        {
          text: '60分钟',
          model: 2,
          checked: false,
          value: 60
        },
        /*  {
                text: "120分钟",
                model: 3,
                checked: false,
                value: 120
                }, */
        {
          text: '6小时',
          model: 4,
          checked: false,
          value: 360
        },
        {
          text: '8小时',
          model: 5,
          checked: false,
          value: 480
        }
      ],
      //血压弹窗收缩压数据
      bloodMaxList: [
        {
          text: '120',
          model: 3,
          checked: false,
          className: 'circle',
          value: 120,
          name: '血压监测'
        },
        {
          text: '140',
          model: 0,
          checked: false,
          className: 'circle',
          value: 140,
          name: '血压监测'
        },
        {
          text: '160',
          model: 1,
          checked: false,
          className: 'circle',
          value: 160,
          name: '血压监测'
        },
        {
          text: '180',
          model: 2,
          checked: false,
          className: 'circle',
          value: 180,
          name: '血压监测'
        }
      ],
      //血压弹窗舒张值上限数据
      bloodMinList: [
        {
          text: '90',
          model: 0,
          checked: false,
          className: 'circle',
          value: 90,
          name: '血压监测'
        },
        {
          text: '100',
          model: 1,
          checked: false,
          className: 'circle',
          value: 100,
          name: '血压监测'
        },
        {
          text: '110',
          model: 2,
          checked: false,
          className: 'circle',
          value: 110,
          name: '血压监测'
        }
      ],
      selectConfirmActive: 0,
      currentDiallogName: '',
      isRegisterBlood: null, //是否已经登记个人信息
      isSetAgeAgain: null, //是否需要重新设置年龄
      isLoading: false
    };
  },
  computed: {
    imei() {
      return this.$store.getters.serialNo;
    },
    watchRole() {
      return this.$store.getters.watchRole;
    }
  },
  mounted() {
    this.getPersonData();
    this.getBloodConfig();
  },
  methods: {
    onNavBack() {
      let fromRouter = this.$route.query.from;
      this.$router.push({
        name: fromRouter ? fromRouter : 'watchSetting'
      });
    },
    onSubmit() {
      ToastService.loading({ message: '设置中' });
      /* if(!this.isRegisterBlood) {
            return DialogService.confirm({
                title: '信息提示',
                message: '使用血压监测功能前需要登记使用者信息，是否前往登记？',
                showCancelButton: true
            }).then(() => {
                this.$router.push({
                    name: 'registeUserInfos',
                    query: {
                        from: 'blood'
                    }
                });
            }).catch(() =>{})
        } */ /* else if(this.isSetAgeAgain) {
            // 2023.06.26 需求取消 小于16岁年龄限制
            return DialogService.confirm({
                title: '信息提示',
                message: '使用血压监测功能年龄最小需要大于16岁，是否需要前往登记？',
                showCancelButton: true
            }).then(() => {
                this.$router.push({
                    name: 'registeUserInfos',
                    query: {
                        from: 'blood'
                    }
                });
            }).catch(() =>{})
        } */
      let reqBody = { ...this.bloodConfig };
      Object.values(this.bloodConfig).filter((item, index) => {
        if (typeof item === 'boolean') {
          item = item === false ? 0 : 1;
          reqBody[Object.keys(this.bloodConfig)[index]] = item;
        } else {
          reqBody[Object.keys(this.bloodConfig)[index]] = item;
        }
      });
      reqBody.imei = this.imei;
      console.log('保存的数据', reqBody);
      APIHealthy.setBloodPressConfig(reqBody)
        .then(res => {
          if (res.data.stateCode === 1) {
            ToastService.success({ message: '设置成功' });
            let fromRouter = this.$route.query.from;
            setTimeout(() => {
              this.$router.push({
                name: fromRouter ? fromRouter : 'watchSetting'
              });
            }, 1500);
          } else {
            DialogService.confirm({
              title: '设置失败',
              message: `${res.data.message}`
            });
          }
        })
        .catch(e => {
          DialogService.confirm({
            title: '设置失败',
            message: `${e.message}`
          });
        })
        .finally(() => {
          setTimeout(() => {
            ToastService.clear();
          }, 1500);
        });
    },
    onSelect(data) {
      this.bloodConfig[this.currentDiallogName] = data.value;
      this.selectConfirmActive = data.model;
      this.dialog.isDialogshow = false;
    },
    onClick(name) {
      this.currentDiallogName = name;
      this.dialog.confirmData = [];
      const intevalList = ['temperatureinteval', 'spo2inteval', 'heartrateinteval', 'bloodPressinteval'];
      if (intevalList.includes(name)) {
        this.dialog.confirmData = this.monitorList;
      } else if (name === 'systolicmaxvalue') {
        // 血压-收缩压
        this.dialog.confirmData = this.bloodMaxList;
      } else if (name === 'bloodminvalue') {
        // 血压-舒张压
        this.dialog.confirmData = this.bloodMinList;
      }
      let seclectIndex = this.dialog.confirmData.findIndex(item => {
        return item.value === this.bloodConfig[name];
      });
      this.selectConfirmActive = seclectIndex;
      this.dialog.isDialogshow = true;
    },
    getResult(number1, number2) {
      const result = parseInt(number1) / parseInt(number2);
      return result.toString().indexOf('.') != -1 ? parseInt(result).toFixed(2).slice(0, 1) : result;
    },
    getPersonData() {
      APIDevice.getPersonInfo({
        userId: this.$store.getters.userId,
        deviceId: this.$store.getters.deviceId
      })
        .then(res => {
          let data = res.data;
          if (isNull(data.gender) || data.height === 0 || data.weight === 0 || isNull(data.bornDate)) {
            this.isRegisterBlood = false;
            // 未进行信息登记，无法使用血压周期性下发功能
            // 2023.08.04 血压个人资料不完整，跳转个人信息等级页面
            setTimeout(() => {
              this.$router.push({
                name: 'registeUserInfos',
                query: {
                  from: 'blood',
                  backRouter: 'watchSetting'
                }
              });
            }, 1500);
          } else {
            // 2023.06.26 需求取消 小于16岁年龄限制
            /* if(isNotNull(data.age)) {
                    if(Number(data.age) < 16) {
                        // 血压限制 大于 >16,需要重新设置年龄
                        this.isSetAgeAgain = true;
                    }
                } */
            this.isRegisterBlood = true;
          }
        })
        .catch(e => {
          console.log('e', e);
          DialogService.confirm({
            message: `${e.message}`
          });
        })
        .finally(() => {
          setTimeout(() => {
            ToastService.clear();
            this.isLoading = true;
          }, 1500);
        });
    },
    getBloodConfig() {
      ToastService.loading({ message: '数据加载中' });
      APIHealthy.getBloodPressConfig(this.imei)
        .then(res => {
          let data = res.data.data;
          if (data) {
            let bloodConfig = data;
            this.bloodConfig.bloodPressenabled = bloodConfig.bloodPressenabled === 1;
            this.bloodConfig.bloodPressinteval = bloodConfig.bloodPressinteval;
            this.bloodConfig.systolicminvalue = bloodConfig.systolicminvalue;
            this.bloodConfig.systolicmaxvalue = bloodConfig.systolicmaxvalue;
            this.bloodConfig.diastolicminvalue = bloodConfig.diastolicminvalue;
            this.bloodConfig.diastolicmaxvalue = bloodConfig.diastolicmaxvalue;
            this.bloodConfig.bloodPressvibrateenabled = bloodConfig.bloodPressvibrateenabled === 1;
            this.bloodConfig.bloodPresslcdenabled = bloodConfig.bloodPresslcdenabled === 1;
            this.bloodConfig.bloodPressreportenabled = bloodConfig.bloodPressreportenabled === 1;
          } else {
            //1 是学生 2是老人
            this.bloodConfig.systolicmaxvalue = this.watchRole === 1 ? 120 : 140;
            this.bloodConfig.bloodPressinteval = this.watchRole === 1 ? 360 : 60;
          }
          ToastService.success({ message: '数据加载完成' });
        })
        .catch(e => {
          console.log('e', e);
          ToastService.clear();
          DialogService.confirm({
            message: `${e.message}`
          });
        });
    },
    onUpdateInfos() {
      this.$router.push({
        name: 'registeUserInfos',
        query: {
          from: 'blood'
        }
      });
    },
    // 格式化某些特殊参数值的时间显示方式
    formatInteval(value) {
      return value >= 360 ? value / 60 + '小时' : value + '分钟';
    }
  }
};
</script>

<style scoped lang="scss">
.location-monitor-container {
  height: 100vh;
  overflow: hidden;
  /* padding: 0 20px; */
  .nav-bar {
    height: 100px;
    padding: 0 20px;
  }
  .main {
    height: calc(100vh - 160px);
    background-color: $background;
    padding: 20px;
    overflow: scroll;
    .list {
      height: auto;
      background-color: #fff;
      border-radius: 8px;
      margin-bottom: 20px;
      .item {
        height: auto;
        padding: 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 2px solid #e5e5e5;
        .left {
          @include center();
          span {
            color: #282828;
            font-size: 32px;
          }
          .title {
            font-weight: 450;
            &.gray {
              color: gray;
            }
          }
        }
        .right {
          /* width: 60%; */
          @include center();
          font-size: 32px;
          img {
            height: 35px;
            width: 35px;
          }
          span {
            font-size: 32px;
            margin-right: 10px;
            color: #aaaaaa;
          }
          .checkbox-group {
            @include center();
            .van-checkbox {
              padding: 5px;
            }
          }
        }
        &.left-gray {
          padding-left: 30px;
          color: gray;
        }
        &.alarmType {
          height: 180px;
          display: flex;
          justify-content: flex-start;
          align-items: flex-start;
          .left {
          }
          .right {
            margin-left: 40px;
            width: 60%;
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
          }
        }
      }
    }
  }
  .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>
