<template>
  <div class="view-table-content">
    <div style="width: 100%">
      <div class="view-dataType-title">
        <div class="view-dataType-title-btn">
          <el-button type="success" @click="openDialog()">新增</el-button>
          <el-button type="warning" @click="reset()">重置</el-button>
        </div>
        <div class="view-dataType-title-search">
          <el-input placeholder="请输入实体名称" v-model="keyWordData" class="input1">
            <el-button slot="append" icon="el-icon-search" @click="searchClick"></el-button>
          </el-input>
        </div>
      </div>
      <div class="view-dataType-table">
        <LTable ref="table" @selection-change="selection" :defaultFetch="false" :fetch="fetch" :columns="columns" :dataSource="tableData" :options="options" :pagination="tableRequset"></LTable>
      </div>
      <!-- 添加或修改模型信息对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" :before-close="handleClose">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="主体类型" prop="subjectCategory">
            <el-input :disabled="dialogTitle === '编辑'" v-model="form.subjectCategory" placeholder="请输入实体名称" />
            <!-- <el-select v-model="form.subjectCategory" placeholder="请选择主体类型">
              <el-option v-for="(item, index) in subjectList" :key="index" :label="item.name" :value="item.name" />
            </el-select> -->
          </el-form-item>
          <el-form-item label="主体名称" prop="subjectName">
            <el-input v-model="form.subjectName" placeholder="请输入实体名称" :disabled="dialogTitle === '编辑'" />
            <!-- <el-select v-model="form.subjectName" placeholder="请选择实体类型">
              <el-option v-for="(item, index) in subjectList" :key="index" :label="item.name" :value="item.name" />
            </el-select> -->
          </el-form-item>

          <el-form-item label="客体名称" prop="objectName">
            <el-input :disabled="dialogTitle === '编辑'" v-model="form.objectName" placeholder="请输入实体名称" />
          </el-form-item>
          <el-form-item label="客体类型" prop="objectCategory">
            <el-input :disabled="dialogTitle === '编辑'" v-model="form.objectCategory" placeholder="请输入实体类型" />
          </el-form-item>
          <el-form-item label="关系" prop="relationName">
            <el-select v-model="form.relationName" placeholder="请选择实体类型">
              <el-option v-for="(item, index) in relationList" :key="index" :label="item.name" :value="item.name" />
            </el-select>
            <!-- <el-input v-model="form.relationName" placeholder="请输入实体名称" /> -->
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getERList, getAllRelationClass, addRelation, updateRelation, deleteRelation } from '@/api/als/ERManage'
import { getEntityList } from '@/api/als/entityManage'
import { deepClone, debounce } from '@/utils/index'

export default {
  name: 'ERManage',
  components: {},
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogVisible: false,
      keyWordData: '',
      searchValue: '',
      columns: [
        {
          prop: 'subjectName',
          label: '主体名称'
        },
        {
          prop: 'subjectCategory',
          label: '主体类型'
        },
        {
          prop: 'objectName',
          label: '客体名称'
        },
        {
          prop: 'objectCategory',
          label: '客体类型'
        },
        {
          prop: 'relationName',
          label: '关系'
        },
        {
          button: true,
          label: '操作',
          width: '240px',
          group: [
            {
              name: '编辑',
              type: 'text',
              round: false,
              plain: false,
              onClick: (row, index, scope) => {
                this.handUpdate(row)
              }
            },
            {
              name: '删除',
              type: 'text',
              round: false,
              plain: false,
              onClick: (row, index, scope) => {
                this.remove([row])
              }
            }
          ]
        }
      ],
      options: {
        stripe: true, // 斑马纹
        mutiSelect: true, // 多选框
        index: false, // 显示序号， 多选则 mutiSelect
        loading: false, // 表格动画
        initTable: false, // 是否一挂载就加载数据
        border: true,
        height: 'calc(100vh - 300px)'
      },
      tableCheckItems: [],
      tableData: [],
      tableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 20,
        searchValue: ''
      },
      form: {
        subjectId: '',
        subjectName: '',
        subjectCategory: '',
        objectId: '',
        objectName: '',
        objectCategory: '',
        relationId: '',
        relationName: ''
      },
      debounceFn: debounce(this.fetch, 500),
      relationList: [],
      loading: null
    }
  },
  watch: {
    keyWord() {
      this.tableRequset.pageIndex = 1
      this.debounceFn()
    }
  },
  mounted() {
    this.getInit()
  },
  methods: {
    async getInit() {
      this.getRelationAPI()
      this.getAllRelationClassAPI()
      // try {
      //   if (this.$refs.table) this.$refs.table.clearSelection()
      //   const {
      //     data: { dataList }
      //   } = await getEntityList()
      //   this.tableData = dataList
      // } catch (error) {

      // }
    },

    async deleteRelationAPI(row) {
      try {
        const deleteData = {
          node_id_heard: row.subjectId,
          node_id_last: row.objectId,
          relation_name: row.relationName
        }
        const { code } = await deleteRelation(deleteData)
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.getRelationAPI()
          this.handleClose()
        }
      } catch (error) {}
    },
    reset() {
      this.getRelationAPI()
      this.keyWordData = ''
    },
    async getRelationAPI(params) {
      try {
        if (this.$refs.table) this.$refs.table.clearSelection()
        const { pageSize, pageIndex } = this.tableRequset
        this.loading = this.$loading({
          lock: true,
          text: '正在获取知识图谱实体关系数据，请稍候...',
          spinner: 'el-icon-loading'
        })
        const {
          data: { dataList, total }
        } = await getERList({ pageSize, pageNum: pageIndex, ...params })
        this.tableData = dataList
        this.tableRequset.total = total
        this.loading.close()
      } catch (error) {}
    },

    handleERData(data) {
      const tableData = []
      data.forEach((item) => {
        let subData = {},
          obData = {},
          reData = {}
        for (const key in item) {
          if (key === 'subject') {
            subData.subjectId = item.subject.id
            subData.subjectName = item.subject.name
            subData.subjectCategory = item.subject.category
          } else if (key === 'object') {
            obData.objectId = item.object.id
            obData.objectName = item.object.name
            obData.objectCategory = item.object.category
          } else if (key === 'relation') {
            reData.relationId = item.relation.id
            reData.relationName = item.relation.name
          }
        }
        tableData.push({ ...subData, ...obData, ...reData })
      })
      return tableData
    },

    async getAllRelationClassAPI(params) {
      try {
        const {
          data: { dataList }
        } = await getAllRelationClass()
        this.relationList = dataList
        this.loading.close()
      } catch (error) {}
    },

    fetch() {
      this.getRelationAPI()
    },

    async searchClick() {
      try {
        if (this.$refs.table) this.$refs.table.clearSelection()
        const {
          data: { dataList, total }
        } = await checkRelation({ node_name: this.keyWordData })
        this.tableData = dataList
        this.tableRequset.total = total
      } catch (error) {}
    },

    async addRelationAPI() {
      try {
        const addData = {
          node_name: this.form.name,
          node_label: this.form.category
        }
        const { code } = await addRelation(addData)
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleClose()
          this.getRelationAPI()
        }
      } catch (error) {}
    },

    async updateRelationAPI() {
      try {
        const updateData = {
          head_node_id: this.form.subjectId,
          tail_node_id: this.form.objectId,
          new_relation_name: this.form.relationName
        }
        console.log('updateData', updateData)
        const { code } = await updateRelation(updateData)
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleClose()
          this.getRelationAPI()
        }
      } catch (error) {}
    },

    openDialog() {
      this.dialogTitle = '新增'
      this.dialogVisible = true
    },

    handleClose() {
      this.dialogVisible = false
      this.form = {
        subjectId: '',
        subjectName: '',
        subjectCategory: '',
        objectId: '',
        objectName: '',
        objectCategory: '',
        relationId: '',
        relationName: ''
      }
    },

    handUpdate(row) {
      this.dialogTitle = '编辑'
      this.form = deepClone(row)
      this.dialogVisible = true
    },

    submit() {
      switch (this.dialogTitle) {
        case '编辑':
          this.updateRelationAPI()
          break
        case '新增':
          this.addRelationAPI()
          break
      }
    },

    selection(val) {
      this.tableCheckItems = val
    },

    remove(row) {
      this.$confirm('是否删除该数据', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // this.deleteRelationAPI(row.map((e) => e.id))
          this.deleteRelationAPI(row[0])
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../index.scss';
</style>
