<template>
  <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-row>

        <el-col :span="24"
          v-if="type != 'goal' && type != 'languageSet' && type != 'messageSend' && type != 'fallcheckSensitivity' && type != 'measureIntervalHr' && type != 'measureIntervalOther' && type != 'phonebookSync'">
          <el-form-item label="开关设置" prop="flag">
            <el-switch v-model="form.flag" active-text="开启" inactive-text="关闭">
            </el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="type == 'medication' && form.flag">
          <el-form-item label="开始提醒时间" prop="medicationStart" label-width="110px">
            <el-time-picker
              value-format="HH:mm:ss"
              v-model="form.medicationStart"
              placeholder="请选择开始时间"
              :picker-options="{
                selectableRange: '00:00:00 - 23:59:59'
              }"
            ></el-time-picker>
          </el-form-item>
          <el-form-item label="结束提醒时间" prop="medicationEnd" label-width="110px">
            <el-time-picker
              value-format="HH:mm:ss"
              v-model="form.medicationEnd"
              placeholder="请选择结束时间"
              :picker-options="{
                selectableRange: '00:00:00 - 23:59:59'
              }"
            ></el-time-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="type == 'study' && form.flag">
          <el-form-item label="开始提醒时间" prop="studyStart" label-width="110px">
            <el-time-picker
              value-format="HH:mm:ss"
              v-model="form.studyStart"
              placeholder="请选择开始时间"
              :picker-options="{
                selectableRange: '00:00:00 - 23:59:59'
              }"
            ></el-time-picker>
          </el-form-item>
          <el-form-item label="结束提醒时间" prop="studyEnd" label-width="110px">
            <el-time-picker
              value-format="HH:mm:ss"
              v-model="form.studyEnd"
              placeholder="请选择结束时间"
              :picker-options="{
                selectableRange: '00:00:00 - 23:59:59'
              }"
            ></el-time-picker>
          </el-form-item>
        </el-col>

        <el-col :span="24" v-if="type == 'autolocate' || type == 'datafreq'">
          <el-form-item label="设备省电设置" prop="mode" label-width="105px">
            <el-radio-group v-model="form.mode">
              <el-radio :label="1">low耗电</el-radio>
              <el-radio :label="2">mid耗电</el-radio>
              <el-radio :label="3">high耗电</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="type == 'autolocate' || type == 'datafreq'">
          <el-form-item label="数据上传间隔(分钟)" prop="time" label-width="150px">
            <el-select v-model="form.time" placeholder="请选择数据上传间隔">
              <el-option v-for="item in timeOptions" :key="item" :label="item" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 翻腕亮屏的开始时间,结束时间(开启时需要，不开启不需要) -->
        <el-col :span="24" v-if="type == 'lcdgesture' && form.flag">
          <el-form-item label="开始时间" prop="start">
            <el-select v-model="form.start" placeholder="请选择开始时间">
              <el-option v-for="i in startOptions" :key="i" :label="i" :value="i">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="type == 'lcdgesture' && form.flag">
          <el-form-item label="结束时间" prop="end">
            <el-select v-model="form.end" placeholder="请选择结束时间">
              <el-option v-for="i in endOptions" :key="i" :label="i" :value="i">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 心率报警设置 -->
        <template v-if="type == 'hralarm' && form.flag">
          <el-col :span="24">
            <el-form-item label="正常心率最高值" prop="high" label-width="130px">
              <!-- <el-input v-model="form.high" maxlength="5" placeholder="请输入正常心率最高值" /> -->
              <el-select v-model="form.high" placeholder="请选择正常心率最高值">
                <el-option
                  v-for="item in hrRangeHigh"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="正常心率最低值" prop="low" label-width="130px">
              <!-- <el-input v-model="form.low" maxlength="5" placeholder="请输入正常心率最低值" /> -->
              <el-select v-model="form.low" placeholder="请选择正常心率最低值">
                <el-option
                  v-for="item in hrRangeLow"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label-width="0" prop="timeout" class="timeout">
              <div class="timeout-box">
                <span class="timeout-txt">产生</span>
                <el-input class="timeout-input" v-model="form.timeout" maxlength="4" placeholder="请输入次数" />
                <span class="timeout-txt">次异常心率，开始报警</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="报警间隔(分钟)" prop="interval" label-width="130px">
              <el-input v-model="form.interval" maxlength="4" placeholder="请输入报警间隔" />
            </el-form-item>
          </el-col>
        </template>
        <!-- 血氧报警设置 -->
        <template v-if="type == 'spo2alarm' && form.flag">
          <el-col :span="24">
            <el-form-item label="血氧报警值(%)" prop="spo2low" label-width="120px">
              <!-- <el-input v-model="form.spo2low" maxlength="5" placeholder="请输入血氧报警值" /> -->
              <el-select v-model="form.spo2low" placeholder="请选择血氧报警值">
                <el-option
                  v-for="item in boRange"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </template>
        <!-- 血压报警设置 -->
        <template v-if="type == 'bpalarm' && form.flag">
          <el-col :span="24">
            <el-form-item label="高压最高值(mmhg)" prop="sbp_high" label-width="155px">
              <el-input v-model="form.sbp_high" maxlength="5" placeholder="请输入高压最高值" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="高压最低值(mmhg)" prop="sbp_below" label-width="155px">
              <el-input v-model="form.sbp_below" maxlength="5" placeholder="请输入高压最低值" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="低压最高值(mmhg)" prop="dbp_high" label-width="155px">
              <el-input v-model="form.dbp_high" maxlength="5" placeholder="请输入低压最高值" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="低压最低值(mmhg)" prop="dbp_below" label-width="155px">
              <el-input v-model="form.dbp_below" maxlength="5" placeholder="请输入低压最低值" />
            </el-form-item>
          </el-col>
        </template>
        <!-- 温度报警设置 -->
        <template v-if="type == 'temperatureAlarm' && form.flag">
          <el-col :span="24">
            <el-form-item label="最高温度报警值(℃)" prop="temperatureHigh" label-width="155px">
              <el-input v-model="form.temperatureHigh" maxlength="6" placeholder="请输入最高温度报警值" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="最低温度报警值(℃)" prop="temperatureLow" label-width="155px">
              <el-input v-model="form.temperatureLow" maxlength="6" placeholder="请输入最低温度报警值" />
            </el-form-item>
          </el-col>
        </template>
        <!-- 自动房颤设置 -->
        <template v-if="type == 'autoaf' && form.flag">
          <el-col :span="24">
            <el-form-item label="测量持续时间(秒)" prop="autoafInterval" label-width="140px">
              <el-input v-model="form.autoafInterval" maxlength="3" placeholder="请输入测量持续时间" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="测量频率" prop="rriSingleTime" label-width="140px">
              <el-select v-model="form.rriSingleTime" clearable placeholder="请选择测量频率">
                <el-option label="按照心率间隔，每次测量完心率后测量一次" :value="true" />
                <el-option label="一直测量" :value="false" />
              </el-select>
            </el-form-item>
          </el-col>
        </template>
        <!-- 目标设置 -->
        <template v-if="type == 'goal'">
          <el-col :span="24">
            <el-form-item label="目标步数" prop="step" label-width="135px">
              <el-input v-model="form.step" maxlength="7" placeholder="请输入目标步数" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="目标距离(米)" prop="distance" label-width="135px">
              <el-input v-model="form.distance" maxlength="7" placeholder="请输入目标距离" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="目标卡路里(千卡)" prop="calorie" label-width="135px">
              <el-input v-model="form.calorie" maxlength="7" placeholder="请输入目标卡路里" />
            </el-form-item>
          </el-col>
        </template>
        <!-- 语言设置 -->
        <template v-if="type == 'languageSet'">
          <el-col :span="24">
            <el-form-item label="选择语言" prop="language">
              <el-select v-model="form.language" clearable placeholder="请选择语言">
                <el-option label="English" :value="0" />
                <el-option label="Chinese" :value="1" />
                <el-option label="Italian" :value="2" />
                <el-option label="Japanese" :value="3" />
                <el-option label="France" :value="4" />
                <el-option label="German" :value="5" />
                <el-option label="Portuguese" :value="6" />
                <el-option label="Spanish" :value="7" />
                <el-option label="Russian" :value="8" />
                <el-option label="Korean" :value="9" />
                <el-option label="Arabic" :value="10" />
                <el-option label="Vietnam" :value="11" />
                <el-option label="Polish" :value="12" />
                <el-option label="Romanian" :value="13" />
                <el-option label="Swedish" :value="14" />
                <el-option label="Thai" :value="15" />
                <el-option label="Turkish" :value="16" />
                <el-option label="Denish" :value="17" />
                <el-option label="Ukrainian" :value="18" />
                <el-option label="Norwegian" :value="19" />
                <el-option label="Dutch" :value="20" />
                <el-option label="Czech" :value="21" />
                <el-option label="Chinese_Tc" :value="22" />
                <el-option label="Indonesian" :value="23" />
              </el-select>
            </el-form-item>
          </el-col>
        </template>
        <!-- 发送设备消息 -->
        <template v-if="type == 'messageSend'">
          <el-col :span="24">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" maxlength="15" placeholder="请输入标题" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input type="textarea" autosize v-model="form.description" maxlength="240" placeholder="请输入描述" />
            </el-form-item>
          </el-col>
        </template>
        <!--  设置跌倒检测灵敏度 -->
        <template v-if="type == 'fallcheckSensitivity'">
          <el-col :span="24">
            <el-form-item label="跌倒检测灵敏度" prop="fallThreshold" label-width="130px">
              <el-input v-model="form.fallThreshold" maxlength="8" placeholder="请输入跌倒检测灵敏度" />
            </el-form-item>
          </el-col>
        </template>
        <!-- 心率数据测量间隔设置 -->
        <template v-if="type == 'measureIntervalHr'">
          <el-col :span="24">
            <el-form-item label="测量间隔(分钟)" prop="measureIntervalHr" label-width="130px">
              <el-input v-model="form.measureIntervalHr" maxlength="4" placeholder="请输入测量间隔" />
            </el-form-item>
          </el-col>
        </template>
        <!-- 其他非心率数据测量间隔设置 -->
        <template v-if="type == 'measureIntervalOther'">
          <el-col :span="24">
            <el-form-item label="测量间隔(分钟)" prop="measureIntervalOther" label-width="130px">
              <el-input v-model="form.measureIntervalOther" maxlength="4" placeholder="请输入测量间隔" />
            </el-form-item>
          </el-col>
        </template>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm" :loading="btnLoading">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { isInteger } from "@/utils/validate.js";
import {
  fallcheck,
  autolocate,
  datafreq,
  medication,
  study,
  lcdgesture,
  hralarm,
  spo2alarm,
  bpalarm,
  temperatureAlarm,
  autoaf,
  goal,
  languageSet,
  messageSend,
  fallcheckSensitivity,
  measureIntervalHr,
  measureIntervalOther,
  getSet
} from "@/api/watch/deviceInfoSet.js";

export default {
  data() {
    const checkIsInteger = (rule, value, callback) => {
      if (!isInteger(value)) {
        callback(new Error("请输入正确的数字"));
      } else {
        callback();
      }
    };
    const checkStudyTimes = (rule, value, callback, type) => {
      if (!value) {
        return callback(new Error('时间不能为空'));
      }

      const start = this.form.studyStart;
      const end = this.form.studyEnd;

      if (type === 'start') {
        if (end && start && new Date(start) >= new Date(end)) {
          callback(new Error('开始时间必须小于结束时间'));
        } else {
          callback();
        }
      } else if (type === 'end') {
        if (start && new Date(start) > new Date(end)) {
          callback(new Error('结束时间必须大于开始时间'));
        } else {
          callback();
        }
      }
    };
    const checkMedicationTimes = (rule, value, callback, type) => {
      if (!value) {
        return callback(new Error('时间不能为空'));
      }

      const start = this.form.medicationStart;
      const end = this.form.medicationEnd;

      if (type === 'start') {
        if (end && start && new Date(start) >= new Date(end)) {
          callback(new Error('开始时间必须小于结束时间'));
        } else {
          callback();
        }
      } else if (type === 'end') {
        if (start && new Date(start) > new Date(end)) {
          callback(new Error('结束时间必须大于开始时间'));
        } else {
          callback();
        }
      }
    };
    //  检查翻腕亮屏开始时间
    const checkStart = (rule, value, callback) => {
      if (value && this.form.end) {
        if(Number(value) >= Number(this.form.end)) {
          callback(new Error("开始时间不能大于等于结束时间"));
        } else {
          this.$refs["form"].validateField("end");
          callback();
        }
      }else {
        callback();
      }
    };
    //  检查翻腕亮屏结束时间
    const checkEnd = (rule, value, callback) => {
      if (value && this.form.start) {
        if(Number(value) <= Number(this.form.start)) {
          callback(new Error("结束时间不能小于等于开始时间"));
        } else {
          this.$refs["form"].validateField("start");
          callback();
        }
      }else {
        callback();
      }
    };
    //   检查正常心率最高值
    const checkHigh = (rule, value, callback) => {
      if (!isInteger(value)) {
        callback(new Error("请输入正确的数字"));
      } else if (isInteger(this.form.low)) {
        if(Number(value) < Number(this.form.low)) {
          callback(new Error("正常心率最高值不能小于正常心率最低值"));
        } else {
          this.$refs["form"].validateField("low");
          callback();
        }
      } else {
        callback();
      }
    };
    //   检查正常心率最低值
    const checkLow = (rule, value, callback) => {
      if (!isInteger(value)) {
        callback(new Error("请输入正确的数字"));
      } else if (isInteger(this.form.high)) {
        if(Number(value) > Number(this.form.high)) {
          callback(new Error("正常心率最低值不能大于正常心率最高值"));
        } else {
          this.$refs["form"].validateField("high");
          callback();
        }
      } else {
        callback();
      }
    };
    //   检查高压最高值
    const checkSbpHigh = (rule, value, callback) => {
      if (!isInteger(value)) {
        callback(new Error("请输入正确的数字"));
      } else if (isInteger(this.form.sbp_below)) {
        if(Number(value) < Number(this.form.sbp_below)) {
          callback(new Error("高压最高值不能小于高压最低值"));
        } else {
          this.$refs["form"].validateField("sbp_below");
          callback();
        }
      } else {
        callback();
      }
    };
    //   检查高压最低值
    const checkSbpBelow = (rule, value, callback) => {
      if (!isInteger(value)) {
        callback(new Error("请输入正确的数字"));
      } else if (isInteger(this.form.sbp_high)) {
        if(Number(value) > Number(this.form.sbp_high)) {
          callback(new Error("高压最低值不能大于高压最高值"));
        } else {
          this.$refs["form"].validateField("sbp_high");
          callback();
        }
      } else {
        callback();
      }
    };
    //   检查低压最高值
    const checkDbpHigh = (rule, value, callback) => {
      if (!isInteger(value)) {
        callback(new Error("请输入正确的数字"));
      } else if (isInteger(this.form.dbp_below)) {
        if(Number(value) < Number(this.form.dbp_below)) {
          callback(new Error("低压最高值不能小于低压最低值"));
        } else {
          this.$refs["form"].validateField("dbp_below");
          callback();
        }
      } else {
        callback();
      }
    };
    //   检查低压最低值
    const checkDbpBelow = (rule, value, callback) => {
      if (!isInteger(value)) {
        callback(new Error("请输入正确的数字"));
      } else if (isInteger(this.form.dbp_high)) {
        if(Number(value) > Number(this.form.dbp_high)) {
          callback(new Error("低压最低值不能大于低压最高值"));
        } else {
          this.$refs["form"].validateField("dbp_high");
          callback();
        }
      } else {
        callback();
      }
    };
    // 检查最高温度报警值
    const checkTemperatureHigh = (rule, value, callback) => {
      // 判断字符串为负数/正数/小数（小数保留一位）
      const reg = /^-?\d+(.\d{1})?$/
      const flag = (val) => reg.test(val) && -100 < Number(val) && Number(val) < 100

      if (!flag(value)) {
        callback(new Error("请输入正确的数字"));
      } else if (flag(this.form.temperatureLow)) {
        if(Number(value) <= Number(this.form.temperatureLow)) {
          callback(new Error("最高温度报警值不能小于等于最低温度报警值"));
        } else {
          this.$refs["form"].validateField("temperatureLow");
          callback();
        }
      } else {
        callback();
      }
    };
    // 检查最低温度报警值
    const checkTemperatureLow = (rule, value, callback) => {
      const reg = /^-?\d+(.\d{1})?$/
      const flag = (val) => reg.test(val) && -100 < Number(val) && Number(val) < 100

      if (!flag(value)) {
        callback(new Error("请输入正确的数字"));
      } else if (flag(this.form.temperatureHigh)) {
        if(Number(value) >= Number(this.form.temperatureHigh)) {
          callback(new Error("最低温度报警值不能大于等于最高温度报警值"));
        } else {
          this.$refs["form"].validateField("temperatureHigh");
          callback();
        }
      } else {
        callback();
      }
    };
    // 检查自动房颤测量持续时间
    const checkInterval = (rule, value, callback) => {
      if (!isInteger(value)) {
        callback(new Error("请输入正确的数字"));
      } else if (Number(value) < 30 || Number(value) > 120) {
        // 最小取值30，最大取值120
        callback(new Error("最小值30,最大值120"));
      } else {
        callback();
      }
    };
    // 检查其他非心率数据测量间隔设置
    const checkMeasureIntervalOther = (rule, value, callback) => {
      if (!isInteger(value)) {
        callback(new Error("请输入正确的数字"));
      } else if (Number(value) < 5) {
        // 最小5分钟
        callback(new Error("最小5分钟"));
      } else {
        callback();
      }
    };

    const hrRangeLow = Array.from({length: 151}, (_, i) => i + 40)
    const hrRangeHigh = Array.from({length: 151}, (_, i) => i + 50)

    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      hrRangeLow,
      hrRangeHigh,
      boRange: [80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93],
      btnLoading: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      //
      param:{
        flag:null,
        start:null,
        end:null
      },
      // 表单校验
      rules: {
        time: [
          { required: true, message: "数据上传间隔不能为空", trigger: ["blur", "change"] },
        ],
        start: [
          { required: true, message: "开始时间不能为空", trigger: ["blur", "change"] },
          { validator: checkStart, trigger: ["blur", "change"] }
        ],
        end: [
          { required: true, message: "结束时间不能为空", trigger: ["blur", "change"] },
          { validator: checkEnd, trigger: ["blur", "change"] }
        ],
        medicationStart: [
          { required: true, message: "开始时间不能为空", trigger: "blur" },
          { validator: (rule, value, callback) => checkMedicationTimes(rule, value, callback, 'start'), trigger: "blur" }
        ],
        medicationEnd: [
          { required: true, message: "结束时间不能为空", trigger: "blur" },
          { validator: (rule, value, callback) => checkMedicationTimes(rule, value, callback, 'end'), trigger: "blur" }
        ],
        studyStart: [
          { required: true, message: "看课提醒开始时间不能为空", trigger: "blur" },
          { validator: (rule, value, callback) => checkStudyTimes(rule, value, callback, 'start'), trigger: "blur" }
        ],
        studyEnd: [
          { required: true, message: "看课提醒结束时间不能为空", trigger: "blur" },
          { validator: (rule, value, callback) => checkStudyTimes(rule, value, callback, 'end'), trigger: "blur" }
        ],
        high: [
          { required: true, message: "正常心率最高值不能为空", trigger: ["blur", "change"] },
          { validator: checkHigh, trigger: ["blur", "change"] }
        ],
        low: [
          { required: true, message: "正常心率最低值不能为空", trigger: ["blur", "change"] },
          { validator: checkLow, trigger: ["blur", "change"] }
        ],
        timeout: [
          { required: true, message: "异常心率次数不能为空", trigger: ["blur", "change"] },
          { validator: checkIsInteger, trigger: ["blur", "change"] }
        ],
        interval: [
          { required: true, message: "报警间隔不能为空", trigger: ["blur", "change"] },
          { validator: checkIsInteger, trigger: ["blur", "change"] }
        ],
        spo2low: [
          { required: true, message: "血氧报警值不能为空", trigger: ["blur", "change"] },
          { validator: checkIsInteger, trigger: ["blur", "change"] }
        ],
        sbp_high: [
          { required: true, message: "高压最高值不能为空", trigger: ["blur", "change"] },
          { validator: checkSbpHigh, trigger: ["blur", "change"] }
        ],
        sbp_below: [
          { required: true, message: "高压最低值不能为空", trigger: ["blur", "change"] },
          { validator: checkSbpBelow, trigger: ["blur", "change"] }
        ],
        dbp_high: [
          { required: true, message: "低压最高值不能为空", trigger: ["blur", "change"] },
          { validator: checkDbpHigh, trigger: ["blur", "change"] }
        ],
        dbp_below: [
          { required: true, message: "低压最低值不能为空", trigger: ["blur", "change"] },
          { validator: checkDbpBelow, trigger: ["blur", "change"] }
        ],
        temperatureHigh: [
          { required: true, message: "最高温度报警值不能为空", trigger: ["blur", "change"] },
          { validator: checkTemperatureHigh, trigger: ["blur", "change"] }
        ],
        temperatureLow: [
          { required: true, message: "最低温度报警值不能为空", trigger: ["blur", "change"] },
          { validator: checkTemperatureLow, trigger: ["blur", "change"] }
        ],
        autoafInterval: [
          { required: true, message: "测量持续时间不能为空", trigger: ["blur", "change"] },
          { validator: checkInterval, trigger: ["blur", "change"] }
        ],
        step: [
          { required: true, message: "目标步数不能为空", trigger: ["blur", "change"] },
          { validator: checkIsInteger, trigger: ["blur", "change"] }
        ],
        distance: [
          { required: true, message: "目标距离不能为空", trigger: ["blur", "change"] },
          { validator: checkIsInteger, trigger: ["blur", "change"] }
        ],
        calorie: [
          { required: true, message: "目标卡路里不能为空", trigger: ["blur", "change"] },
          { validator: checkIsInteger, trigger: ["blur", "change"] }
        ],
        language: [
          { required: true, message: "请选择语言", trigger: "change" }
        ],
        title: [
          { required: true, message: "标题不能为空", trigger: ["blur", "change"] }
        ],
        description: [
          { required: true, message: "描述不能为空", trigger: ["blur", "change"] }
        ],
        fallThreshold: [
          { required: true, message: "跌倒检测灵敏度不能为空", trigger: ["blur", "change"] },
          { validator: checkIsInteger, trigger: ["blur", "change"] }
        ],
        measureIntervalHr: [
          { required: true, message: "测量间隔不能为空", trigger: ["blur", "change"] },
          { validator: checkIsInteger, trigger: ["blur", "change"] }
        ],
        measureIntervalOther: [
          { required: true, message: "测量间隔不能为空", trigger: ["blur", "change"] },
          { validator: checkMeasureIntervalOther, trigger: ["blur", "change"] }
        ],
      },
      // 弹窗事件类型
      type: "",
      // 数据上传时间间隔（分钟）
      timeOptions: [10, 20, 30, 40, 50, 60, 120],
      // 翻腕亮屏开始时间
      startOptions: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23],
      // 翻腕亮屏结束时间
      endOptions: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24],
    };
  },
  methods: {
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deviceid: undefined, // 设备id
        deviceNumber: undefined, // 设备编号
        flag: false,
        mode: 2, // 设备自动定位开关(可选,设备省电设置)
        time: 10, // 设备数据上传间隔设置
        start: 0, // 翻腕亮屏的开始时间
        end: 24, // 翻腕亮屏的结束时间
        high: undefined, // 正常心率最高值
        low: undefined, // 正常心率最低值
        timeout: undefined, //  产生几次异常心率，开始报警
        interval: undefined, // 报警间隔，单位分钟
        spo2low: undefined, // 血氧值报警
        sbp_high: undefined, // 血压 高压最高值
        sbp_below: undefined, // 血压 高压最低值
        dbp_high: undefined, // 血压 低压最高值
        dbp_below: undefined, // 血压 低压最低值
        temperatureHigh: undefined, // 温度报警设置最高值
        temperatureLow: undefined,  // 温度报警设置最低值
        autoafInterval: undefined, // 自动房颤设置 测量持续时间(秒)
        rriSingleTime: undefined, // 自动房颤设置(可选值。设置为true，按照心率间隔，每次测量完心率后测量一次。设置为false，一直测量)
        step: undefined,  // 目标步数
        distance: undefined,  // 目标距离,单位米
        calorie: undefined,  // 目标卡路里,单位千卡
        language: undefined,  // 语言设置
        title: undefined, // 发送设备消息 标题
        description: undefined, // 发送设备消息 描述
        fallThreshold: 14000, // 跌倒检测的灵敏度，默认14000
        measureIntervalHr: undefined, // 心率数据测量间隔设置 分钟
        medicationStart: undefined, // 用药提醒的开始时间
        medicationEnd: undefined, // 用药提醒的结束时间
        studyStart: undefined, // 看课提醒的开始时间
        studyEnd: undefined, // 看课提醒的结束时间
      };
      this.resetForm("form");
      this.btnLoading = false
    },
    handleSet(deviceid, deviceNumber, item) {
      this.reset();
      this.form.deviceid = deviceid
      this.form.deviceNumber = deviceNumber;
      this.open = true;
      this.title = item.label;
      this.type = item.eventName
    },
    handleTimeSet(item) {
      //查询对应设置
      this.reset();
      this.type = item.eventName;
      this.open = true;
      getSet({type:this.type}).then(response => {
        this.param = response.data;
        this.form.flag = this.param.flag;
        this.title = item.label;
        if(this.type == 'medication'){
          this.form.medicationStart = this.param.start;
          this.form.medicationEnd = this.param.end;
        } else if(this.type == 'study'){
          this.form.studyStart = this.param.start;
          this.form.studyEnd = this.param.end;
        }
      });

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if(this.type=='medication' || this.type=='study'){
          this.confirmFun()
        } else if (valid) {
          if (this.form.deviceNumber != undefined) {
            this.confirmFun()
          } else {
            this.msgError("设备id错误~");
          }
        }
      });
    },
    confirmFun() {
      const flagTxt = this.form.flag ? '开启' : '关闭'
      const typeTxt = {
        fallcheck: `是否确认${flagTxt}设备信息编号为${this.form.deviceNumber}的跌倒检测？`,
        autolocate: `是否确认${flagTxt}设备信息编号为${this.form.deviceNumber}的自动定位？`,
      }
      if(this.type=='medication' || this.type=='study'){
        this.$confirm(`是否确认对所有设备进行以上操作？`, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.handleFun()
        }).then(() => {
          this.open = false
          // this.$emit("refreshList")
        }).catch(() => { });

      } else {
        this.$confirm(typeTxt[this.type] || `是否确认对设备id为${this.form.deviceNumber}进行以上操作？`, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.handleFun()
        }).then(() => {
          this.open = false
          // this.$emit("refreshList")
        }).catch(() => { });
        }

    },
    handleFun() {
      const options = {
        // 设备跌倒检测开关
        fallcheck: () => fallcheck({
          deviceNumber: this.form.deviceNumber,
          flag: this.form.flag
        }),
        // 设备自动定位开关
        autolocate: () => autolocate({
          deviceNumber: this.form.deviceNumber,
          flag: this.form.flag,
          time: this.form.time,
          mode: this.form.mode
        }),
        // 设备数据上传间隔设置
        datafreq: () => datafreq({
          deviceNumber: this.form.deviceNumber,
          flag: this.form.flag,
          time: this.form.time,
          mode: this.form.mode
        }),
        // 用药提醒设置
        medication: () => medication({
          flag: this.form.flag,
          start: this.form.flag ? this.form.medicationStart : undefined,
          end: this.form.flag ? this.form.medicationEnd : undefined
        }),
        // 看课提醒设置
        study: () => study({
          flag: this.form.flag,
          start: this.form.flag ? this.form.studyStart : undefined,
          end: this.form.flag ? this.form.studyEnd : undefined
        }),
        // 翻腕亮屏设置
        lcdgesture: () => lcdgesture({
          deviceNumber: this.form.deviceNumber,
          flag: this.form.flag,
          start: this.form.flag ? this.form.start : undefined,
          end: this.form.flag ? this.form.end : undefined
        }),
        // 心率报警设置
        hralarm: () => hralarm({
          deviceid: this.form.deviceNumber,
          open: this.form.flag,
          high: this.form.high,
          low: this.form.low,
          timeout: this.form.timeout,
          interval: this.form.interval,
        }),
        // 血氧报警设置
        spo2alarm: () => spo2alarm({
          deviceid: this.form.deviceNumber,
          open: this.form.flag,
          low: this.form.spo2low,
        }),
        // 血压报警设置
        bpalarm: () => bpalarm({
          deviceid: this.form.deviceNumber,
          open: this.form.flag,
          sbp_high: this.form.sbp_high,
          sbp_below: this.form.sbp_below,
          dbp_high: this.form.dbp_high,
          dbp_below: this.form.dbp_below,
        }),
        // 温度报警设置
        temperatureAlarm: () => temperatureAlarm({
          deviceNumber: this.form.deviceNumber,
          flag: this.form.flag,

          high: this.form.flag ? Number(this.form.temperatureHigh) * 10 : undefined,
          low: this.form.flag ? Number(this.form.temperatureLow) * 10 : undefined,
        }),
        // 自动房颤设置
        autoaf: () => autoaf({
          deviceNumber: this.form.deviceNumber,
          flag: this.form.flag,
          interval: this.form.autoafInterval,
          rriSingleTime: this.form.rriSingleTime,
        }),
        // 目标设置
        goal: () => goal({
          deviceid: this.form.deviceNumber,
          step: this.form.step,
          distance: this.form.distance,
          calorie: this.form.calorie,
        }),
        // 设置语言
        languageSet: () => languageSet({
          deviceid: this.form.deviceNumber,
          languageid: this.form.language,
        }),
        // 发送设备消息
        messageSend: () => messageSend({
          deviceNumber: this.form.deviceNumber,
          title: this.form.title,
          description: this.form.description,
        }),
        // 设置跌倒检测灵敏度
        fallcheckSensitivity: () => fallcheckSensitivity({
          deviceNumber: this.form.deviceNumber,
          fallThreshold: this.form.fallThreshold
        }),
        // 心率数据测量间隔设置
        measureIntervalHr: () => measureIntervalHr({
          deviceNumber: this.form.deviceNumber,
          interval: this.form.measureIntervalHr
        }),
        // 其他非心率数据测量间隔设置
        measureIntervalOther: () => measureIntervalOther({
          deviceNumber: this.form.deviceNumber,
          interval: this.form.measureIntervalOther
        }),
      };

      const option = options[this.type];
      if (option) {
        this.btnLoading = true
        option().then(res => {
          this.btnLoading = false
          if (res.code == 200) {
            this.msgSuccess("操作成功");
          } else {
            this.msgError(res.msg);
          }
        }).catch(err => {
          this.btnLoading = false
        })
      }
    }

  },
};
</script>

<style lang="scss" scoped>
.timeout {
  ::v-deep {
    .el-form-item__error {
      left: 100px;
    }
  }

  &-box {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #606266;
    font-weight: 700;

    &::before {
      content: '*';
      color: #ff4949;
      margin-right: -8px;
    }
  }

  &-txt {
    flex-shrink: 0;
    margin: 0 12px;
  }

  &-input {
    flex: 1;
  }
}
</style>
