<template>
  <div class="sy-content">
    <el-row>
      <el-col>
        <!-- 操作按钮 -->
        <el-row class="czBtns">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增
            </el-button>
          </el-col>
        </el-row>
        <!-- 表格数据信息 -->
        <el-table
          ref="driverConfigTable"
          v-loading="loading"
          :data="driverConfigList"
          stripe
          border
          header-row-class-name="headBackground"
        >
          <el-table-column
            v-if="false"
            key="id"
            label="ID"
            align="center"
            prop="id"
          />
          <el-table-column
            v-if="false"
            key="clsId"
            label="clsId"
            align="center"
            prop="clsId"
          />
          <el-table-column
            key="driverName"
            label="驱动名称"
            align="center"
            prop="driverName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="操作"
            align="center"
            width="250"
            class-name="small-padding fixed-width"
          >
            <template v-if="scope.row.userId !== 1" slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="driverForm" :model="driverForm" :rules="rules" label-width="140px">
        <el-row style="margin-bottom: 5px">
          <el-col>
            <el-form-item label="驱动：" prop="driver">
              <el-select
                v-if="driverForm.id"
                v-model="driverForm.driver"
                placeholder="请选择驱动"
                style="width: 300px"
                disabled
              >
                <el-option
                  v-for="dict in driverList"
                  :key="dict.value"
                  :label="dict.name"
                  :value="dict"
                />
              </el-select>
              <el-select
                v-else
                v-model="driverForm.driver"
                placeholder="请选择驱动"
                style="width: 300px"
              >
                <el-option
                  v-for="dict in driverList"
                  :key="dict.value"
                  :label="dict.name"
                  :value="dict"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据项名称：" prop="items" class="cy-item-name">
              <el-tag
                v-for="tag in dynamicTags"
                :key="tag.itemName"
                closable
                :disable-transitions="false"
                @close="handleTagClose(tag)"
              >
                {{ tag.itemName }}
              </el-tag>
              <el-input
                v-if="inputVisible"
                ref="saveTagInput"
                v-model="inputValue"
                class="input-new-tag"
                size="small"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm"
              />
              <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-top: 20px;">
        <el-button
          type="primary"
          size="mini"
          @click="submitForm"
        >确定
        </el-button>
        <el-button size="mini" @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addDataSourceDriver, delDataSourceDriver,
  getAllDataSourceDriver,
  getDriverItemById,
  getOpcDaDriverEnum,
  updateDataSourceDriver
} from '@/api/system/driver'

export default {
  name: 'Index',
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 驱动配置数据
      driverConfigList: [],
      // 驱动数据
      driverList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      inputVisible: false,
      inputValue: '',
      dynamicTags: [],
      driverForm: {
        id: null,
        driver: null,
        items: null
      },
      // 表单验证
      rules: {
        driver: [
          {
            required: true,
            message: '驱动不能为空',
            pattern: '[^ \x22]+',
            trigger: 'change'
          }
        ],
        items: [
          {
            required: true,
            message: '数据项不能为空',
            pattern: '[^ \x22]+',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getDriverConfigList()
  },
  methods: {
    /** 查询所有数据源配置信息 */
    getDriverConfigList() {
      this.loading = true
      getAllDataSourceDriver().then((response) => {
        const data = response.data
        this.driverConfigList = data
        this.loading = false
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('您确定要删除该驱动配置吗？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'btn_custom_cancel',
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        delDataSourceDriver(row.id).then((res) => {
          if (res.code === 200) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getDriverConfigList()
          }
        })
      }).catch(() => {
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getOpcDaDriverEnum((res) => {
        getDriverItemById(row.id).then((res) => {
          this.open = true
          this.title = '驱动数据项属性配置'
          const data = res.data
          this.driverForm = {
            id: data.id,
            driver: {
              'name': data.driverName,
              'value': data.clsId
            }
          }
          this.dynamicTags = data.driverBasicItemList
        })
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '驱动数据项属性配置'
      this.getOpcDaDriverEnum()
    },
    /** 表单提交 */
    submitForm() {
      if (!this.driverForm.driver) {
        this.$message({
          message: '请选择驱动',
          type: 'warning'
        })
        return
      }
      if (!this.dynamicTags || this.dynamicTags.length === 0) {
        this.$message({
          message: '请添加数据项',
          type: 'warning'
        })
        return
      }
      const params = {
        driverName: this.driverForm.driver.name,
        clsId: this.driverForm.driver.value,
        driverBasicItemList: []
      }
      this.dynamicTags.forEach((tag) => {
        params.driverBasicItemList.push({
          id: tag.id,
          driverId: tag.driverId,
          itemName: tag.itemName
        })
      })
      if (this.driverForm.id) {
        params.id = this.driverForm.id
        updateDataSourceDriver(params).then((response) => {
          if (response.code === 200) {
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.getDriverConfigList()
            this.cancel()
          }
        })
        return
      }
      addDataSourceDriver(params).then((response) => {
        if (response.code === 200) {
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.getDriverConfigList()
          this.cancel()
        }
      })
    },
    /** 查询所有驱动信息 */
    getOpcDaDriverEnum(callback) {
      getOpcDaDriverEnum().then((res) => {
        const data = res.data
        const drivers = []
        for (const key in data) {
          drivers.push({
            'name': key,
            'value': data[key]
          })
        }
        this.driverList = drivers
        if (callback) callback(data)
      })
    },
    /** 移除数据项 */
    handleTagClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },
    /** 显示数据项输入框 */
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    /** 数据项输入完成事件 */
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        const isInArray = this.dynamicTags.some(item => item.itemName === inputValue)
        if (!isInArray) {
          this.dynamicTags.push({
            itemName: inputValue
          })
        }
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    /** 表单重置 */
    reset() {
      this.dynamicTags = []
      this.driverForm = {
        id: null,
        driver: null,
        items: null
      }
      if (this.$refs['driverForm']) {
        this.$refs['driverForm'].resetFields()
      }
    },
    /** 表单重置 */
    cancel() {
      this.open = false
      this.reset()
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.cy-item-name {
  .el-form-item__content {
    position: absolute;
    height: 110px;
    overflow: auto;
  }
}
</style>
