<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="500px"
    @close="close"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="数据下发" prop="dataValue">
        <el-input
          v-if="is_text"
          v-model="form.dataValue"
          type="text"
        ></el-input>
        <el-radio-group v-else v-model="form.dataValue">
          <div v-for="(item, index) in unitData" :key="index">
            <el-radio-button v-if="item.label != '故障'" :label="item.value">
              {{ item.label }}
            </el-radio-button>
          </div>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button size="small" @click="close">取 消</el-button>
      <el-button type="primary" size="small" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { writeData } from '@/api/monitor';
export default {
  data() {
    return {
      form: {
        deviceCode: '',
        dataKey: '',
        dataValue: '',
      },
      is_text: false,
      rules: {
        projectId: [
          { required: true, trigger: 'change', message: '请选择项目' },
        ],
      },
      title: '',
      dialogFormVisible: false,
      unitData: [],
    };
  },
  created() {},
  methods: {
    showEdit(row) {
      this.title = '下发数据';
      this.form.deviceCode = row.deviceCode;
      this.form.dataKey = row.dataKey;
      if (row.convertFlag == '1') {
        this.is_text = false;
      } else {
        this.is_text = true;
      }
      const unit = row.unit;
      if (unit.indexOf(';')) {
        const unitArr = unit.split(';');
        const unitData = [];
        for (let i = 0; i < unitArr.length; i++) {
          const units = unitArr[i].split(':');
          unitData.push({ value: units[0], label: units[1] });
        }
        this.unitData = unitData;
      }
      this.dialogFormVisible = true;
    },
    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 { msg, code } = await writeData(this.form);
          if (code === 0) {
            this.$notify({
              title: msg,
              type: 'success',
            });
          } else {
            this.$notify({
              title: msg,
              type: 'error',
            });
          }
          this.$refs['form'].resetFields();
          this.dialogFormVisible = false;
          this.$parent.fetchData();
        } else {
          return false;
        }
      });
    },
  },
};
</script>
