<template>
  <div class="setting-container">
    <!-- nav -->
    <van-nav-bar title="参数设置" left-arrow :border="true" @click-left="onNavBack"> </van-nav-bar>
    <!-- main -->
    <div class="setting-main">
      <div class="top">
        <div
          class="setting-item"
          v-for="(item, index) in settingListTop"
          :key="index"
          @click="onRoute(item)"
          v-show="item.show"
        >
          <div class="left">
            <span
              >{{ item.name }} <span v-show="item.remark !== ''">({{ item.remark }})</span></span
            >
          </div>
          <div class="right">
            <img :src="rightIcon" alt="" />
          </div>
        </div>
      </div>
      <div class="bottom">
        <div
          class="setting-item"
          v-for="(item, index) in settingListBottom"
          :key="index"
          @click="onRoute(item)"
          v-show="item.show"
        >
          <div class="left">
            <span
              >{{ item.name }}<span v-show="item.remark !== ''">({{ item.remark }})</span></span
            >
          </div>
          <div class="right">
            <span>{{ item.powerStatus }}</span>
            <img :src="rightIcon" alt="" />
          </div>
        </div>
      </div>

      <div class="bottom">
        <div class="setting-item" v-for="(item, index) in settingListBottomUp" :key="index" @click="onRoute(item)">
          <div class="left">
            <span>{{ item.name }}({{ item.remark }})</span>
          </div>
          <div class="right">
            <span>{{ item.powerStatus }}</span>
            <img :src="rightIcon" alt="" />
          </div>
        </div>
      </div>
    </div>
    <!-- 弹窗 -->
    <van-dialog
      v-model="dialog.isDialogshow"
      :show-cancel-button="false"
      :show-confirm-button="true"
      confirm-button-text="返回"
    >
      <template #title>
        <div class="title">
          <span>{{ dialog.title }}</span>
        </div>
      </template>
      <template #default>
        <div class="dialog-container">
          <div class="selectConfirm">
            <div class="con">
              <p>请选择多少时间上报一次数据：</p>
              <div class="select-con" ref="select">
                <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 class="tips">
                <p>温馨提示：</p>
                <p>数字越小，越耗电，请慎重修改</p>
              </div>
            </div>
          </div>
        </div>
      </template>
    </van-dialog>

    <van-dialog
      v-model="isUserRoleDialogshow"
      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 userRoleData"
                :key="`selectUserRole${index}`"
                @click="onSelectUserRole(item)"
              >
                <div class="text">
                  <div v-html="item.text"></div>
                </div>
                <em :class="['circle', { on: selectUserConfirmActive == 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';
export default {
  name: '',
  data() {
    //   Do Not disturb
    return {
      settingListTop: [
        { name: '监护角色', iconUrl: '', className: 'userRole', routerName: '', remark: '', show: true },
        { name: '场景模式', iconUrl: '', className: 'sceneMode', routerName: 'sceneMode', remark: '', show: true },
        {
          name: '加强省电模式',
          iconUrl: '',
          className: 'deepPowerDownMode',
          routerName: 'deepPowerDownMode',
          remark: '',
          show: false
        },
        { name: '免扰设置', iconUrl: '', className: '', routerName: 'notDisturb', remark: '', show: false },
        {
          name: '健康信息登记',
          iconUrl: '',
          className: '',
          routerName: 'psychologicalRegUserInfos',
          remark: '',
          show: false
        },
        { name: '设备名片', iconUrl: '', className: '', routerName: 'equipmentCard', remark: '', show: false }
      ],
      settingListBottom: [
        {
          name: '定位监测',
          iconUrl: '',
          className: 'locationMonitor',
          routerName: 'locationMonitor',
          remark: '',
          powerStatus: '',
          show: true
        },
        {
          name: '危险区域监测',
          iconUrl: '',
          className: 'dangerAreaMonitor',
          routerName: 'dangerAreaMonitor',
          remark: '',
          powerStatus: '',
          show: true
        },
        {
          name: '健康监测',
          iconUrl: '',
          className: 'healthMonitor',
          routerName: 'healthMonitor',
          remark: '',
          powerStatus: '',
          show: true
        },
        {
          name: '血压监测',
          iconUrl: '',
          className: 'blood',
          routerName: 'blood',
          remark: '',
          powerStatus: '',
          show: true
        },
        {
          name: '心理监测',
          iconUrl: '',
          className: 'psychologicalSetting',
          routerName: 'psychologicalSetting',
          remark: '',
          show: true
        },
        {
          name: '佩戴监测',
          iconUrl: '',
          className: 'wearMonitor',
          routerName: 'wearMonitor',
          remark: '',
          powerStatus: '',
          show: true
        },
        {
          name: '久坐提醒',
          iconUrl: '',
          className: 'longSitReminder',
          routerName: 'longSitReminder',
          remark: '',
          powerStatus: '',
          show: false
        },
        {
          name: '抬腕亮屏',
          iconUrl: '',
          className: 'raiseToLightScreen',
          routerName: 'raiseToLightScreen',
          remark: '',
          powerStatus: '',
          show: false
        }
      ],
      userRoleData: [
        { text: '学生', value: 1 },
        { text: '老人', value: 2 }
      ],
      selectUserConfirmActive: 0,
      isUserRoleDialogshow: false,
      settingListBottomUp: [
        { name: '上报周期', iconUrl: '', className: 'uploadinteval', routerName: '', remark: '', powerStatus: '' }
      ],
      rightIcon: /* require('../../../assets/myself/health/right_more.png') */ '',
      dialog: {
        isDialogshow: false,
        title: '上报周期',
        confirmData: [
          {
            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
          }
        ]
      },
      selectConfirmActive: 0, // 弹窗选中
      uploadinteval: 60,
      roleId: null,
      version: 30071 //可以显示强省电模式设置菜单的设备的版本
    };
  },
  computed: {
    imei() {
      return this.$store.getters.serialNo;
    },
    iotCardTitle() {
      return this.$store.getters.iotCardTitle;
    },
    deviceVersion() {
      return this.$store.getters.deviceVersion;
    }
  },
  created() {
    /*  this.settingListBottom[6].show = process.env.NODE_ENV !== 'production'; */
    /*  this.settingListBottom[7].show = process.env.NODE_ENV !== "production"; */
    /* this.settingListTop[2].show =
      this.iotCardTitle === '零川' &&
      process.env.NODE_ENV !== 'production' &&
      parseInt(this.deviceVersion) > this.version; */
    this.loadRequest();
  },
  methods: {
    async loadRequest() {
      ToastService.loading({
        message: '数据加载中'
      });
      const allPromise = [
        this.getLocationConfig(),
        this.getHealthConfig(),
        this.getDrownConfig(),
        this.getNowearConfig(),
        this.getWatchConfig(),
        this.getPsychAbilityConfig(),
        this.getBloodConfig(),
        this.getUploadConfig(),
        this.getLongSitReminder()
      ];
      const promise = Promise.all(allPromise);
      try {
        const result = await promise;
        const isLoadAllSuccess = result.every(item => {
          return item;
        });
        if (isLoadAllSuccess) {
          ToastService.success({
            message: '数据加载完成',
            duration: 2000
          });
        } else {
          ToastService.clear();
          DialogService.comfirm({
            title: '提示',
            message: '数据加载失败，请重试'
          });
        }
      } catch (error) {
        console.log('error', error);
        ToastService.clear();
      }
    },
    onNavBack() {
      this.$router.push({
        name: 'Myself'
      });
    },
    onRoute(item) {
      if (this.modeId === 2 && item.className !== 'sceneMode' && item.className !== 'userRole') {
        DialogService.confirm({
          message: '当前模式为省电模式，请关闭省电模式后再操作',
          showCancelButton: true,
          cancelButtonText: '返回'
        });
      } else if (item.className === 'uploadinteval') {
        let selectIndex = this.dialog.confirmData.findIndex(item => {
          return item.value === this.uploadinteval;
        });
        this.selectConfirmActive = selectIndex;
        this.dialog.isDialogshow = true;
        // 2023.6.7 因弹窗参数减少，取消动态滚动
        /* setTimeout(() => {
                let selectScollEl = this.$refs.select;
                selectScollEl.scrollTop = this.getScroll(uploadinteval);
            },1000); */
      } else if (item.className === 'userRole') {
        let selectIndex = this.userRoleData.findIndex(item => {
          return item.value === this.roleId;
        });
        this.selectUserConfirmActive = selectIndex;
        this.isUserRoleDialogshow = true;
      } else if (
        item.routerName === 'psychologicalSetting' ||
        item.routerName === 'psychologicalRegUserInfos' ||
        item.routerName === 'blood'
      ) {
        this.$router.push({
          name: item.routerName,
          query: {
            from: 'watchSetting'
          }
        });
      } else if (item.routerName !== '') {
        this.$router.push({ name: item.routerName });
      }
    },
    getScroll(value) {
      console.log('value', value);
      if (value > 90) {
        return 600;
      } else if (value > 60 && value < 90) {
        return 350;
      } else if (value === 60) {
        return 120;
      } else if (value < 60) {
        return 10;
      }
    },
    onSelect(data) {
      console.log('选择了', data);
      this.selectConfirmActive = data.model;
      if (data.value === 10) {
        DialogService.confirm({
          message: '切换后数据更新更快、但耗电也高，确定切换吗?',
          showCancelButton: true
        })
          .then(() => {
            this.uploadinteval = data.value;
            this.setUploadConfig();
          })
          .catch(() => {});
      } else {
        this.uploadinteval = data.value;
        this.setUploadConfig();
      }
      this.dialog.isDialogshow = false;
    },
    // 获取设备上报参数
    getUploadConfig() {
      return new Promise((resolve, reject) => {
        APIHealthy.getUploadConfig({ imei: this.imei })
          .then(res => {
            console.log('获取上报参数', res);
            const data = res.data;
            if (data.data) {
              this.uploadinteval = data.data.uploadinteval;
              let selectIndex = this.dialog.confirmData.findIndex(item => {
                return item.value === data.data.uploadinteval;
              });
              console.log('selectIndex', selectIndex);
              this.selectConfirmActive = selectIndex;
              this.$store.commit('uploadinteval', data.data.uploadinteval);
              let index = this.settingListBottomUp.findIndex(item => {
                return item.className === 'uploadinteval';
              });
              this.settingListBottomUp[index].remark = data.data.uploadinteval + '分钟';
              /* ToastService.success({message: "加载成功"}); */
            }
            resolve(true);
          })
          .catch(() => {
            reject(false);
          });
      });
    },
    // 获取设备定位参数
    getLocationConfig() {
      return new Promise((resolve, reject) => {
        APIHealthy.getLocationConfig({ imei: this.imei })
          .then(res => {
            let data = res.data.data;
            if (data) {
              let index = this.settingListBottom.findIndex(item => {
                return item.routerName === 'locationMonitor';
              });
              this.settingListBottom[index].remark = data.enabled === 1 ? '打开' : '关闭';
              this.settingListBottom[index].powerStatus = data.enabled === 1 ? '耗电高' : '耗电低';
            }
            resolve(true);
          })
          .catch(() => {
            reject(false);
          });
      });
    },
    // 获取设备危险区域参数
    getDrownConfig() {
      return new Promise((resolve, reject) => {
        APIHealthy.getDrownConfig(this.imei)
          .then(res => {
            let data = res.data.data;
            if (data) {
              let index = this.settingListBottom.findIndex(item => {
                return item.routerName === 'dangerAreaMonitor';
              });
              this.settingListBottom[index].remark = data.config.enabled === 1 ? '打开' : '关闭';
              this.settingListBottom[index].powerStatus = data.config.enabled === 1 ? '耗电高' : '耗电低';
            }
            resolve(true);
          })
          .catch(() => {
            reject(false);
          });
      });
    },
    getPsychAbilityConfig() {
      return new Promise((resolve, reject) => {
        APIHealthy.getPsychAbilityConfig(this.imei)
          .then(res => {
            let data = res.data.data;
            let index = this.settingListBottom.findIndex(item => {
              return item.routerName === 'psychologicalSetting';
            });
            if (data) {
              this.settingListBottom[index].remark = data.enabled === 1 ? '打开' : '关闭';
              this.settingListBottom[index].powerStatus = data.enabled === 1 ? '耗电高' : '耗电低';
            } else {
              this.settingListBottom[index].remark = '关闭';
              this.settingListBottom[index].powerStatus = '耗电低';
            }
            resolve(true);
          })
          .catch(() => {
            reject(false);
          });
      });
    },
    // 获取设备健康参数
    getHealthConfig() {
      return new Promise((resolve, reject) => {
        APIHealthy.getHealthConfig({ imei: this.imei })
          .then(res => {
            let data = res.data.data;
            if (data) {
              let index = this.settingListBottom.findIndex(item => {
                return item.routerName === 'healthMonitor';
              });
              let healthEnablelist = [
                { enabled: data.config.heartrateenabled },
                { enabled: data.config.spo2enabled },
                { enabled: data.config.temperatureenabled }
              ];
              console.log('healthEnablelist', healthEnablelist);
              // 获取健康设置打开的次数
              const healthSettingCount = healthEnablelist.reduce((acc, cur) => (cur.enabled === 1 ? ++acc : acc), 0);
              console.log('healthSettingCount', healthSettingCount);
              this.settingListBottom[index].remark =
                healthSettingCount >= 3 ? '打开' : healthSettingCount >= 1 ? '部分' : '关闭';
              this.settingListBottom[index].powerStatus =
                healthSettingCount > 2 ? '耗电高' : healthSettingCount === 2 ? '耗电中' : '耗电低';
            }
            resolve(true);
          })
          .catch(() => {
            reject(false);
          });
      });
    },
    // 获取设备佩戴检测参数
    getNowearConfig() {
      return new Promise((resolve, reject) => {
        APIHealthy.getNowearConfig(this.imei)
          .then(res => {
            let data = res.data.data;
            if (data) {
              let index = this.settingListBottom.findIndex(item => {
                return item.routerName === 'wearMonitor';
              });
              this.settingListBottom[index].remark = data.enabled === 1 ? '打开' : '关闭';
              this.settingListBottom[index].powerStatus = data.enabled === 1 ? '耗电高' : '耗电低';
            }
            resolve(true);
          })
          .catch(() => {
            reject(false);
          });
      });
    },
    // 设置设备数据上报周期
    setWatchConfig(value) {
      if (value) {
        ToastService.loading({ message: '设置中' });
      }
      let reqBody = {
        imei: this.imei,
        roleId: this.roleId,
        modeId: this.modeId
      };
      console.log('reqBody', reqBody);
      APIHealthy.setWatchConfig(reqBody)
        .then(res => {
          console.log('设置上报参数', res);
          const data = res.data;
          if (data.stateCode === 1) {
            if (value) {
              ToastService.success({ message: '设置成功' });
            }
            this.getWatchConfig();
            this.getHealthConfig();
          } else {
            DialogService.confirm({
              title: '设置失败',
              message: `${res.data.message}`
            });
          }
        })
        .catch(error => {
          console.log('接口报错了', error);
        })
        .finally(() => {
          ToastService.clear();
        });
    },
    // 获取设备场景模式参数
    getWatchConfig() {
      return new Promise((resolve, reject) => {
        APIHealthy.getWatchConfig(this.imei)
          .then(res => {
            let data = res.data.data;
            if (data) {
              console.log('场景模式', data);
              const modeId = data.modeId;
              const roleId = data.roleId;
              this.modeId = data.modeId;
              this.roleId = roleId;
              this.$store.commit('watchRole', roleId);
              this.settingListTop[0].remark = roleId === 1 ? '学生' : '老人';
              this.settingListTop[1].remark = this.getModeById(modeId);
            } else {
              this.modeId = 1;
              this.roleId = 1;
              this.$store.commit('watchRole', 1);
              this.setWatchConfig(false);
            }
            resolve(true);
          })
          .catch(() => {
            reject(false);
          });
      });
    },
    // 获取设备血压周期性参数
    getBloodConfig() {
      return new Promise((resolve, reject) => {
        APIHealthy.getBloodPressConfig(this.imei)
          .then(res => {
            let data = res.data.data;
            let index = this.settingListBottom.findIndex(item => {
              return item.routerName === 'blood';
            });
            if (data) {
              this.settingListBottom[index].remark = data.bloodPressenabled === 1 ? '打开' : '关闭';
              this.settingListBottom[index].powerStatus = data.bloodPressenabled === 1 ? '耗电高' : '耗电低';
            } else {
              this.settingListBottom[index].remark = '关闭';
              this.settingListBottom[index].powerStatus = '耗电低';
            }
            resolve(true);
          })
          .catch(() => {
            reject(false);
          });
      });
    },
    getRaiseToLightScreen() {
      APIHealthy.getRaiseToLightScreen(this.imei).then(res => {
        let data = res.data.data;
        let index = this.settingListBottom.findIndex(item => {
          return item.routerName === 'raiseToLightScreen';
        });
        if (data) {
          this.settingListBottom[index].remark = data.enabled === 1 ? '打开' : '关闭';
          this.settingListBottom[index].powerStatus = data.enabled === 1 ? '耗电高' : '耗电低';
        } else {
          this.settingListBottom[index].remark = '关闭';
          this.settingListBottom[index].powerStatus = '耗电低';
        }
      });
    },
    getLongSitReminder() {
      return new Promise((resolve, reject) => {
        APIHealthy.getLongSitReminder(this.imei)
          .then(res => {
            let data = res.data.data;
            let index = this.settingListBottom.findIndex(item => {
              return item.routerName === 'longSitReminder';
            });
            if (data) {
              this.settingListBottom[index].remark = data.enabled === 1 ? '打开' : '关闭';
              this.settingListBottom[index].powerStatus = data.enabled === 1 ? '耗电高' : '耗电低';
            } else {
              this.settingListBottom[index].remark = '关闭';
              this.settingListBottom[index].powerStatus = '耗电低';
            }
            resolve(true);
          })
          .catch(() => {
            reject(false);
          });
      });
    },
    // 通过模式id获取场景模式
    getModeById(id) {
      if (id === 1) {
        return '标准';
      } else if (id === 2) {
        return '省电';
      } else {
        return '个性';
      }
    },
    // 设置设备数据上报周期
    setUploadConfig() {
      /* let reg = /^[1-9]+[0-9]*$/;
        if(this.uploadinteval === '') {
            return DialogService.confirm({
                message: '上报周期不能为空'
            })
        } else if(!reg.test(this.uploadinteval)) {
            return DialogService.confirm({
                message: '上报周期只能为正整数'
            })
        } */
      ToastService.loading({ message: '设置中' });
      let reqBody = {
        imei: this.imei,
        uploadinteval: Number(this.uploadinteval)
      };
      APIHealthy.setUploadConfig(reqBody).then(res => {
        console.log('设置上报参数', res);
        this.$store.commit('uploadinteval', this.uploadinteval);
        ToastService.success({ message: '设置成功' });
        this.getUploadConfig();
        this.getWatchConfig();
      });
    },
    // 设置选择属性
    onSelectUserRole(value) {
      console.log('this.roleI', this.roleId);
      DialogService.confirm({
        message: '切换后默认参数会变化，确定要切换？',
        showCancelButton: true,
        cancelButtonText: '返回'
      })
        .then(() => {
          this.roleId = value.value;
          this.modeId = this.modeId === 3 ? 1 : this.modeId;
          this.isUserRoleDialogshow = false;
          this.setWatchConfig(true);
        })
        .catch(() => {});
    }
  }
};
</script>

<style scoped lang="scss">
.setting-container {
  height: 100vh;
  background-color: $background;
  overflow: hidden;
  .setting-main {
    height: calc(100vh - 160px);
    padding: 20px;
    background-color: $background;
    overflow: scroll;
    .top {
      background-color: white;
      .setting-item {
        height: 120px;
        padding: 0 40px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 2px solid #d2d0d0;
        .left {
          @include center();
          img {
            height: 45px;
            width: 45px;
            margin-right: 20px;
          }
          span {
            color: #282828;
            font-size: 34px;
          }
        }
        .right {
          @include center();
          img {
            height: 35px;
            width: 35px;
          }
        }
      }
    }
    .bottom {
      margin: 20px 0 40px 0;
      background-color: white;
      .setting-item {
        height: 120px;
        padding: 0 40px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 2px solid #d2d0d0;
        .left {
          @include center();
          img {
            height: 45px;
            width: 45px;
            margin-right: 20px;
          }
          span {
            color: #282828;
            font-size: 34px;
          }
        }
        .middle {
          span {
            color: #c0baba;
            font-size: 32px;
          }
        }
        .right {
          @include center();
          span {
            padding-right: 80px;
            color: #c0baba;
            font-size: 32px;
          }
          img {
            height: 35px;
            width: 35px;
          }
        }
      }
    }
  }
  .dialog-container {
    padding: 20px 60px;
    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%;
                  }
                }
              }
            }
          }
        }
      }
    }
    .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: 5px 0;
      color: #999;
    }
  }
  .title {
    font-size: 32px;
  }
}
</style>
