<template>
  <div class="psychological-setting-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>
                </template> -->
      </van-nav-bar>
    </div>
    <!-- main -->
    <div class="main">
      <div class="list">
        <div class="item">
          <div class="left">
            <span class="title">开启心理监测</span>
          </div>
          <div class="right">
            <van-switch v-model="enabled" :active-color="$green" />
          </div>
        </div>
        <div class="item left-gray" v-show="enabled">
          <div class="left">
            <span class="title">设备显示:</span>
          </div>
          <div class="right">
            <!-- <img :src="rightIcon" alt=""> -->
            <van-switch v-model="checked" :active-color="$green" />
          </div>
        </div>

        <!--  <div class="item left-gray" >
                    <div class="left">
                        <span class="title gray">检测周期:</span>
                    </div>
                    <div class="right" @click="onClick('interval')">
                        <span>{{ interval }}分钟</span>
                        <img :src="rightIcon" alt="">
                    </div>
                </div> -->
        <div class="item time left-gray" v-show="enabled">
          <div class="left">
            <span class="title">监测时段:</span>
          </div>
          <div class="right time">
            <div class="time-item" @click="onClickDate('add')" v-show="date.dateList.length < 4">
              <span>添加时段</span>
              <img :src="rightIcon" alt="" />
            </div>
            <!-- <div class="time-item date" v-for="(item, index) in date.dateList" :key="index" @click="onClickDate('update', item)">
                                    <span>{{ item.startTime }} - {{ item.endTime }}</span>
                                    <img :src="rightIcon" alt="">
                                    <template slot="right">
                                        <van-button square type="danger" text="返回" />
                                    </template>
                        </div>

                        <div class="time-item" v-show="date.dateList.length === 10">
                            <span>监测时段最大可设置10个</span>
                        </div> -->
          </div>
        </div>

        <div class="item time-list" v-show="enabled">
          <div class="date-time" v-for="(item, index) in date.dateList" :key="index">
            <div class="time-left" @click="onClickDate('update', item)">
              <div class="left">
                <span>时段{{ index + 1 }}:</span>
              </div>
              <div class="right">
                <div class="border">{{ item.startTime }}</div>
                <span> - </span>
                <div class="border">{{ item.endTime }}</div>
              </div>
            </div>

            <div class="time-right">
              <div class="left">
                <span>时长:</span>
                <input
                  type="tel"
                  maxlength="2"
                  v-model="item.duration"
                  @input="onInput(index)"
                  oninput="value=value.replace(/e|-|\+/ig,'').replace(/[^0-9]/ig,'').replace(/\s+/g,'')"
                />
                <span>小时</span>
              </div>
              <div class="right">
                <img :src="rightIcon" alt="" />
              </div>
            </div>
          </div>
        </div>

        <!-- 提醒设置 -->
        <div class="item left-gray" v-show="enabled">
          <div class="left">
            <span class="title">提醒设置:</span>
          </div>
          <div class="right">
            <van-switch v-model="reminderChecked" :active-color="$green" />
          </div>
        </div>

        <div class="item left-gray" v-show="enabled">
          <div class="left">
            <span class="title gray">抑郁等级:</span>
          </div>
          <div class="right" @click="onClick('depressive')">
            <span>{{ formatReminder(setting.depressive) || '请选择' }}</span>
            <img :src="rightIcon" alt="" />
          </div>
        </div>

        <div class="item left-gray" v-show="enabled">
          <div class="left">
            <span class="title gray">压力等级:</span>
          </div>
          <div class="right" @click="onClick('pressure')">
            <span>{{ formatReminder(setting.pressure) || '请选择' }}</span>
            <img :src="rightIcon" alt="" />
          </div>
        </div>

        <div class="item left-gray" v-show="enabled">
          <div class="left">
            <span class="title gray">疲劳等级:</span>
          </div>
          <div class="right" @click="onClick('fatigue')">
            <span>{{ formatReminder(setting.fatigue) || '请选择' }}</span>
            <img :src="rightIcon" alt="" />
          </div>
        </div>

        <div class="item alarmType left-gray" v-show="enabled">
          <div class="left">
            <span class="title gray">提醒方式:</span>
          </div>
          <div class="right">
            <div class="checkbox-group">
              <van-checkbox name="a" shape="square" v-model="vibrateenabled" direction="horizontal">震动</van-checkbox>
              <van-checkbox name="b" shape="square" v-model="lcdenabled" direction="horizontal">亮屏</van-checkbox>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- bottom -->
    <div class="bottom">
      <div class="btn" @click="onPre" v-show="!showSubmit">上一步</div>
      <div class="btn" @click="onNext" v-show="!showSubmit">下一步</div>
      <div class="btn submit" @click="onSubmit" v-show="showSubmit">保存</div>
    </div>
    <!-- 弹窗 -->
    <van-dialog v-model="dialog.isDialogshow" show-cancel-button :show-confirm-button="false">
      <template #title>
        <div class="title">
          <span>{{ dialog.title }}</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>

    <!-- 时间选择器弹窗 -->
    <van-dialog v-model="dateDialog.show" :show-confirm-button="false" :close-on-click-overlay="true" @close="onCancel">
      <template #default>
        <div class="date-dialog-container">
          <div class="date-top">
            <div :class="['top-item', { active: date.currentCount === 0 }]" @click="onChooseDate(0)">
              <span>开始时段</span>
            </div>
            <div :class="['top-item', { active: date.currentCount === 1 }]" @click="onChooseDate(1)">
              <span>结束时段</span>
            </div>
          </div>
          <div class="date-bottom">
            <van-datetime-picker
              v-show="date.currentCount === 0"
              v-model="date.defaultStartTime"
              type="time"
              :formatter="formatter"
              :show-toolbar="false"
              :item-height="itemHeight"
              :visible-item-count="4"
            />
            <van-datetime-picker
              v-show="date.currentCount === 1"
              v-model="date.defaultEndTime"
              type="time"
              :formatter="formatter"
              :show-toolbar="false"
              :item-height="itemHeight"
              :visible-item-count="4"
            />
          </div>
          <div class="button-box">
            <!-- <div class="button" @click="onCancel">
                            <span>关闭</span>
                        </div> -->
            <div class="button">
              <div class="btn-item" @click="onCancel" v-show="date.action !== 'update'"><p class="cancel">返回</p></div>
              <div class="btn-item" @click="onDelete" v-show="date.action === 'update'"><p class="delete">删除</p></div>
              <div class="btn-item" @click="onConfirm(date.dateList.length)"><p class="confirm">完成</p></div>
            </div>
          </div>
        </div>
      </template>
    </van-dialog>

    <!-- 涉水停留告警间隔弹窗 -->
    <van-dialog
      v-model="isWearDialogshow"
      :close-on-click-overlay="false"
      :show-cancel-button="false"
      :show-confirm-button="false"
    >
      <template #title>
        <div class="title">
          <span>检测周期</span>
        </div>
      </template>
      <template #default>
        <div class="wear-dialog-container">
          <div class="selectConfirm">
            <div class="con">
              <p>请输入时间：</p>
              <div class="input-con">
                <label for="">检测周期: </label>

                <input type="text" maxlength="2" oninput="value=value.replace(/\s+/g,'')" v-model.trim="interval" />
                <label for="">分钟 </label>
              </div>
              <!-- <p>温馨提示：</p> -->
              <!-- <p>设置范围：30~500之间</p> -->
              <p class="error-tips">{{ warningDistanceTips }}</p>
            </div>
            <div class="button">
              <p @click="onCancelWear">返回</p>
              <p @click="onConfirmWear" class="confirm">确认</p>
            </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 { checkPeriodExist, isNotNull, isNull } from '@/services/utils-service';
export default {
  name: '',
  data() {
    return {
      rightIcon: require('../../../assets/myself/health/right_more.png'), //右边图标
      checked: null, //是否选中
      interval: 60, //检测周期-定位检测
      alarmType: ['reportenabled'], //告警方式
      reportenabled: true, //是否上报数据,默认为true
      //    弹窗内容
      dialog: {
        isDialogshow: false,
        title: '告警等级',
        confirmData: [
          /* {
                text: "不告警",
                model: 3,
                checked: false,
                value: 0
                }, */
          {
            text: '轻度',
            model: 0,
            checked: false,
            value: 1
          },
          {
            text: '中度',
            model: 1,
            checked: false,
            value: 2
          },
          {
            text: '重度',
            model: 2,
            checked: false,
            value: 3
          }
        ]
      },
      //    日期弹窗内容
      dateDialog: {
        show: false
      },
      //    日期时间
      date: {
        action: '',
        model: null,
        defaultStartTime: '07:00',
        defaultEndTime: '23:00',
        currentCount: 0,
        currentDuration: '',
        dateList: [
          { startTime: '07:00', endTime: '23:00', model: 0, duration: 6 }
          /* { startTime: '08:00', endTime: '21:00', model: 0, reqTime: '08002100' },
                { startTime: '08:00', endTime: '21:00', model: 0, reqTime: '08002100' },
                { startTime: '08:00', endTime: '21:00', model: 0, reqTime: '08002100' },
                { startTime: '08:00', endTime: '21:00', model: 0, reqTime: '08002100' }, */
        ]
      },
      selectConfirmActive: 0, // 弹窗选中
      itemHeight: Number(((document.body.clientWidth / 750) * 95).toFixed()), // 日历组件item高度
      warningDistanceTips: '',
      isWearDialogshow: false,
      currentInterval: null,
      radioModel: '1',
      lcdenabled: false, //亮屏
      vibrateenabled: false, //震动
      setting: {
        depressive: 1,
        pressure: 1,
        fatigue: 1
      },
      currentReminder: '',
      currentDuration: '',
      durationList: [{ duration: '' }, { duration: '' }, { duration: '' }, { duration: '' }, { duration: '' }],
      showSubmit: null,
      reminderChecked: null, //提醒设置
      enabled: null, //心理监测开始与关闭
      isCompleted: null, //心理监测资料是否填写完整
      uid: ''
    };
  },
  watch: {
    interval: {
      handler(n) {
        let reg = /^[1-9]+[0-9]*$/;
        if (n === '') {
          this.warningDistanceTips = '检测周期不能为空';
          this.isCanSave = false;
        } else if (!reg.test(n)) {
          this.warningDistanceTips = '检测周期只能为整数';
          this.isCanSave = false;
        } else if (parseInt(n) < 3 || parseInt(n) > 60) {
          this.warningDistanceTips = '请输入3-60的整数';
          this.isCanSave = false;
        } else {
          this.warningDistanceTips = '';
          this.isCanSave = true;
        }
      },
      deep: true
    },
    enabled: {
      handler(n, o) {
        if (o === false && n === true) {
          // 2023.8.30 需求变更 关闭打开，不根据从接口获取到的设置来显示 根据设备角色使用默认设置
          this.checked = this.watchRole === 2;
          this.reminderChecked = this.watchRole === 2;
          this.setting =
            this.watchRole === 2
              ? { depressive: 1, pressure: 1, fatigue: 1 }
              : { depressive: 1, pressure: 1, fatigue: 1 };
          this.lcdenabled = this.watchRole === 2;
          this.vibrateenabled = this.watchRole === 2;
          this.date.dateList[0] = { startTime: '07:00', endTime: '23:00', model: 0, duration: 6 };
          // 2023.09.13 新需求 对于心理监测参数设置时，启用时，如果用户资料还未设置完成，则自动跳转到用户资料的参数设置
          if (this.isCompleted) {
            // 如果不完整，则自动跳转到用户资料的参数设置
            this.$router.push({
              name: 'personInfos',
              query: {
                from: 'psychologicalSetting',
                // 加多一个参数来识别显示保存文字按钮的文字，因为资料设置页面会有多个页面跳转
                isShowSubmit: true
              }
            });
          }
        } else if (o === true && n === false) {
          // 2023.8.30 新增需求 打开关闭，统一关闭显示，提醒，提醒方式开关
          this.checked = false;
          this.reminderChecked = false;
          this.lcdenabled = false;
          this.vibrateenabled = false;
        }
      },
      deep: true
    },
    //   2023.09.19 设置了“设备显示”关闭，则联动把“提醒设置”设置为不启用，提醒方式的2个选项都不选中
    checked: {
      handler(n, o) {
        if (o === true && n === false) {
          this.reminderChecked = false;
        }
      },
      deep: true
    },
    // 提醒设置，2023.9.1 需求变更 关闭打开，震动亮屏相应关闭打开
    reminderChecked: {
      handler(n, o) {
        if (o === false && n === true) {
          this.vibrateenabled = true;
          this.lcdenabled = true;
          this.setting =
            this.watchRole === 2
              ? { depressive: 1, pressure: 1, fatigue: 1 }
              : { depressive: 1, pressure: 1, fatigue: 1 };
        } else if (o === true && n === false) {
          this.vibrateenabled = false;
          this.lcdenabled = false;
        }
      },
      deep: true
    }
  },
  computed: {
    imei() {
      return this.$store.getters.serialNo;
    },
    watchRole() {
      return this.$store.getters.watchRole;
    }
  },
  created() {
    this.loadParams();
    this.getPersonData();
    this.getPsychAbilityConfig();
  },
  methods: {
    loadParams() {
      let params = this.$route.query;
      if (params) {
        this.showSubmit = params.from !== 'personInfos';
      }
    },
    // 获取个人信息
    getPersonData() {
      APIDevice.getPersonInfo({
        userId: this.$store.getters.userId,
        deviceId: this.$store.getters.deviceId
      }).then(res => {
        let data = res.data;
        this.uid = data.uid;
        if (
          isNotNull(data.gender) &&
          data.height > 0 &&
          data.weight > 0 &&
          isNotNull(data.bornDate) &&
          data.profession > 0 &&
          isNotNull(data.uid)
        ) {
          console.log('资料完整');
          this.isCompleted = true;
        }
      });
    },
    onNavBack() {
      this.$router.push({
        name: this.$route.query.from ? `${this.$route.query.from}` : 'watchSetting'
      });
    },
    getPsychAbilityConfig(action) {
      if (action !== 'delete') {
        ToastService.loading({ message: '数据加载中' });
      }
      //ToastService.loading({message: "数据加载中"});
      APIHealthy.getPsychAbilityConfig(this.imei)
        .then(res => {
          if (action !== 'delete') {
            ToastService.success({ message: '数据加载完成' });
          }
          //ToastService.success({message: "数据加载完成"});
          let data = res.data.data;
          if (data) {
            this.checked = data.device_display === 1;
            this.lcdenabled = data.brightening_screen === 1;
            this.vibrateenabled = data.vibrating_screen === 1;
            this.enabled = data.enabled === 1;
            this.setting = { ...data.reminder_setting.setting };
            this.reminderChecked = data.reminder_setting.enable === 1;
            this.date.dateList = data.time_area.map((item, index) => {
              console.log('item', item);
              return {
                startTime: item.time.slice(0, 5),
                endTime: item.time.slice(6, 11),
                duration: item.duration,
                model: index
              };
            });
          } else {
            // 根据设备角色 部分修改默认参数值
            this.enabled = false;
            this.checked = this.watchRole === 2;
            this.reminderChecked = this.watchRole === 2;
            this.setting =
              this.watchRole === 2
                ? { depressive: 2, pressure: 2, fatigue: 2 }
                : { depressive: 1, pressure: 1, fatigue: 1 };
          }
        })
        .catch(e => {
          DialogService.confirm({
            message: `${e.message}`
          });
        })
        .finally(() => {
          setTimeout(() => {
            ToastService.clear();
          }, 1500);
        });
    },
    // 获取个人信息
    /* getPersonData() {
        APIDevice.getPersonInfo({
            userId: this.$store.getters.userId,
            deviceId: this.$store.getters.deviceId
        }).then(res => {
            let data = res.data;
            this.uid = data.uid;
            if(isNotNull(data.gender) && data.height > 0 && data.weight > 0 && isNotNull(data.bornDate) && data.profession > 0 && isNotNull(data.uid)) {
                console.log("资料完整");
                this.isCompleted = true;
            }
        })
    }, */
    onSubmit(action) {
      const messageText = action === 'delete' ? '删除' : '设置';
      /* if(!this.isCanSave) {
            return DialogService.confirm({
                message: '请输入正确的检测周期'
            })
        } */
      let isNullDuration = this.date.dateList.some(d => {
        return isNull(d.duration);
      });
      if (isNullDuration) {
        return DialogService.confirm({
          message: `时长不能为空`
        });
      }
      let reqDateList = this.date.dateList.map(item => {
        return {
          duration: Number(item.duration),
          time: item.startTime + '-' + item.endTime
        };
      });
      let reqBody = {
        enabled: this.enabled ? 1 : 0,
        imei: this.imei,
        time_area: [
          /* {     //监测时间段集合
                    time: "08:00-12:00", //时间段范围
                    duration: 2 //需要监测时长
                },
                {
                    time: "12:00-18:00",
                    duration: 3
                } */ ...reqDateList
        ],
        reminder_setting: {
          //设备提醒设置
          enable: this.reminderChecked ? 1 : 0, //启用 0禁用 1启用,//是否提醒 0否 1是(默认)
          setting: {
            ...this.setting
            /*  depressive: 1,//抑郁:1=轻度(默认)/2=中度/3=高
                    pressure: 1, //压力:1=轻度(默认)/2=中度/3=高
                    fatigue: 1 //劳累:1=轻度(默认)/2=中度/3=高 */
          }
        },
        device_display: this.checked === true ? 1 : 0, //设备端显示 0否 1是
        brightening_screen: this.lcdenabled ? 1 : 0, //是否亮屏 0否 1是
        vibrating_screen: this.vibrateenabled ? 1 : 0 //是否振动 0否 1是
      };
      ToastService.loading({
        message: `${messageText}中`
      });
      APIHealthy.setPsychAbilityConfig(reqBody)
        .then(async res => {
          if (res.data.stateCode === 1) {
            ToastService.success({ message: `${messageText}成功` });
            if (action === 'delete') {
              setTimeout(() => {
                this.date.dateList = [];
                this.getPsychAbilityConfig('delete');
              }, 1500);
            } else {
              if (this.showSubmit) {
                setTimeout(() => {
                  this.$router.push({
                    name: 'watchSetting'
                  });
                }, 1500);
              } else {
                // 2023.11.17
                // 首次设置心理参数后，调取自动填写问卷答案接口
                /* let autoCommit = await  */ this.psychQuestionAutoCommit();
                /* if (isNotNull(autoCommit)) {
                  setTimeout(() => {
                    const authToken = this.$store.getters.authToken;
                    const baseUrl =
                      process.env.NODE_ENV === 'production'
                        ? 'https://ai.ssjlai.com/h5-frontendweb'
                        : 'https://id.ssjlai.com/h5-frontendweb';
                    window.location.href = `${baseUrl}/#/PsychologicalModeling?uid=${this.uid}&token=${authToken}&fromSsjl=true&fromMenu=health`;
                  }, 1500);
                } */
                /* setTimeout(() => {
                            const authToken = this.$store.getters.authToken;
                            const baseUrl = process.env.NODE_ENV === "production" ? 'https://ai.ssjlai.com/h5-frontendweb' : 'https://id.ssjlai.com/h5-frontendweb';
                            window.location.href = `${baseUrl}/#/PsychologicalModeling?uid=${this.$route.query.uid}&token=${authToken}&fromSsjl=true&fromMenu=health`;
                        },1500) */
              }
            }
          } else {
            ToastService.clear();
            DialogService.confirm({
              title: `${messageText}失败`,
              message: `${res.data.message}`
            });
          }
        })
        .catch(() => {})
        .finally(() => {
          setTimeout(() => {
            ToastService.clear();
          }, 1500);
        });
    },
    // 自动提交问卷调查接口
    psychQuestionAutoCommit() {
      let reqParams = {
        uid: this.uid
      };
      return new Promise((resolve, reject) => {
        APIDevice.psychQuestionAutoCommit(reqParams)
          .then(() => {
            resolve(true);
          })
          .catch(() => {
            reject(true);
          });
      });
    },
    // 转换时间格式
    shiftTime(time, model) {
      if (time) {
        let startTime = time.slice(0, 2) + ':' + time.slice(2, 4);
        let endTime = time.slice(4, 6) + ':' + time.slice(6, 8);
        let timeObj = {
          startTime: startTime,
          endTime: endTime,
          model: model,
          reqTime: time
        };
        this.date.dateList.push(timeObj);
      }
    },
    // 判断时间段数组里面的是否有对象,然后返回对应对象的值
    getReqTime(dateArr, index) {
      if (dateArr.length > 0) {
        if (dateArr[index]) {
          return dateArr[index].reqTime;
        } else {
          return '';
        }
      } else {
        return '';
      }
    },
    onSelect(data) {
      console.log('data', data, this.currentReminder);
      let currentReminder = this.currentReminder;
      this.setting[currentReminder] = data.value;
      this.selectConfirmActive = data.model;
      this.dialog.isDialogshow = false;
      console.log('currentReminder', this.setting[currentReminder], this.setting);
    },
    // 格式化提醒设置文字
    formatReminder(value) {
      let text = '';
      if (value == 1) {
        text = '轻度';
      } else if (value == 2) {
        text = '中度';
      } else if (value == 3) {
        text = '重度';
      } /* else if (value == 0) {
            text = '不告警'
        } */
      return text;
    },
    onClick(name) {
      console.log('name', name);
      this.dialog.isDialogshow = true;
      this.currentReminder = name;
      let seclectIndex = this.dialog.confirmData.findIndex(item => {
        return item.value == this.setting[name];
      });
      this.selectConfirmActive = seclectIndex;
    },
    onClickDate(action, data) {
      this.date.action = action;
      if (action === 'update') {
        this.date.defaultStartTime = data.startTime;
        this.date.defaultEndTime = data.endTime;
        this.date.model = data.model;
        console.log('action', action, data, this.date.dateList);
      }
      this.dateDialog.show = true;
    },
    onChooseDate(value) {
      this.date.currentCount = value;
    },
    formatter(type, val) {
      if (type === 'hour') {
        return val + '时';
      }
      if (type === 'minute') {
        return val + '分';
      }
      return val;
    },
    resetDate() {
      this.dateDialog.show = false;
      this.date.currentCount = 0;
      this.date.defaultStartTime = '08:00';
      this.date.defaultEndTime = '21:00';
      this.date.action = '';
      this.date.model = null;
    },
    onCancel() {
      this.resetDate();
    },
    // 判断新增或更新的 是否有时间交叉 todo
    checkPeriodExist() {
      let canSave = true;
      let list = null;
      if (this.date.action === 'add') {
        // 新增-跟所有判断
        list = this.date.dateList.map(item => {
          item.startTime = item.startTime.replace('-', ':');
          item.endTime = item.endTime.replace('-', ':');
          item.weekdays = '0';
          return item;
        });
      } else {
        // 更新-跟除自己以外判断
        list = this.date.dateList.filter(item => {
          return this.date.model !== item.model;
        });
      }
      console.log('list', list);
      let currentTimeObj = {
        startTime: this.date.defaultStartTime.replace('-', ':'),
        endTime: this.date.defaultEndTime.replace('-', ':'),
        weekdays: '0'
      };
      console.log('新增的时间对象', currentTimeObj);
      list.forEach(t => {
        if (checkPeriodExist(currentTimeObj, t)) {
          canSave = false;
        }
      });
      return canSave;
    },
    onDelete() {
      console.log('当前选中的time', this.date.defaultStartTime + this.date.defaultEndTime);
      console.log('当前第几个时间段', this.date.model);
      if (this.date.dateList.length === 1) {
        return DialogService.confirm({
          message: '心理监测至少要保留1个监测时间段'
        });
      }
      DialogService.confirm({
        message: '是否要删除当前的检测时段',
        showCancelButton: true
      })
        .then(() => {
          this.date.dateList = this.date.dateList.filter(item => {
            return item.model !== this.date.model;
          });
          console.log('dateList', this.date.dateList);
          this.onSubmit('delete');
          //this.resetDate();
          this.dateDialog.show = false;
        })
        .catch(() => {});
    },
    onConfirm(index) {
      console.log('当前的时间列表', this.date.dateList, index);
      console.log('时间段是否有交叉', this.checkPeriodExist());
      let startConflict = this.date.defaultStartTime.replace(':', '');
      let endConflict = this.date.defaultEndTime.replace(':', '');
      if (Number(startConflict) >= Number(endConflict)) {
        return DialogService.confirm({
          title: '设置失败',
          message: '开始时间不能大于结束时间'
        });
      } else if (!this.checkPeriodExist()) {
        return DialogService.confirm({
          title: '设置失败',
          message: '检测时间有交叉，请重新选择'
        });
      }
      if (this.date.action === 'add') {
        let dateObj = {
          startTime: this.date.defaultStartTime,
          endTime: this.date.defaultEndTime,
          time: this.date.defaultStartTime.replace(':', '') + this.date.defaultEndTime.replace(':', '')
        };
        this.date.dateList.push(dateObj);
        this.resetDate();
      } else if (this.date.action === 'update') {
        let selectIndex = this.date.dateList.findIndex(item => {
          console.log('item', item);
          return item.model === this.date.model;
        });
        this.date.dateList[selectIndex].startTime = this.date.defaultStartTime;
        this.date.dateList[selectIndex].endTime = this.date.defaultEndTime;
        this.date.dateList[selectIndex].time =
          this.date.defaultStartTime.replace(':', '') + this.date.defaultEndTime.replace(':', '');
        this.resetDate();
      }
    },
    onInput(index) {
      // eslint-disable-next-line no-self-assign
      this.date.dateList[index].duration = this.date.dateList[index].duration;
      this.durationList[index].duration = this.date.dateList[index].duration;
    },
    onCancelWear() {
      this.isWearDialogshow = false;
      this.interval = this.currentInterval;
      //this.warningDistanceTips = '';
    },
    onConfirmWear() {
      if (this.isCanSave) {
        this.isWearDialogshow = false;
        this.warningDistanceTips = '';
      }
    },
    onPre() {
      this.$router.push({
        name: 'personInfos'
      });
    },
    onNext() {
      let isInputNull = this.date.dateList.some(item => {
        return !isNotNull(item.duration);
      });
      let isMoreThan = this.date.dateList.some(item => {
        return this.checkTimeMorethan(item.startTime, item.endTime, item.duration);
      });
      if (!this.enabled) {
        return DialogService.confirm({
          message: '需要开启心理监测才能进行下一步'
        });
      } else if (isInputNull) {
        return DialogService.confirm({
          message: '监测时长不能为空'
        });
      } else if (isMoreThan) {
        return DialogService.confirm({
          message: '监测时长不能大于设置的监测时间间隔'
        });
      }
      this.onSubmit();
    },
    checkTimeMorethan(sTime, eTime, t) {
      // eslint-disable-next-line no-useless-escape
      let startTime = sTime.replace(/\:/g, '');
      // eslint-disable-next-line no-useless-escape
      let endTime = eTime.replace(/\:/g, '');
      console.log('startTime', startTime, 'startTime', endTime);
      let diff = (endTime - startTime) / 100;
      if (t > diff) {
        return true;
      } else {
        return false;
      }
    }
  }
};
</script>

<style scoped lang="scss">
.psychological-setting-container {
  height: 100vh;
  overflow: hidden;
  .nav-bar {
    height: 100px;
    padding: 0 20px;
  }
  .main {
    height: calc(100vh - 80px);
    background-color: $background;
    padding: 20px 0;
    overflow: scroll;
    padding-bottom: constant(safe-area-inset-bottom); //解决iphone X底部安全区域
    padding-bottom: env(safe-area-inset-bottom); //解决 iphone X底部安全区域
    .list {
      flex: 1;
      max-height: 80%;
      background-color: #fff;
      border-radius: 8px;
      overflow: scroll;
      .item {
        flex: 1;
        padding: 20px 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 2px solid #e5e5e5;
        .left {
          height: 60px;
          @include center();
          span {
            color: #282828;
            font-size: 32px;
          }
          .title {
            font-weight: 450;
            &.gray {
              color: gray;
            }
          }
        }

        .right {
          @include center();
          font-size: 32px;
          img {
            height: 35px;
            width: 35px;
          }
          span {
            font-size: 32px;
            margin-right: 10px;
            color: #aaaaaa;
          }

          &.time {
            width: 480px;
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            flex-direction: column;
            .time-item {
              height: 70px;
              width: 100%;
              display: flex;
              justify-content: flex-end;
              align-items: center;
              margin-bottom: 5px;
              .van-swipe-cell {
                display: flex;
                justify-content: flex-end;
                .van-swipe-cell__right {
                  .van-button--danger {
                    background-color: #ee0a24;
                    @include center();
                    span {
                      color: #fff;
                    }
                  }
                }
              }
              &.date {
                display: flex;
                justify-content: flex-start;
                align-items: center;
              }
            }
          }
        }
        &.left-gray {
          padding-left: 30px;
          color: gray;
        }
        &.time {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
        }
        &.time-list {
          flex: 1;
          display: flex;
          justify-content: flex-start;
          align-items: flex-start;
          flex-direction: column;
          .date-time {
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 20px 0;
            .time-left,
            .time-right {
              display: flex;
              justify-content: flex-start;
              align-items: center;
              span {
                font-size: 32px;
                margin: 0 5px;
                color: #999;
              }
              .left {
                @include center();
                .title {
                  font-weight: 450;
                  &.gray {
                    color: #999;
                  }
                }
                input {
                  height: 40px;
                  width: 60px;
                  font-size: 32px;
                  color: #999;
                  border: 1px solid #999;
                  margin: 0 5px;
                }
              }
              .right {
                .border {
                  font-size: 32px;
                  border: 1px solid #999;
                  padding: 5px;
                  margin: 0 10px;
                  color: #999;
                  span {
                    font-size: 32px;
                    margin: 0 5px;
                  }
                }
                img {
                  height: 35px;
                  width: 35px;
                }
                span {
                  font-size: 32px;
                  margin-right: 10px;
                  color: #999;
                }
              }
            }
          }
        }
        &.alarmType {
          height: auto;
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          .right {
            height: auto;
            margin-left: 40px;
            width: 50%;
            display: flex;
            justify-content: flex-start;
            align-items: center;
            .checkbox-group {
              @include center();
              .van-checkbox {
                padding: 5px;
              }
            }
          }
        }
      }
    }
  }
  .bottom {
    position: absolute;
    bottom: -60px;
    left: 0;
    height: 120px;
    width: 100%;
    @include center();
    .btn {
      position: relative;
      height: 80px;
      width: 323px;
      background-color: $green;
      color: #fff;
      font-size: 36px;
      border-radius: 55px;
      margin: 0 20px;
      @include center();
      &.gray {
        background-color: #d1d2d4;
        margin-right: 45px;
      }
      &.submit {
        width: 80%;
      }
    }
  }
  .date-dialog-container {
    min-height: 550px;
    .date-top {
      width: 100%;
      height: 120px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .top-item {
        height: 100%;
        width: 50%;
        @include center();
        //border-right: .5 solid #e5e5e5;
        background-color: #e5e5e5;
        border-bottom: 2px solid #e5e5e5;
        span {
          font-size: 32px;
          color: #000;
        }
        &.active {
          background-color: #fff;
        }
      }
    }
    .date-bottom {
      height: 380px;
    }
    .button-box {
      position: absolute;
      bottom: 0;
      height: 100px;
      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: 220px;
          p {
            font-size: 32px;
            height: 80px;
            width: 100%;
            color: #000;
            @include center();
          }
          .confirm {
            color: $green;
          }
          .delete {
            color: red;
          }
          .cancel {
            color: #000;
          }
        }
      }
    }
  }
  .wear-dialog-container {
    padding: 30px 40px 0 40px;
    font-size: 32px;
    .selectConfirm {
      padding: 0;
    }
    .con {
      width: 100%;
      overflow: scroll;
      padding-bottom: 20px;
      border-bottom: 1px solid #999;
      .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 {
        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 {
      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>
