<template>
  <el-dialog :close-on-click-modal="false" :visible.sync="visible" append-to-body :modal-append-to-body='false'>
    <div slot="title" class="title-bold">{{id ? '编辑设备': '新增设备'}}</div>
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" :label-width="formLabelWidth" v-loading="loading">
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备所属层级" prop="level">
              <el-select v-model="dataForm.level" style='width:100%;' placeholder="请选择" autocomplete="off" clearable @change="changeHandle" disabled>
                <el-option v-for="item in optionLevel" :key="item.value" :label="item.label" :value="item.value" ></el-option>
              </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属节点名称" prop="stationId">
            <el-input style="width:100%" v-model="jdName" disabled placeholder=""></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备名称" prop="name">
            <el-input style="width:100%" v-model="dataForm.name" placeholder="请输入设备名称" autocomplete="off" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备编码" prop="code">
            <el-input style="width:100%" v-model="dataForm.code" placeholder="请输入设备编码" autocomplete="off" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备类型" prop="type">
            <el-select  style='width:100%;'  :disabled="typeDisabled" v-model="dataForm.type" placeholder="请选择设备类型" clearable>
              <el-option
                v-for="item in optionType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备IP地址" prop="specifications">
            <el-input style="width:100%" v-model="dataForm.specifications" placeholder="请输入设备IP地址" autocomplete="off" clearable ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="端口" prop="port">
            <el-input style="width:100%" v-model="dataForm.port" placeholder="请输入端口" autocomplete="off" type="number" clearable ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生产厂家" prop="factory">
            <el-input style="width:100%" v-model="dataForm.factory" placeholder="请输入生产厂家" autocomplete="off" clearable ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="部署地址" prop="deployAddress">
            <el-input style="width:100%" v-model="dataForm.deployAddress" placeholder="请输入部署地址" autocomplete="off" clearable ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input style="width:100%" type="textarea" placeholder="请输入备注" v-model="dataForm.remark" rows="5" resize="none" ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" size='medium' @click="cancel">取 消</el-button>
      <el-button type="primary" size='medium'  @click="saveHandling" v-prevent-re-click>保 存</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    let validateIpUnique = (rule, value, callback) => {
             this.$http({
               url: this.$http.adornUrl(`/eqEquipment/queryIpUnique`),
               method: 'get',
               params: {
                 ip: this.dataForm.specifications,
                 stationId: this.dataForm.stationId
               }
             }).then(data => {
                   if (data && data.code === 0) {
                       if (data.bean) {
                         if (this.id) {
                           if (this.dataForm.id !== data.bean.id) {
                             callback(new Error('ip已存在'))
                           } else {
                             callback()
                           }
                         } else {
                           callback(new Error('ip已存在'))
                         }
                       } else {
                         callback()
                       }
                   }
             })
    }

    let nameUnique = (rule, value, callback) => {
      this.$http({
        url: this.$http.adornUrl(`/eqEquipment/queryNameUnique`),
        method: 'get',
        params: {
          name: this.dataForm.name,
          stationId: this.dataForm.stationId
        }
      }).then(data => {
        if (data && data.code === 0) {
          if (data.bean) {
            if (this.id) {
              if (this.dataForm.id !== data.bean.id) {
                callback(new Error('设备名称已存在'))
              } else {
                callback()
              }
            } else {
              callback(new Error('设备名称已存在'))
            }
          } else {
            callback()
          }
        }
      })
    }

    return {
      id: null,
      visible: true,
      formLabelWidth: '120px',
      dataForm: {},
      jdName: '',
      loading: false,
      typeDisabled: false,
      dataRule: {
        level: [
          { required: true, message: '请选择设备所属层级', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '设备名称不能为空', trigger: 'blur' },
          { max: 100, message: '长度不能大于100个字符', trigger: 'blur' },
          { validator: nameUnique, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '设备编码不能为空', trigger: 'blur' },
          { max: 20, message: '长度不能大于20个字符', trigger: 'blur' }
        ],
        // stationId: [
        //   { required: true, message: '线路站点不能为空', trigger: 'blur' }
        // ],
        type: [
          { required: true, message: '请选择设备类型', trigger: 'change' }
        ],
        specifications: [
          { required: true, message: '设备IP地址不能为空', trigger: 'blur' },
          { max: 20, message: '长度不能大于20个字符', trigger: 'blur' },
          { validator: validateIpUnique, trigger: 'blur' }
        ],
        port: [
          { required: true, message: '端口不能为空', trigger: 'blur' },
          { pattern: /(^[1-9]\d*$)/, message: '只能输入正数', trigger: 'blur' },
          { max: 10, message: '长度不能大于10个字符', trigger: 'blur' }
        ],
        factory: [
          { max: 100, message: '长度不能大于100个字符', trigger: 'blur' }
        ],
        deployAddress: [
          { max: 100, message: '长度不能大于100个字符', trigger: 'blur' }
        ],
        remark: [
          { max: 500, message: '长度不能大于500个字符', trigger: 'blur' }
        ]
      },
      options: [],
      optionLevel: [
        {
          label: '本级设备',
          value: 1
        },
        {
          label: '外接设备',
          value: 2
        }
      ],
      stationInfo: null,
      optionType: [
        {
          label: '应用服务器',
          value: 1
        },
        {
          label: '数据库服务器',
          value: 2
        },
        {
          label: '集群服务器',
          value: 3
        }
      ]
    }
  },
  created() {
  },
  methods: {
    init(id, paramLevel) {
      //清除验证提示
      this.jdName = ''
      this.id = null
      this.dataForm = {}
      this.visible = true
      this.typeDisabled = false
      //let code = localStorage.getItem('stationId')
      //this.dataForm.byx3 = code
      this.$refs['dataForm'].resetFields()
      if (id) {
        this.id = id
        this.$http({
          url: this.$http.adornUrl(`/eqEquipment/getId/` + this.id),
          method: 'get'
        }).then(data => {
          if (data && data.code === 0) {
            this.dataForm = data.bean
            this.dataForm.stationName = this.dataForm.sname
            this.dataForm.lineName = this.dataForm.liName
            this.changeHandle(this.dataForm.level)
            if (this.dataForm.level === 2) this.typeDisabled = true
            //this.dataForm.stationId = Array.from([data.bean.lineId, data.bean.stationId])
          }
        })
      } else {
        if (paramLevel === 2) {
          this.dataForm.type = 1
          this.typeDisabled = true
        }
        this.getStationName(paramLevel)
      }
    },
    changeHandle(val) {
      if (val === 1) {
        this.jdName = this.dataForm.stationName
      } else if (val === 2) {
        this.jdName = this.dataForm.lineName
      } else {
        this.jdName = ''
      }
    },
    //获取当前站点名称
    getStationName(paramLevel) {
      this.$http({
        url: this.$http.adornUrl(`/liStation/queryId/` + localStorage.getItem('stationId')),
        method: 'get'
      }).then(data => {
        if (data && data.code === 0) {
          this.dataForm.byx3 = data.bean.id
          this.dataForm.stationName = data.bean.stationName
          this.dataForm.lineId = data.bean.lineId
          this.dataForm.lineName = data.bean.lineName
          if (paramLevel) {
            this.changeHandle(paramLevel)
            this.dataForm.level = paramLevel
          }
        }
      })
    },
    //根据用户角色权限获取站点信息
    // getStationByUserId() {
    //   this.$http({
    //     url: this.$http.adornUrl(`/liLine/getTreeListStation`),
    //     method: 'post',
    //     data: {}
    //   }).then(data => {
    //     if (data && data.code === 0) {
    //       for (let li of data.liList) {
    //         let arr = []
    //         for (let lis of data.lisList) {
    //           if (li.id === lis.lineId) {
    //             arr.push({ value: lis.id, label: lis.stationName })
    //           }
    //         }
    //         this.options.push({ value: li.id, label: li.name, children: arr })
    //       }
    //     }
    //   })
    // },
    //添加，修改
    saveHandling() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (!/(^[1-9]\d*$)/.test(this.dataForm.port)) {
            this.$message.error('端口必须为正整数！')
            return
          }
          // debugger
          //let node = this.$refs['stationOption'].getCheckedNodes()
          //this.dataForm.stationId = this.dataForm.stationId.toString()
          //this.dataForm.stationName = node[0].parent.data.label + node[0].data.label
          this.loading = true
          this.dataForm.stationId = localStorage.getItem('stationId')
          this.$http({
            url: this.$http.adornUrl(
              `/eqEquipment/${!this.dataForm.id ? 'save' : 'update'}`
            ),
            method: 'post',
            data: this.dataForm
          }).then(data => {
            if (data && data.code === 0) {
              this.$message.success('保存成功')
              this.visible = false
              this.$emit('refreshDataList')
            }
            this.loading = false
          })
        }
      })
    },
    handleChange(value) {},
    //取消
    cancel() {
      this.$confirm('确认取消?', this.id ? '编辑设备' : '新增设备', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.visible = false
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消退出'
          })
        })
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
