<template>
    <div class="flex-col">
        <h3 style="font-weight: 400;color: #1f2f3d;    margin: 0px 0 20px;">
            <a-icon type="info-circle" class="warnIcons" theme="filled" />
            关联关系
        </h3>
        <div style="margin-bottom: 10px">
            <a-button type="primary" @click="addEnt" style="margin-right: 10px">新增关联实体</a-button>
            <a-button type="primary" @click="selectEnt" style="margin-right: 10px">选择关联实体</a-button>
            <a-button type="primary" @click="dels">删除</a-button>
        </div>
        <a-table :pagination="false" :loading="loading" :columns="columns" :data-source="data" :row-selection="{ onChange: onTableSelect }">
            <span slot="entName" slot-scope="text, record">
                <a @click="openNewPage(record)">{{text}}</a>
            </span>
            <span slot="action" slot-scope="text, record">
                <a @click="edit(record)" style="margin-right: 5px">编辑</a>
                <a-popconfirm title="此操作无法恢复，请确认是否删除？"
                              @confirm="() => del(record)">
                  <a href="javascript:;" class="spanMarginl">删除</a>
                </a-popconfirm>
            </span>
        </a-table>
        <a-row style="margin-top: 30px;">
            <a-col>
                <a-pagination
                        v-model="pagination.current"
                        :total="pagination.total"
                        :pageSize="pagination.pageSize"
                        @change="onChangePagination"/>
            </a-col>
        </a-row>
    </div>
</template>

<script>
  import { getRelationAttr } from '@/api/graph/entity'
  import { addRelBatch, deleteEntityRelation } from '@/api/graph/relationClass'

  export default {
    name: "relationClsAttrEditor",
    props: ['entId', 'relClsId', 'direction', 'isModel', 'clsId', 'otherVID'],
    data() {
      return {
        data: [],
        columns: [
          {
            title: '实体名称',
            dataIndex: 'entName',
            key: 'entName',
            scopedSlots: {customRender: 'entName'},
          },
          {
            title: '操作',
            key: 'action',
            scopedSlots: {customRender: 'action'},
          },
        ],
        loading: false,
        selectRows: [],
        columnsIdCache: [],
        columnsCache: [],
        pagination: {
          pageSize: 9,
          total: 100,
          current: 1
        }
      }
    },
    mounted() {
      this.getAttr()
    },
    methods: {
      // 获取属性
      getAttr() {
        const vm = this
        this.loading = true
        getRelationAttr(this.entId, this.relClsId, this.direction, this.isModel, this.pagination.current, this.pagination.pageSize).then(res => {
          const attrClsNameList = {}
          this.pagination.total = res.total
          // 组装表格columns
          res.headers.reverse().forEach(item => {
            if (vm.columnsIdCache.indexOf(item.attrClsId) === -1) {
              attrClsNameList[item.attrClsId] = item.attrClsName
              vm.columnsIdCache.push(item.attrClsId)
              vm.columnsCache.push({
                attrClsId: item.attrClsId,
                attrClsName: item.attrClsName
              })
              vm.columns.splice(1, 0, {
                dataIndex: item.attrClsId,
                key: item.attrClsId,
                title: item.attrClsName
              })
            }
          })
          res.data.forEach(item => {
            item.key = item.entID
            // 新建的关系类没有属性，给一个空的属性列表，方便后面操作
            item.attrList ? item.attrList.forEach(attr => {
              item[attr.attrClsId] = attr.attrValue
              item[attr.attrClsId + '_name'] = attrClsNameList[attr.attrClsId]
            }) : item.attrList = []
          })
          vm.data = res.data
          vm.loading = false
        })
      },
      openNewPage(record) {
        const params = this.$route.params
        const query = this.$route.query
        const location = window.location
        const url = location.origin + location.pathname + '#/model/' + params.classId + '/entity_model/' + record.entID + '?page=' + query.page + '&clsName=' + query.clsName + '&entName=' + record.entName + '&isModel=' + query.isModel
        window.open(url)
      },
      // 表格选中行后的回调
      onTableSelect(selectedRowKeys, selectedRows) {
        this.selectRows = selectedRows
      },
      // 分页变更
      onChangePagination(current) {
        this.pagination.current = current
        this.getAttr()
      },
      // 新增实体
      addEnt() {
        this.$open(
          'addEntityModal',
          {
            title: '新增实体',
            paramsId: this.otherVID, // 实体类id
            isModel: this.isModel
          },
          function (data) {
            if (data) {
              this.addRelEnt(data)
            }
          }
        )
      },
      // 新增关系类实体
      addRelEnt(data) {
        let entityRelations = []
        let startEntId;
        let endEntId;
        if (this.direction === 'START') {
          startEntId = this.entId
          endEntId = data
          
        } else {
          startEntId = data
          endEntId = this.entId
        }
        let entityRelation = {
          startEntId,
          endEntId,
          isModel: this.isModel,
          relClsId: this.relClsId
        }
        entityRelations.push(entityRelation)
        addRelBatch(entityRelations).then(res => {
          if (res) {
            this.getAttr()
          }
        })
      },
      // 选择实体
      selectEnt() {
        this.$open(
          'addRelBatchModal',
          {
            relClsId: this.relClsId, // 实体类id
            isModel: this.isModel,
            direction: this.direction,
            entId: this.entId
          },
          function (data) {
            if (data) {
              this.getAttr()
            }
          }
        )
      },
      // 编辑
      edit(record) {
        // 如果新增实体，没有属性类
        if (record.attrList.length === 0) {
          this.columnsCache.forEach(cls => {
            record.attrList.push({
              attrClsId: cls.attrClsId,
              attrValue: ''
            })
            record[cls.attrClsId] = ''
            record[cls.attrClsId + '_name'] = cls.attrClsName
          })
        }
        this.columnsCache.forEach(cls => {
          let hasCls = false;
          record.attrList.forEach(attr => {
            if (attr.attrClsId === cls.attrClsId) hasCls = true
          })
          if (!hasCls) {
            record.attrList.push({
              attrClsId: cls.attrClsId,
              attrValue: ''
            })
            record[cls.attrClsId] = ''
            record[cls.attrClsId + '_name'] = cls.attrClsName
          }
        })
        this.$open(
          'editTemplateRelAttrbatchModal',
          {
            record: record, // 实体类id
            isModel: this.isModel
          },
          function (data) {
            if (data) {
              this.getAttr()
            }
          }
        )
      },
      // 批量删除
      dels() {
        const ids = []
        this.selectRows.forEach(row => {
          ids.push(row.relId)
        })
        deleteEntityRelation(ids, this.isModel).then(res => {
          if (res) {
            this.$notification["success"]({
              message: "删除成功"
            });
            this.getAttr()
          }
        })
      },
      // 表格删除
      del(record) {
        const relIds = [record.relId]
        deleteEntityRelation(relIds, this.isModel).then(res => {
          if (res) {
            this.$notification["success"]({
              message: "删除成功"
            });
            this.getAttr()
          }
        })
      }
    }
  }
</script>

<style scoped>

</style>