<template>
  <ai-detail class="dmAdd">
    <ai-title slot="title" :title="pageTitle" isShowBottomBorder isShowBack @back="back"/>
    <template #content>
      <el-form size="small" :model="form" label-width="60px" :rules="rules" ref="DataModelForm">
        <ai-card title="主表实体">
          <el-form-item label="主表" prop="tableName">
            <ai-select v-model="form.tableName" :selectList="entries" placeholder="指定主表实体模型,更换主表会清空设计模型" filterable @select="initMainModel" :disabled="isEdit"/>
          </el-form-item>
        </ai-card>
        <ai-card title="设计模型" panel>
          <el-form-item prop="model" label-width="0" class="diagram">
            <div ref="DataModel" class="dataModel"/>
            <div class="dndPanel pad-8">
              <div class="iconfont iconxinxiguanli pad-h8" v-text="`表实体`" @mousedown="handleAddModel"/>
            </div>
          </el-form-item>
        </ai-card>
      </el-form>
      <el-drawer :visible.sync="drawer" @close="current={}">
        <div slot="title" v-text="`设置${current.name||'实体对象'}`"/>
        <el-form class="pad-h16" :model="current" ref="ModelSettingForm" size="small" label-position="top">
          <template v-if="current.type=='model'">
            <el-form-item label="实体名称">
              <ai-select v-model="current.id" :selectList="entries" placeholder="请选择实体对象" filterable @select="changeModel"/>
            </el-form-item>
            <el-form-item label="实体属性">
              <ai-table :tableData="current.props" :colConfigs="currentCols" :is-show-pagination="false" tableSize="small"/>
            </el-form-item>
          </template>
          <template v-else-if="current.type=='polyline'">

          </template>
        </el-form>
        <div class="footBar">
          <el-button @click="drawer=false">取消</el-button>
          <el-button type="primary" @click="handleSaveModel">保存</el-button>
        </div>
      </el-drawer>
    </template>
    <template #footer>
      <el-button @click="back">返回</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </template>
  </ai-detail>
</template>

<script>
import {mapActions} from "vuex";
import {LogicFlow} from "@logicflow/core"
import "@logicflow/core/dist/style/index.css"
import {ModelElement} from "./element";

export default {
  name: "dmAdd",
  props: {
    instance: Function,
    dict: Object
  },
  data() {
    return {
      entries: [],
      form: {},
      rules: {
        tableName: {required: true, message: "请选择主表模型"},
      },
      diagram: null,
      drawer: false,
      current: {},
      currentCols: [
        {label: "属性", prop: "columnName"},
        {label: "属性名", prop: "columnComment"},
      ]
    }
  },
  computed: {
    isEdit: v => !!v.$route.tableName,
    pageTitle: v => v.isEdit ? "编辑数据关联模型" : "新增数据关联模型",
  },
  methods: {
    ...mapActions(['closePage']),
    back() {
      this.closePage()
      this.$router.push({})
    },
    getDetail() {
      const {tableName} = this.$route.query
      tableName && this.instance.post("/relation/list", null, {params: {tableName}}).then(res => {
        if (res?.data) {
          this.form = res.data
        }
      })
    },
    submit() {
      const jsonData = this.diagram.getGraphData()
      this.form.relationNodes = jsonData.edges.map(e => e.properties)
      this.$refs.DataModelForm.validate()
      .then(() => this.instance.post("/relation/setting", {...this.form, jsonData: JSON.stringify(jsonData)}))
      .then(res => {
        if (res?.code == 200) {
          this.$message.success("提交成功")
          this.back()
        }
      })
    },
    initLf() {
      this.diagram = new LogicFlow({
        container: this.$refs.DataModel,
        plugins: [ModelElement],
        edgeType: 'bezier',
        animation: true,
        grid: true,
        keyboard: {
          enabled: true
        },
        style: {
          bezier: {
            stroke: "#666",
            strokeWidth: 1
          }
        }
      })
      this.diagram.on('node:click', this.onNodeClick)
      this.diagram.on('node:dnd-add', this.onNodeClick)
      this.diagram.on('anchor:dragstart', () => {
        this.diagram.graphModel.nodes.map(e => {
          if (e.type == 'model') {
            e.setProperties({isConnection: true})
          }
        })
      })
      this.diagram.on('anchor:drop', ({edgeModel}) => {
        const {sourceAnchorId, targetAnchorId, targetNodeId} = edgeModel
        edgeModel.setProperties({joinField: targetAnchorId.replace(`${targetNodeId}_`, ''), mainField: sourceAnchorId, tableName: targetNodeId})
        this.diagram.graphModel.nodes.map(e => {
          if (e.type == 'model') {
            e.setProperties({isConnection: false})
          }
        })
      })
      this.diagram.render()
    },
    handleAddModel() {
      this.diagram.dnd.startDrag({type: "model"})
    },
    onNodeClick({data}) {
      if (data.id != this.form.tableName) {
        const {id: oldId, type} = data
        this.current = this.$copy({props: [], ...data.properties, oldId, type})
        this.drawer = true
      }
    },
    handleSaveModel() {
      let {id, oldId, props} = this.current
      props = props?.filter(e => !!e.prop) || []
      this.diagram.changeNodeId(oldId, id)
      this.diagram.setProperties(id, this.current)
      this.drawer = false
    },
    initMainModel(v) {
      this.diagram.clearData()
      if (!!v?.id) {
        this.getTableFields(v.id).then(list => {
          this.diagram.addNode({
            type: 'main',
            x: 200,
            y: 60,
            id: v.id,
            properties: {id: v.id, props: list}
          })
          this.diagram.focusOn({id: v.id})
        })

      }
    },
    changeModel(v) {
      if (!!v?.id) {
        this.current.name = v.id
        this.getTableFields(v.id).then((list = []) => this.current.props = list)
      }
    },
    getEntries() {
      this.instance.get("/relation/table").then(res => {
        if (res?.data) {
          this.entries = res.data.map(e => ({...e, id: e.name, label: [e.entityName, e.des].filter(Boolean).join(" | ") || e.name}))
        }
      })
    },
    getTableFields(tableName) {
      return this.instance.get(`/relation/fields`, {params: {tableName}}).then(res => {
        if (res?.data) {
          return res.data
        }
      })
    }
  },
  created() {
    this.getDetail()
    this.getEntries()
  },
  mounted() {
    this.initLf()
  }
}
</script>

<style lang="scss" scoped>
.dmAdd {
  .dataModel {
    height: 400px;
  }

  .diagram {
    position: relative;

    .dndPanel {
      position: absolute;
      top: 0;
      left: 0;
      background-color: #fff;
      border: 1px solid #eee;

      .iconfont {
        font-size: 14px;
        display: flex;
        align-items: center;
        flex-direction: column;
        cursor: pointer;
        user-select: none;

        &:before {
          font-size: 40px;
        }

        &:hover {
          color: #26f;
        }
      }

    }

    :deep(.modelElement) {
      border-radius: 4px;
      font-size: 12px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, .3);
      background-color: #fff;
      overflow: hidden;
      min-width: 200px;

      & > b {
        display: block;
        width: 100%;
        text-align: center;
        line-height: 28px;
        font-size: 14px;
        background-color: #f5f5f5;

        &:before {
          content: " ";
          display: block;
          width: 100%;
          height: 4px;
          background-color: #82b366;
        }
      }

      &.main > b:before {
        background-color: #26f;
      }

      .content {
        min-height: 40px;
        line-height: 20px;
      }
    }

    :deep(.custom-anchor) {
      stroke: #999;
      stroke-width: 1;
      fill: #d9d9d9;
      cursor: crosshair;

      &:hover {
        fill: #26f;
        stroke: #26f;
      }

      &.incomming-anchor {
        stroke: #d79b00;
      }

      & .outgoing-anchor {
        stroke: #82b366;
      }
    }
  }

  :deep(.el-drawer) {
    .el-drawer__header {
      padding: 16px;
      border-bottom: 1px solid #ddd;
      margin-bottom: 16px;
    }

    .el-drawer__body {
      position: relative;

      .footBar {
        position: absolute;
        bottom: 0;
        width: 100%;
      }

      .el-form-item {
        margin-bottom: 0;

        .el-form-item__label {
          width: 100%;
          font-weight: bold;
          color: #333;
          padding-bottom: 0;
        }
      }
    }
  }

  .footBar {
    padding: 16px 20px;
    box-sizing: border-box;
    background: #F3F6F9;
    display: flex;
    align-items: center;
    justify-content: center;

    .el-button {
      width: 92px !important;
    }
  }
}
</style>
