<template>
  <div class="manage-container">
    <el-dialog
      v-model="dialogFormVisible"
      :title="title"
      width="500px"
      @close="close"
    >
      <vab-query-form>
        <h1 class="tigger-title">添加触发器信息</h1>
      </vab-query-form>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item :label="$t('trigger.cfqmc')" prop="name">
          <el-input
            v-model="form.name"
            size="small"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="站点" prop="deviceId">
          <el-select
            v-model="form.deviceId"
            size="small"
            placeholder="请选择站点"
            @change="getDeviceId"
          >
            <el-option
              v-for="item in deviceData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('dataEnquiry.cgq')" prop="sensorId">
          <el-select
            v-model="form.sensorId"
            size="small"
            placeholder="请选择传感器"
          >
            <el-option
              v-for="item in sensorData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <vab-query-form>
          <h1 class="tigger-title">触发条件</h1>
        </vab-query-form>
        <el-form-item label="条件类型" prop="triggerCondition">
          <el-select
            ref="condition"
            v-model="form.triggerCondition"
            size="small"
            placeholder="请选择条件类型"
            @change="condition"
          >
            <el-option
              v-for="item in conditionData"
              :key="item.dataCode"
              :label="item.dataValue"
              :value="item.dataCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="mShow == true" label="M">
          <el-input v-model="data.m" size="small" placeholder="M"></el-input>
        </el-form-item>
        <el-form-item v-if="xShow == true" label="X">
          <el-input v-model="data.x" size="small" placeholder="X"></el-input>
        </el-form-item>
        <el-form-item v-if="yShow == true" label="Y">
          <el-input v-model="data.y" size="small" placeholder="Y"></el-input>
        </el-form-item>
        <el-form-item label="是否发送报警信息给报警联系人" prop="alarmFlag">
          <el-select
            v-model="form.alarmFlag"
            size="small"
            placeholder="是否发送"
          >
            <el-option
              v-for="item in alarmFlagData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联控设备动作" prop="controlFlag">
          <el-select
            v-model="form.controlFlag"
            size="small"
            placeholder="请选择联控设备动作"
          >
            <el-option
              v-for="item in controlFlagData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联控设备" prop="controlDevice">
          <el-select
            v-model="form.controlDevice"
            size="small"
            placeholder="请选择联控设备"
            @change="deviceChange"
          >
            <el-option
              v-for="item in controlDevicesData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联控传感器" prop="controlSensor">
          <el-select
            v-model="form.controlSensor"
            size="small"
            placeholder="请选择联控传感器"
          >
            <el-option
              v-for="item in controlSensorData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('alarm.bjjb')" prop="alarmLevel">
          <el-select
            v-model="form.alarmLevel"
            size="small"
            placeholder="请选择报警级别"
          >
            <el-option
              v-for="item in levelData"
              :key="item.dataCode"
              :label="item.dataValue"
              :value="item.dataCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('trigger.cfzq')" prop="triggerCycle">
          <el-input
            v-model="form.triggerCycle"
            size="small"
            placeholder="单位秒 0不循环触发"
          ></el-input>
        </el-form-item>
        <el-form-item label="报警信息模板" prop="alarmTemplate">
          <el-input
            v-model="form.alarmTemplate"
            size="small"
            placeholder="报警信息模板"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button type="primary" size="small" @click="save">保存</el-button>
        <el-button size="small" @click="close">返回</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  doEdit,
  doAdd,
  selectDeviceByProjectId,
  selectAllAlarmLevel,
  selectAllTriggerCondition,
  selectControlDevices,
  selectSensorByDeviceId,
} from '@/api/trigger';
export default {
  name: 'TriggerEdit',
  data() {
    return {
      form: {
        id: '',
        name: '',
        projectId: '',
        deviceId: '',
        sensorId: '',
        triggerCondition: '',
        triggerConditionParams: '',
        triggerCycle: '',
        alarmFlag: '', // 1
        alarmLevel: '', //1
        controlFlag: '',
        controlDevice: '',
        controlSensor: '',
        controlData: '',
        alarmTemplate: '', //1
        // alarmInfoFlag: '',
        // alarmRecoveryFlag: '',
        // alarmInfoLevel: '',
        // status: '',
      },
      data: {
        x: '',
        y: '',
        m: '',
      },
      rules: {
        name: [
          { required: true, trigger: 'blur', message: '请输入触发器名称' },
        ],
        deviceId: [
          { required: true, trigger: 'change', message: '请选择设备' },
        ],
        sensorId: [
          { required: true, trigger: 'change', message: '请选择传感器' },
        ],
        triggerCondition: [
          { required: true, trigger: 'change', message: '请选择条件类型' },
        ],
        alarmLevel: [
          { required: true, trigger: 'change', message: '请选择报警级别' },
        ],
      },
      title: '',
      dialogFormVisible: false,
      projectId: '',
      diffData: {},
      ruleForm: [],
      typeData: [],
      levelData: [],
      controlSensorData: [],
      conditionData: [],
      userData: [],
      controlDevicesData: [],
      deviceData: [],
      sensorData: [],
      flagData: [
        { label: '开启', value: '0' },
        { label: '关闭', value: '1' },
      ],
      controlFlagData: [
        { label: '不联控', value: '0' },
        { label: '联控', value: '1' },
      ],
      RecoveryFlagData: [
        { label: '开启', value: '0' },
        { label: '关闭', value: '1' },
      ],
      alarmFlagData: [
        { label: '不发送', value: '0' },
        { label: '发送', value: '1' },
      ],
      statusData: [
        { label: '正常', value: '0' },
        { label: '暂停', value: '1' },
      ],
      xShow: false,
      yShow: false,
      mShow: false,
      isControl: false,
      isUser: false,
      isLevel: false,
    };
  },
  created() {
    this.form.projectId = sessionStorage.getItem('projectId');
    this.projectId = sessionStorage.getItem('projectId');
  },
  methods: {
    //设备列表
    async getDevice() {
      const { data } = await selectDeviceByProjectId({
        projectId: this.projectId,
      });
      this.deviceData = data;
    },
    deviceChange() {
      this.getControlSensorData();
    },
    async getControlSensorData() {
      const { data } = await selectSensorByDeviceId({
        deviceId: this.form.controlDevice,
      });
      this.controlSensorData = data;
    },
    getDeviceId(deviceId) {
      this.getSensor(deviceId);
    },
    controlUserShow(type) {
      if (
        (type.indexOf('0') !== -1 && type.indexOf('1') !== -1) ||
        (type.indexOf('0') !== -1 && type.indexOf('2') !== -1) ||
        (type.indexOf('0') !== -1 && type.indexOf('3') !== -1)
      ) {
        this.isControl = true;
        this.isUser = true;
      } else if (type.indexOf('0') != -1) {
        this.isControl = true;
        this.isUser = false;
      } else if (type.indexOf('1') != -1 || type.indexOf('2') != -1) {
        this.isControl = false;
        this.isUser = true;
      } else {
        this.isControl = false;
        this.isUser = false;
      }
    },
    //传感器列表
    async getSensor() {
      const { data } = await selectSensorByDeviceId({
        deviceId: this.form.deviceId,
      });
      this.sensorData = data;
    },
    condition(e) {
      let obj = {};
      obj = this.conditionData.find(item => {
        return item.dataCode === e;
      });
      const code = obj.dataValue;
      this.xymShow(code);
    },
    xymShow(code) {
      if (code.indexOf('x') != -1 && code.indexOf('y') != -1) {
        this.xShow = true;
        this.yShow = true;
        this.mShow = false;
      } else if (code.indexOf('x') != -1 && code.indexOf('m') != -1) {
        this.xShow = true;
        this.yShow = false;
        this.mShow = true;
      } else if (code.indexOf('x') != -1) {
        this.xShow = true;
        this.yShow = false;
        this.mShow = false;
      } else if (code.indexOf('y') != -1) {
        this.xShow = false;
        this.yShow = true;
        this.mShow = false;
      } else if (code.indexOf('m') != -1) {
        this.xShow = false;
        this.yShow = false;
        this.mShow = true;
      }
      this.data.x = '';
      this.data.y = '';
      this.data.m = '';
    },
    //报警级别
    async getLevel() {
      const { data } = await selectAllAlarmLevel();
      this.levelData = data;
    },
    //触发条件
    async getCondition() {
      const { data } = await selectAllTriggerCondition();
      this.conditionData = data;
    },
    //联控的设备列表
    async getControlDevice() {
      const projectId =
        this.form.projectId == '' ? this.projectId : this.form.projectId;
      const { data } = await selectControlDevices({
        projectId: projectId,
      });
      this.controlDevicesData = data;
    },
    showEdit(row, status) {
      this.getLevel();
      this.getCondition();
      this.getControlDevice();
      this.getDevice();
      this.deviceData = {};
      if (status == 1) {
        this.title = '添加触发器';
      } else {
        this.title = '编辑触发器';
        this.getTriggerData(row);
      }
      this.dialogFormVisible = true;
    },
    async getTriggerData(data) {
      const list = Object.assign({}, data);
      this.form = list;
      this.form.deviceId = list.device.id;
      this.getSensor();
      this.form.sensorId = list.sensor.id;
      if (list.alarmLevel != null) {
        this.form.alarmLevel = list.alarmLevel.dataCode;
      }
      if (list.controlDevice != null) {
        this.form.controlDevice = Number(list.controlDevice.id);
        this.getControlSensorData();
      }
      if (list.controlSensor != null) {
        this.form.controlSensor = Number(list.controlSensor.id);
      }
      if (list.triggerCondition != null) {
        this.form.triggerCondition = list.triggerCondition.dataCode;
        this.xymShow(data.triggerCondition.dataValue);
        const triggerConditionParams = data.triggerConditionParams.split(',');
        console.log(this.mShow, this.xShow, this.yShow);
        if (this.mShow == true) {
          this.data.m =
            triggerConditionParams[2] == undefined
              ? triggerConditionParams[1]
              : triggerConditionParams[2];
        }
        if (this.xShow == true) {
          this.data.x =
            triggerConditionParams[0] == undefined
              ? ''
              : triggerConditionParams[0];
        }
        if (this.yShow == true) {
          this.data.y =
            triggerConditionParams[1] == undefined
              ? triggerConditionParams[0]
              : triggerConditionParams[1];
        }
      }
    },
    arrToSrt(data, field = '') {
      if (undefined != data && data.length != 0) {
        let str = '';
        for (let i = 0; i < data.length; i++) {
          if (field) {
            str += data[i].id + ',';
          } else {
            str += data[i] + ',';
          }
        }
        return str.substring(0, str.length - 1);
      }
    },
    close() {
      this.$refs['form'].resetFields();
      this.form = this.$options.data().form;
      this.dialogFormVisible = false;
      this.$emit('fetch-data');
    },
    save() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          const data = this.data;
          let dataObj = '';
          if (data.m != '') {
            dataObj += data.m + ',';
          }
          if (data.x != '') {
            dataObj += data.x + ',';
          }
          if (data.y != '') {
            dataObj += data.y + ',';
          }
          this.form.triggerConditionParams = dataObj.substring(
            0,
            dataObj.length - 1
          );
          if (this.form.id) {
            delete this.form.sensor;
            delete this.form.device;
            console.log(this.form);
            const { msg } = await doEdit(this.form);
            this.$notify({
              title: msg,
              type: 'success',
            });
          } else {
            delete this.form.id;
            const { msg } = await doAdd(this.form);
            this.$notify({
              title: msg,
              type: 'success',
            });
          }
          this.$refs['form'].resetFields();
          this.dialogFormVisible = false;
          this.$parent.fetchData();
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.tigger-title {
  font-size: 18px;
  border-left: 6px solid #3281fd;
  padding-left: 10px;
  margin-bottom: 20px;
}
</style>
