<template>
  <a-modal
    title="新建一个关系类"
    :visible="show"
    :maskClosable="false"
    @ok="handleOk"
    @cancel="handleClose"
  >
    <h4 class="title">{{entClsName}}</h4>
    <div style="margin-bottom: 20px;">
      <a-radio-group @change="onChangeOrigin" v-model="Originvalue" disabled>
        <a-radio :value="3">作为起点</a-radio>
        <a-radio :value="4">作为终点</a-radio>
      </a-radio-group>
    </div>
    <h4 class="title">选择或新建关系</h4>
    
     <a-row :gutter="10" >
        <a-col :span="4">
          <h4 class="title" style="margin-top:.6em;">背景颜色</h4>
        </a-col>
        <a-col :span="15">
            <a-form :form="form">
                <a-form-item>
                    <a-color-picker @fromChild="getColor"  v-decorator="formRules.backGroundColor" />    
                </a-form-item>
            </a-form>
       </a-col>
    </a-row>
   
    <div style="margin-bottom: 20px;">
      <a-radio-group @change="onChange" v-model="value">
        <a-radio :value="1">复制已有关系</a-radio>
        <a-radio :value="2">新建关系</a-radio>
      </a-radio-group>
    </div>
    <div v-if="value==1" style="margin-bottom: 20px;">
      <a-row :gutter="10">
        <a-col :span="12">
          <a-button @click="getRelationCls">
            {{selectedRelCls ? selectedRelCls : '选择一个关系类名称'}}
          </a-button>
        </a-col>
        <a-col :span="12">
          <!-- <a-select
                  showSearch
                  placeholder="选择一个关系类"
                  style="width:200px;"
                  @change="handleSelectRelationClass"
          >
            <a-select-option
                    v-for="item in filterRelationList"
                    :value="item.relClsID"
                    :key="item.relClsID"
            >
              <a-popover placement="left">
                <template slot="content">
                  <div>起点：{{item.startName}}</div>
                  <div>关系类：{{item.relClsName}}</div>
                  <div>终点：{{item.endName}}</div>
                  <div v-for="(p,i) in attrList" :key="i">属性:{{p.attrClsName}}</div>
                </template>
                <span
                        @mouseenter="enter(item)"
                        @mouseleave="leave()"
                >
                  {{item.startName}}->{{item.relClsName}}->{{item.endName}}</span>
              </a-popover>
            </a-select-option>
          </a-select> -->
        </a-col>
      </a-row>
    </div>
    <div v-if="value==2">
      <a-form :form="form">
        <a-form-item>
          <a-input v-decorator="formRules.entityClass" placeholder="请输入关系类名" />
        </a-form-item>
      </a-form>
    </div>
    <h4 class="title">{{Originvalue===3 ? '选择终点关系类' : '选择起点关系类'}}</h4>
    <div style="max-height: 420px; overflow: auto;">
      <!--<class-tree @nodeSelected="entityClassNodeSelected" :editable="false"></class-tree>-->
      <z-tree :editable="false" @nodeSelected="entityClassNodeSelected"></z-tree>
    </div>
  </a-modal>
</template>

<script>
import AColorPicker  from '@/components/knowledge/colorPicker';
import ClassTree from "@/views/knowledge/graphClass/entityClassTree.vue";
import zTree from "@/views/knowledge/graphClass/entityClassZtree.vue";
import { getRelationAttr, getAllRelationClassListByName, addRelationClass } from "@/api/graph/relationClass"

const formRules = {
  // 所有验证规则
  entityClass: [
    // 用作标识，我们统一写成和表单提交字段一样
    "entityClass", // 表单提交的字段
    {
      rules: [{ required: true, message: "此选项必填", whitespace: true }]
    }
  ]
  // relationClass: [
  //   relationClass, // 表单提交的字段
  //   {
  //     rules: [{required: false, message: '此选项必填', whitespace: true}]
  //   }
  // ]
};
export default {
  components: {
    AColorPicker,
    zTree,
    ClassTree,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes
    }
  },
  name: "create-relation-class-modal",
  props: ["pramsId", "entClsName", "entClsType"],
  data() {
    return {
      color:'',
      show: true,
      form: this.$form.createForm(this),
      formRules,
      value: 1,
      Originvalue: 3,
      filterRelationList: [], // 已有关系列表
      EntityClassNode: {}, // 实体类节点信息
      selectRelationValue: "",
      timer: null, // 延时器
      attrMap: {},
      attrList: [], // 属性list
      selectedRelCls: ''
    };
  },
  created() {
    // 判断是起点还是终点
    if (this.entClsType === "START") {
      this.Originvalue = 3; // 起点
    } else {
      this.Originvalue = 4; // 终点
    }
  },
  destroyed() {
  },
  methods: {
    getColor (color) {
      this.color = color;
    },
    enter(item) {
      const vm = this
      if (vm.attrMap.hasOwnProperty(item.relClsID)) {  // 判断map中是否存在
        vm.attrList = vm.attrMap[item.relClsID];
        clearTimeout(vm.timer);
      } else {
        vm.timer = setTimeout(() => {
          getRelationAttr(item.relClsID).then(res => {
            vm.attrMap[item.relClsID] = res; // 缓存
            vm.attrList = res;
          });
        }, 10);
      }
    },
    leave() {
      clearTimeout(this.timer);
    },
    /**
     * // 传出来的实体类节点信息
     * @param node
     */
    entityClassNodeSelected(node) {
      this.EntityClassNode = node;
    },
    /**
     * 选中的已有关系
     * @param value
     */
    handleChange(name) {
      getAllRelationClassListByName(name,false).then(data => {
        //参数为空,获取所有的列表
        this.filterRelationList = data.records;
      });
    },
    handleSelectRelationClass(id) {
      this.selectRelationValue = id;
    },
    getRelationCls() {
      this.$open('getRelationClsListModal', {}, function (data) {
        if (data) {
          this.relClsName = data
          this.selectedRelCls = data
          getAllRelationClassListByName(data,false).then(data => {
            //参数为空,获取所有的列表
            this.filterRelationList = data.rows;
          });
        }
      })
    },
    onChange(e) {
    },
    // 选择起点或终点
    onChangeOrigin(e) {
    },
    async getFormData() {
      var result = await this.$formValidateFields("form"); //form的字符串
      // 在这里对form返回数据进行处理
      return result;
    },
    async handleOk(e) {
      let result = await this.getFormData(); // this是当前组件的this,  'form'此表单的名称，一定要是字符串
      const endID = this.EntityClassNode && this.EntityClassNode.entClsID;
      const relClsID = this.selectRelationValue;
      let entClsType = "START";
      if (!endID) {
        this.$message.error("请选择要建立关系的实体类");
        return;
      }
      const data = {
        startID: this.pramsId,
        endID: endID,
        backGroundColor:this.color,
        relClsMemo:this.relClsMemo,
        relClsName:this.relClsName,
     
       
      };
      if (this.Originvalue == 4) {
        // 传进来的实体类作为终点
        data["startID"] = endID;
        data["endID"] = this.pramsId;
        entClsType = "ENT";
      }
      if (this.value == 1) {
        // 已有关系属性
        data["relClsID"] = relClsID;
      }
      if (this.value == 2) {
        // 新建关系
        data["relClsName"] = result.entityClass;
        const uniqueMatchList = this.$checkSpecialChar(result.entityClass)
        if (uniqueMatchList.length > 0) {
          this.$message.error(`关系类名称不能包含特殊字符【${uniqueMatchList.join('、')}】！`)
          return false
        }
      }
      addRelationClass(data).then(resp => {
        let data = resp.data
        if (data !== false) {
          this.$trigger("relationClass:nodeCreated", data);
          this.$close({
            id: this.pramsId,
            entClsType: entClsType
          });
        }
      });
    },
    handleClose(e) {
      this.$close(false);
    }
  }
};
</script>

<style scoped>
  .ant-row {
    margin-bottom: 2px;
 }
</style>
