<template>
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="1000px"
    append-to-body
    :close-on-click-modal="false"
  >
    <el-button
      type="primary"
      plain
      icon="el-icon-plus"
      size="mini"
      style="margin-bottom: 20px"
      @click="addSedentary"
      >新增久坐</el-button
    >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      size="small"
      :hide-required-asterisk="true"
      :inline-message="true"
      label-width="0px"
    >
      <el-table :data="form.sedentaries">
        <el-table-column type="index" align="center" width="50" />
        <el-table-column label="久坐检查时间段" align="center" width="130px">
            <template slot-scope="scope">
                <div class="inputbox">
                    <div>
                        <div class="label">开始小时:</div>
                        <el-form-item :prop="'sedentaries.' + scope.$index + '.start_hour'" :rules="rules.start_hour" class="input">
                            <el-select v-model="scope.row.start_hour" placeholder="" @change="changeStarthour(scope.$index,'sedentaries.' + scope.$index + '.end_hour')">
                                <el-option :label="item" :value="item" v-for="(item,i) in hourOptions" :key="i" />
                            </el-select>
                        </el-form-item>
                    </div>
                    <div>
                        <div class="label">结束小时:</div>
                        <el-form-item :prop="'sedentaries.' + scope.$index + '.end_hour'" :rules="rules.end_hour" class="input">
                            <el-select v-model="scope.row.end_hour" placeholder="" @change="changeEndhour(scope.$index,'sedentaries.' + scope.$index + '.start_hour')">
                                <el-option :label="item" :value="item" v-for="(item,i) in hourOptions" :key="i" />
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
            </template>
        </el-table-column>
        <el-table-column label="重复频率" align="center" width="160px">
          <template slot-scope="scope">
            <el-form-item :prop="'sedentaries.' + scope.$index + '.repeat'">
              <el-radio-group v-model="scope.row.repeat">
                <el-radio :label="true">重复</el-radio>
                <el-radio :label="false">一次性</el-radio>
              </el-radio-group>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="提醒频率" align="center" min-width="130px">
          <template slot-scope="scope">
            <el-form-item
              :prop="'sedentaries.' + scope.$index + '.week'"
              :rules="rules.week"
            >
              <el-select
                v-model="scope.row.week"
                multiple
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="星期一" value="monday" />
                <el-option label="星期二" value="tuesday" />
                <el-option label="星期三" value="wednesday" />
                <el-option label="星期四" value="thursday" />
                <el-option label="星期五" value="friday" />
                <el-option label="星期六" value="saturday" />
                <el-option label="星期日" value="sunday" />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="累计久坐分钟数提醒" align="center">
            <template slot-scope="scope">
                <el-form-item :prop="'sedentaries.' + scope.$index + '.duration'" :rules="rules.duration">
                    <el-input v-model="scope.row.duration" maxlength="4" placeholder="" />
                </el-form-item>
            </template>
        </el-table-column>
        <el-table-column label="久坐条件步数" align="center">
            <template slot-scope="scope">
                <el-form-item :prop="'sedentaries.' + scope.$index + '.threshold'" :rules="rules.threshold">
                    <el-input v-model="scope.row.threshold" maxlength="3" placeholder="40" />
                </el-form-item>
            </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              v-if="form.sedentaries.length > 1"
              @click="handleDelete(scope.row, scope.$index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div class="tips">
        <div> 提示：</div>
        <div>累计久坐分钟数提醒：单位为5分钟，即设置1，等于5分钟。</div>
        <div>久坐条件步数：一分钟内步数少于多少，判断这一分钟为久坐，计数+1，单位步，默认40。</div>
    </div>
    <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 { setSedentary } from "@/api/watch/deviceInfoSet.js";

export default {
  data() {
    const checkStarthour = (rule, value, callback) => {
      const index = rule.field.split('.')[1]
      if (this.form.sedentaries[index].end_hour && Number(value) >= Number(this.form.sedentaries[index].end_hour)) {
        callback(new Error("开始小时不能大于等于结束小时"));
      } else {
        callback();
      }
    }

    const checkEndhour = (rule, value, callback) => {
      const index = rule.field.split('.')[1]
      if (this.form.sedentaries[index].start_hour && Number(value) <= Number(this.form.sedentaries[index].start_hour)) {
        callback(new Error("结束小时不能小于等于开始小时"));
      } else {
        callback();
      }
    }

    return {
      btnLoading: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
       start_hour: [
            { required: true, message: "开始小时不能为空", trigger: ["blur", "change"] },
            { validator: checkStarthour, trigger: ["blur", "change"] }
        ],
        end_hour: [
            { required: true, message: "结束小时不能为空", trigger: ["blur", "change"] },
            { validator: checkEndhour, trigger: ["blur", "change"] }
        ],
        duration: [
            { required: true, message: "累计久坐分钟数提醒不能为空", trigger: ["blur", "change"] }
        ],
        threshold: [
            { required: true, message: "久坐条件不能为空", trigger: ["blur", "change"] }
        ],
      },
      // 弹窗事件类型
      type: "",
      hourOptions: ["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23"],
    };
  },
  methods: {
    changeStarthour(index,prop) {
        if(this.form.sedentaries[index].end_hour) {
            this.$refs["form"].validateField(prop)
        }
    },
    changeEndhour(index,prop){
        if(this.form.sedentaries[index].start_hour) {
            this.$refs["form"].validateField(prop)
        }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deviceid: undefined, // 设备id
        deviceNumber: undefined, // 设备编号
        sedentaries: [
          {
            repeat: true,
            week: [
              "monday",
              "tuesday",
              "wednesday",
              "thursday",
              "friday",
              "saturday",
              "sunday",
            ],
            start_hour: undefined,
            end_hour: undefined,
            duration: "",
            threshold: 40,
          },
        ],
      };
      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;
    },
    // 新增久坐
    addSedentary() {
      if (this.form.sedentaries && this.form.sedentaries.length == 3) {
        this.msgError("最多设置3个久坐提醒!");
        return;
      }
      const obj = {
        repeat: true,
        week: [
          "monday",
          "tuesday",
          "wednesday",
          "thursday",
          "friday",
          "saturday",
          "sunday",
        ],
        // monday: true,
        // tuesday: true,
        // wednesday: true,
        // thursday: true,
        // friday: true,
        // saturday: true,
        // sunday: true,
        start_hour: undefined,
        end_hour: undefined,
        duration: "",
        threshold: 40,
      };
      this.form.sedentaries.push(obj);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.deviceNumber != undefined) {
            const sedentaries = this.form.sedentaries.map((item) => ({
              repeat: item.repeat,
              monday: item.week.includes("monday"),
              tuesday: item.week.includes("tuesday"),
              wednesday: item.week.includes("wednesday"),
              thursday: item.week.includes("thursday"),
              friday: item.week.includes("friday"),
              saturday: item.week.includes("saturday"),
              sunday: item.week.includes("sunday"),
              start_hour: item.start_hour,
              end_hour: item.end_hour,
              duration: item.duration,
              threshold: item.threshold,
            }));
            const param = {
              deviceid: this.form.deviceNumber,
              sedentaries,
            };
            this.btnLoading = true;
            setSedentary(param)
              .then((res) => {
                this.btnLoading = false;
                if (res.code == 200) {
                  this.msgSuccess("操作成功");
                  this.open = false;
                } else {
                  this.msgError(res.msg);
                }
              })
              .catch((err) => {
                this.btnLoading = false;
              });
          }
        }
      });
    },
    // 删除
    handleDelete(row,index) {
        this.form.sedentaries.splice(index,1)
    }
  },
};
</script>
  
<style lang="scss" scoped>
::v-deep .el-form-item {
    margin-bottom: 0;
}
.inputbox {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .label {
        font-size: 14px;
        color: #606266;
        font-weight: 700;
    }
}
.tips {
    font-size: 12px;
    margin: 15px 0 0 15px;
    color: #999;
}
</style>