<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" append-to-body>
    <el-form ref="dataForm" :rules="rules" :model="configForm" label-well-code="right" label-width="110px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item v-if="dialogStatus=='create'" label="设备编号" prop="deviceId">
            <el-select
              v-model="configForm.deviceId"
              :loading="loading"
              :disabled="dialogStatus=='update'?true:false"
              filterable
              placeholder="请输入设备编号"
            >
              <el-option
                v-for="item in devices"
                :key="item.id"
                :label="item.devcode"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="dialogStatus=='update'" label="设备编号">
            <el-input v-model="deviceForm.devcode" type="text" placeholder="未知" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="deviceForm.deviceName!=''" label="设备名称">
            <el-input v-model="deviceForm.deviceName" type="text" placeholder="未知" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item v-if="deviceForm.deviceTypeName!=''" label="设备类型" prop="deviceType">
            <el-input v-model="deviceForm.deviceTypeName" type="text" placeholder="未知" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="deviceForm.deptName!=''" label="权属单位" prop="deptName">
            <el-input v-model="deviceForm.deptName" type="text" placeholder="未知" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="重传次数" prop="retryTimes">
            <el-input-number v-model="configForm.retryTimes" :min="1" :max="9" type="text" placeholder="必填" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="采集间隔(分)" prop="collectInterval">
            <el-input v-model.trim="configForm.collectInterval" type="text" placeholder="必填" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="上传周期(分)" prop="uploadPeriod">
            <el-input v-model.trim="configForm.uploadPeriod" type="text" placeholder="必填" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最大尝试次数">
            <el-input-number v-model="configForm.attemptsMax" :min="1" :max="100" type="text" placeholder="必填" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="showIp" :gutter="20">
        <el-col :span="12">
          <el-form-item label="ip地址" prop="ip">
            <el-input v-model.trim="configForm.ip" type="text" placeholder="非必填" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="端口号" prop="port">
            <el-input v-model.trim="configForm.port" type="text" placeholder="非必填" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :disabled="!canEdit" type="primary" @click="saveData">
        保存
      </el-button>
      <el-button @click="cancel">
        取消
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { editTubeConfig } from '@/api/config/tubeconfig'
import { getDeviceSimpleList } from '@/api/config/liquidconfig'
import { validateFloatPlus } from '@/utils/validate'
export default {
  name: 'EditTubeConfig',
  data() {
    const validateIp = (rule, value, callback) => {
      if (value !== '') {
        if ((/((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))/).test(value) === false) {
          callback(new Error('请填写正确的ip地址'))
        } else {
          callback()
        }
      } else {
        // callback(new Error('ip地址不能为空'))
        callback()
      }
    }
    const validatePort = (rule, value, callback) => {
      if (value !== '') {
        if ((/[1-9]$|(^[1-9][0-9]$)|(^[1-9][0-9][0-9]$)|(^[1-9][0-9][0-9][0-9]$)|(^[1-6][0-5][0-5][0-3][0-5]$)/).test(value) === false) {
          callback(new Error('请填写正确的端口号'))
        } else {
          callback()
        }
      } else {
        // callback(new Error('端口号不能为空'))
        callback()
      }
    }
    const validateCollectCycle = (rule, value, callback) => {
      if (value !== '') {
        if (validateFloatPlus(value, 1, 60) === true) {
          callback()
        } else {
          callback(new Error('请填写1到60数值'))
        }
      } else {
        callback(new Error('采集间隔不能为空'))
      }
    }
    const validateUpPeriod = (rule, value, callback) => {
      if (value !== '') {
        if (validateFloatPlus(value, 0, 10080) === true) {
          callback()
        } else {
          callback(new Error('请填写0到10080之间数值'))
        }
      } else {
        callback(new Error('上传周期不能为空'))
      }
    }
    return {
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update
      deviceForm: {
        deviceName: '',
        deviceTypeName: '',
        deptName: '',
        devcode: '',
        deviceType: ''
      }, // 设备基本信息
      configForm: {
        id: '', // config id
        deviceId: '', // 设备id
        collectInterval: '', // 报警阈值
        uploadPeriod: '', // 安装高度
        retryTimes: '3', // 重传次数
        attemptsMax: '3', // 最大尝试次数
        ip: '', // ip地址
        port: '' // 端口号
      },
      textMap: {
        update: '编辑',
        create: '新增'
      }, // 表头显示标题
      devices: [], // 设备下拉选择列表
      loading: false, // 加载动画是否显示
      canEdit: true, // 是否允许点击保存按钮
      rules: {
        collectInterval: [{ required: true, trigger: ['blur', 'change'], validator: validateCollectCycle }],
        uploadPeriod: [{ required: true, trigger: ['blur', 'change'], validator: validateUpPeriod }],
        deviceId: [{ required: true, message: '设备编号不能为空', trigger: ['blur', 'change'] }],
        ip: [{ trigger: ['blur', 'change'], validator: validateIp }],
        port: [{ trigger: ['blur', 'change'], validator: validatePort }]
      } // 前端校验规则
    }
  },
  computed: {
    watchDeviceId() { // 监控权属单位变化
      return this.configForm.deviceId
    },
    showIp() { // 是否显示ip配置
      return true
    }
  },
  watch: {
    watchDeviceId(newValue, oldValue) {
      for (const device of this.devices) {
        if (device.id === newValue) {
          this.deviceForm.deviceTypeName = device.deviceTypeName
          this.deviceForm.deptName = device.deptName
          this.deviceForm.deviceName = device.deviceName
          return
        }
      }
    }
  },
  methods: {
    // 初始化对话框
    initDialog: function(dialogStatus, dialogFormVisible, row = null) {
      this.dialogStatus = dialogStatus
      this.dialogFormVisible = dialogFormVisible
      this.canEdit = true
      if (dialogStatus === 'create') { // 如果是新增，清除验证
        this.resetForm()
        this.fetchDevice()
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      } else if (dialogStatus === 'update') { // 如果是修改，将row中数据填写到输入框中
        this.deviceForm = {
          deviceName: row.deviceName,
          devcode: row.devcode,
          deptName: row.deptName,
          deviceType: row.deviceType,
          deviceTypeName: row.deviceTypeName
        }
        this.configForm = {
          id: row.id,
          deviceId: row.deviceId, // 设备id
          collectInterval: row.collectInterval, // 采集间隔
          uploadPeriod: row.uploadPeriod, // 上传周期
          retryTimes: row.retryTimes, // 重传次数
          ip: row.ip, // ip地址
          port: row.port, // 端口号
          attemptsMax: row.attemptsMax // 最大尝试次数
        }
      }
    },
    // 重置表单
    resetForm() {
      this.deviceForm = {
        deviceName: '',
        deviceTypeName: '',
        deptName: '',
        devcode: ''
      }
      this.configForm = {
        deviceId: '', // 设备id
        collectInterval: '', // 采集间隔
        uploadPeriod: '', // 上传周期
        retryTimes: '3', // 重传次数
        ip: '', // ip地址
        port: '', // 端口号
        attemptsMax: '3' // 最大尝试次数
      }
    },
    // 保存数据
    saveData: function() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.canEdit = false
          editTubeConfig(this.configForm).then(response => {
            if (response.code === 200) {
              this.$message.success('配置成功')
              this.$emit('watchChild')
              this.dialogFormVisible = false
            }
            this.canEdit = false
          }).catch(_ => {
            this.canEdit = true
          })
        }
      })
    },
    fetchDevice() {
      this.loading = true
      getDeviceSimpleList('12', '0').then(response => {
        this.loading = false
        this.devices = response.data
      })
    },
    cancel: function() {
      this.dialogFormVisible = false
      this.$emit('watchChild')
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .el-select{
    width: 100%;
  }
  .el-input-number{
    width: 100%;
  }
</style>
