<!-- 添加采样 -->
<template>
  <el-dialog
    :title="comonentVar.modelTitle"
    :visible.sync="comonentVar.dialogVisible"
    :destroy-on-close="true"
    :close-on-click-modal="true"
    @close="modelOnClose"
  >
    <div class="model-form">
      <!-- label-width 设置了：label 和 input 就不会换行 -->
      <el-form ref="modelForm" :model="modelForm" label-width="100px" :rules="rules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="modelForm.name" autocomplete="off" maxlength="32" />
        </el-form-item>
        <!-- <el-form-item label="查询id">
          <el-input v-model="form.product" />
        </el-form-item> -->
        <el-form-item class="modelInput" label="寄存器范围" prop="range">
          <template slot-scope="scope">
            <el-select
              :key="toString(scope.row)"
              v-model="modelForm.range"
              :disabled="isupdata"
              clearable
              placeholder=""
            >
              <el-option
                v-for="item in checkPointFuctionOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="寄存器地址" prop="offset">
          <el-input v-model="modelForm.offset" :disabled="isupdata" type="number" maxlength="32" />
        </el-form-item>
        <el-form-item class="modelInput" label="值类型" prop="dataType">
          <template slot-scope="scope">
            <el-select
              :key="toString(scope.row)"
              v-model="modelForm.dataType"
              clearable
              placeholder=""
            >
              <el-option
                v-for="item in valueTypeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </template>
        </el-form-item>
        <el-form-item class="modelInput" label="字内交换">
          <el-switch
            v-model="modelForm.swapByte"
            active-text="交换"
            inactive-text="不交换"
          />
        </el-form-item>
        <el-form-item class="modelInput" label="字节交换">
          <el-switch
            v-model="modelForm.swapWord"
            active-text="交换"
            inactive-text="不交换"
          />
        </el-form-item>
        <el-form-item label="倍率">
          <el-input v-model="modelForm.scaling" maxlength="32" />
        </el-form-item>
        <el-form-item label="偏移量">
          <el-input v-model="modelForm.adjust" maxlength="32" />
        </el-form-item>
      </el-form>
      <div class="buttons">
        <div class="cancel">
          <el-button class="lightButton" icon="el-icon-circle-close" size="small" @click="cancelForm">取消</el-button>
        </div>
        <div class="submit">
          <el-button
            type="primary"
            icon="el-icon-circle-check"
            class="dark-button"
            size="small"
            @click="submitForm"
          >保存</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import { mapGetters } from 'vuex'
import {
  httpGet,
  putData
} from '@/api/common-action'
export default {
  name: 'ModelFormSample',
  // model-parames 模态框参数
  props: {
    modelParames: {
      type: Object,
      default: function() {
        return {}
      }
    },
    sampleData: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      rules: {
        name: [{ required: true, message: '名称不能为空' }],
        range: [{ required: true, message: '寄存器范围不能为空' }],
        offset: [{ required: true, message: '寄存器地址不能为空' }],
        dataType: [{ required: true, message: '值类型不能为空' }]
      },
      comonentVar: {
        modelTitle: '加载中...',
        dialogVisible: true
      },
      // 表单默认数据,选项数组 一定要在这里先定义，否则无法正常获取
      modelForm: {
        name: ''
      },
      // 下拉框单独定义 避免错位
      valueTypeOptions: [],
      checkPointFuctionOptions: [],
      isupdata: false
    }
  },
  computed: {
    ...mapGetters([
      'roles'
    ])
  },
  created() {
  },
  mounted() {
    // 初始化
    this.$nextTick(() => {
      this.initFunctions()
      // console.log('sampleData', this.sampleData)
    })
  },
  methods: {
    // 初始化
    async initFunctions() {
      //  初始化 值类型 下拉框选项
      this.valueTypeOptions = JSON.parse(localStorage.getItem('valueTypeOptions'))
      // 因为 this.modelForm 在前面已经赋值过了，所以这里必须使用 set 的方式赋值，否则无法更新选项

      //  初始化 功能码 下拉框选项
      this.checkPointFuctionOptions = JSON.parse(localStorage.getItem('checkPointFuctionOptions'))

      this.comonentVar.modelTitle = `[${this.modelParames.deviceName}]-添加采样`
      if (this.modelParames.modelFormData) {
        if (this.modelParames.modelFormData.id > 0) {
          this.comonentVar.modelTitle = `[${this.modelParames.deviceName}]-编辑采样`
          // #TODO: 编辑状态 锁住 寄存器范围和寄存器地址
          this.isupdata = true
          // 如果 寄存器范围 是 开关量 输出/输入 则 值类型 固定为 开关
          // 如果 寄存器范围 是 其它值类型 默认为 16位有符号数
          // this.$message({
          //   message: `编辑功能还未准备好`,
          //   type: 'error',
          //   offset: window.screen.height / 3
          // })
          // 如果是编辑，从 接口 单测点查询 再获取一次数据
          // /product/model/:product/:tag
          // 例 :product 1100000645
          // 例 :tag 6386 tag id 为采样列表序号id
          const getUrl = `/product/model/${this.modelParames.productId}/${this.modelParames.modelFormData.iec104}`

          httpGet(getUrl).then(res => {
            this.modelForm = res
            if (res.swapByte === 1 || res.swapByte === true) {
              this.modelForm.swapByte = true
            } else {
              this.modelForm.swapByte = false
            }
            if (res.swapWord === 1 || res.swapWord === true) {
              this.modelForm.swapWord = true
            } else {
              this.modelForm.swapWord = false
            }
          })
          // this.modelForm = this.modelParames.modelFormData
          // console.log('mounted this.modelForm= ', this.modelForm)
        }
      }

      // 添加 采样 数据示例：
      // {
      //   "id": 0,
      //   "name": "my_tag",
      //   "dataType": "BOOL",
      //   "range": "COIL_STATUS",
      //   "offset": 0,
      //   "scaling": 1,
      //   "adjust": 0,
      //   "swapByte": false,
      //   "swapWord": false,
      //   "pollingCycle": 0
      // }

      // this.$forceUpdate()
      // httpGet(getUrl).then(res => {
      //   delete res.code
      //   console.log('获取测试规则 res= ', res)
      //   this.modelForm.ruleOptions = res
      // })
    },
    // 关闭model时执行
    modelOnClose() {
      this.$emit('toggleModel', 'ModelFormSample', false)
    },
    // 表单提交按钮
    submitForm() {
      if (this.isupdata === false) {
        // console.log('this.modelForm', this.modelForm)
        // console.log('sampleData', this.sampleData)
        const hasThis = this.sampleData.some(item => item.range === this.modelForm.range && item.offset === parseInt(this.modelForm.offset))
        if (hasThis) {
          this.$message({
            type: 'error',
            message: '该采样值已存在',
            offset: window.screen.height / 3
          })
          return
        }
      }
      let checkForm = false
      this.$refs.modelForm.validate(f => { checkForm = f })
      if (!checkForm) {
        return
      }

      delete this.modelForm.code
      const putUrl = `/test/plan/${this.modelParames.curPlanId}/point`
      // const putUrl = `/test/plan/${this.modelForm.id}/point`
      putData(putUrl, this.modelForm).then(res => {
        // 保存表单
        this.comonentVar.dialogVisible = false
      })
    },
    // 表单取消按钮
    cancelForm() {
      this.modelForm = {}
      this.comonentVar.dialogVisible = false
    }
  }
}
</script>
<style lang="scss">
.steps-setting {
  padding: 10px 0;
  label {
    padding: 0;
  }
}
</style>
<style lang="scss" scoped>
// 表单按钮样式
.buttons {
  display: flex;
  justify-content: right;
  padding-bottom: 20px;

  .submit {
    padding-left: 20px;
  }
}
.model-form {
  .setting-input {
    width: 100px;
  }
}
// 按钮公用样式
.dark-button {
  background-color: #00706B;
  border: 1px #00706B solid;
  color: #fff;
}

.light-button {
  color: #00706B;
  border: 1px #00706B solid;
}
</style>
