<template>
  <div id="orgcard" style="height:100%">
    <Card style="height:100%">
      <Alert type="error">
        <template slot="desc">
          <Icon type="ios-alert-outline"/>双击编辑,单击选择
          <br>
          &nbsp;&nbsp; &nbsp;&nbsp;当前节点：
          {{currentData?currentData.title:"请选择操作节点"}}
        </template>
      </Alert>
      <Tree v-if="!isupdate" :data="treedata" :render="renderContent" class="ptree"></Tree>
      <Drawer
        ref="eddrawer"
        placement="right"
        :closable="false"
        :mask-closable="false"
        v-model="showedform"
        width="70"
        @on-visible-change="ondrawvisable"
      >
        <NodeForm ref="nodeform" :fminfo="nodeinfo" @controlctl="controlctl">
          <template v-slot:default="slotProps">
            <Button type="text" @click="doexec('ok',slotProps.fm)">保存</Button>
            <Button type="text" @click="doexec('cancel',slotProps.fm)">取消</Button>
          </template>
        </NodeForm>
      </Drawer>
    </Card>
  </div>
</template>
  <script>
import { getApp, saveAuths, findAuthsByRoles } from "@/api/meta";
import NodeForm from "./forms.vue";
import config from "@/config";

export default {
  name: "jsoneditor",
  props: {
    initData: {
      type: Function,
      default() {
        return cbk => {
          cbk(this.originalRoot);
        };
      }
    },
    metainfo: {
      type: Object
    }
  },
  components: {
    NodeForm
  },
  data() {
    return {
      isupdate: false,
      rootNode: null,
      currentData: null,
      currentNode: null,
      code: "root",
      treedata: [],
      originalMetaInfo: [
        {
          title: "基本信息",
          key: "baseinfo",
          cols: 1,
          ctls: [
            {
              type: "input",
              label: "序号",
              prop: "seq",
              placeHolder: "请输入序号",
              style: { width: "165px" },
              rules: [{ required: true, message: "  ", trigger: "blur" }]
            },
            {
              type: "input",
              label: "编码",
              prop: "code",
              placeHolder: "请输入编码",
              style: "",
              rules: [{ required: true, message: "  ", trigger: "blur" }]
            },
            {
              type: "input",
              label: "标题",
              prop: "title",
              placeHolder: "请输入节点标题",
              style: "",
              rules: [{ required: true, message: "  ", trigger: "blur" }],
              default: "点击修改"
            }
          ]
        },
        {
          title: "节点路径",
          key: "baseinfo",
          cols: 2,
          ctls: [
            {
              type: "input",
              label: "KEY",
              prop: "nodeKey",
              placeHolder: "请输入编码",
              disabled: true,
              style: "",
              rules: []
            },
            {
              type: "input",
              label: "路径",
              prop: "orgpath",
              placeHolder: "",
              disabled: true,
              style: "",
              rules: []
            }
          ]
        }
      ],
      originalRoot: {
        title: "使用者定义",
        code: "root",
        expand: true,
        orgpath: "/root",
        render: (h, { root, node, data }) => {
          return h(
            "span",
            {
              style: {
                display: "inline-block",
                width: "100%"
              }
            },
            [
              h(
                "span",
                {
                  on: {
                    dblclick: () => {
                      this.onselnode(node, data);
                    },
                    click: () => {
                      this.currentData = data;
                      this.currentNode = node;
                      this.rootNode = root;
                    }
                  }
                },
                [
                  h("Icon", {
                    props: {
                      type: "ios-folder-outline"
                    },
                    style: {
                      marginRight: "8px"
                    }
                  }),
                  h("span", {}, [data.title])
                ]
              ),
              h(
                "span",
                {
                  style: {
                    display: "inline-block",
                    float: "right",
                    marginRight: "32px"
                  }
                },
                [
                  h("Button", {
                    props: Object.assign({}, this.buttonProps, {
                      icon: "md-add",
                      type: "text"
                    }),
                    style: {
                      width: "64px"
                    },
                    on: {
                      click: () => {
                        this.append(data);
                      }
                    }
                  })
                ]
              )
            ]
          );
        },
        children: []
      },
      showedform: false,
      buttonProps: {
        type: "default",
        size: "small"
      },
      nodeinfo: {},
      treeheight: 0
    };
  },
  mounted() {
    this.initTree();
  },
  created() {
    if (this.metainfo) {
      this.nodeinfo = Object.assign(this.nodeinfo, this.metainfo);
      this.nodeinfo.main = this.nodeinfo.main.concat(this.originalMetaInfo);
    }
    window.modiTreeNodeByCode = function(treedata, newobj, parentitem) {
      treedata.forEach(item => {
        if (item.nodeKey == newobj.nodeKey) {
          item = Object.assign(item, newobj);
        }
        if (item.children) {
          if (parentitem) {
            item.orgpath = parentitem.orgpath + "/" + item.code;
          } else {
            item.orgpath = item.code;
          }
          item.children.sort((item1, item2) => {
            return item1.seq < item2.seq;
          });
          modiTreeNodeByCode(item.children, newobj, item);
        } else {
          if (parentitem) {
            item.orgpath = parentitem.orgpath + "/" + item.code;
          } else {
            item.orgpath = item.code;
          }
        }
      });
    };
  },
  methods: {
    setCtlVisable(prop, b) {
      this.$refs.nodeform.setCtlVisable(prop, b);
    },
    controlctl(v, prop, fm) {
      this.$emit("controlctl", v, prop, fm);
    },
    ondrawvisable(v) {
      this.$emit("drawaction", v, this.$refs.nodeform);
    },
    resetForm() {
      this.$refs.nodeform.resetForm();
      this.$refs.nodeform.formModel.children = [];
    },
    refreshTree() {
      this.isupdate = true;
      this.$nextTick(() => {
        this.isupdate = false;
      });
    },
    doexec(k, fm) {
      if (k == "ok") {
        this.$refs.nodeform.validate(v => {
          console.log(v);
          if (v) {
            let modiobj = this.$refs.nodeform.getNewModel();
            modiTreeNodeByCode(this.treedata, modiobj, null);
            this.showedform = false;
            this.$emit("modisave", this.treedata, modiobj);
            this.resetForm();
            console.log(this.treedata);
            //this.refreshTree()//使用者调用刷新
          }
        });
      } else {
        this.showedform = false;
        this.resetForm();
      }
    },
    deepclone(ind) {
      let s = JSON.stringify(ind);
      return JSON.parse(s);
    },
    onselnode(node, data) {
      this.showedform = true;
      this.currentData = data;
      this.currentNode = node;
      let nd = this.deepclone(data);
      this.$refs.nodeform.resetForm();
      this.$refs.nodeform.formModel = nd;
    },
    initTree() {
      //异步加载
      //按照当前公司加载组织结构,如果数据为空，那么就初始化一个根实体对象
      if (this.initData) {
        this.initData(originalData => {
          if (
            originalData &&
            originalData[0] &&
            (!originalData.children ||
              (originalData.children && originalData.children.length == 0))
          ) {
            this.originalRoot = Object.assign(
              this.originalRoot,
              originalData[0]
            );
            console.log(originalData);
            console.log(
              "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<,",
              this.originalRoot
            );
            this.treedata = [this.originalRoot];
          } else {
            originalData[0].render = this.originalRoot.render;
            this.treedata = originalData;
          }
        });
      }
    },
    setHeight() {
      let $orgcard = $("#orgcard");
      let el = $orgcard.get()[0];
      let h = window.innerHeight - el.offsetTop - 30;
      $orgcard.css("height", h + "px");
      this.treeheight = h;
    },
    renderContent(h, { root, node, data }) {
      return h(
        "span",
        {
          style: {
            display: "inline-block",
            width: "100%"
          }
        },
        [
          h(
            "span",
            {
              on: {
                dblclick: $event => {
                  $("span", ".ptree").removeClass("spansel");
                  $($event.target)
                    .parent()
                    .parent()
                    .addClass("spansel");
                  this.onselnode(node, data);
                },
                click: () => {
                  this.currentData = data;
                  this.currentNode = node;
                  this.rootNode = root;
           
                }
              }
            },
            [
              h("Icon", {
                props: {
                  type:
                    data.children && data.children.length > 0
                      ? "ios-folder-outline"
                      : "ios-paper-outline"
                },
                style: {
                  marginRight: "8px"
                }
              }),
              h("span", data.title)
            ]
          ),
          h(
            "span",
            {
              style: {
                display: "inline-block",
                float: "right",
                marginRight: "32px"
              }
            },
            [
              h("Button", {
                props: Object.assign({}, this.buttonProps, {
                  icon: "ios-add"
                }),
                style: {
                  marginRight: "8px"
                },
                on: {
                  click: () => {
                    this.append(data);
                  }
                }
              }),
              h("Button", {
                props: Object.assign({}, this.buttonProps, {
                  icon: "ios-remove"
                }),
                on: {
                  click: () => {
                    this.remove(root, node, data);
                  }
                }
              })
            ]
          )
        ]
      );
    },
    append(data) {
      const children = data.children || [];
      let newModel = this.$refs.nodeform.getNewModel();
      console.log("new model.........................", newModel);
      newModel.expand = true;
      children.push(newModel);
      this.$set(data, "children", children);
    },
    remove(root, node, data) {
      const parentKey = root.find(el => el === node).parent;
      const parent = root.find(el => el.nodeKey === parentKey).node;
      const index = parent.children.indexOf(data);
      parent.children.splice(index, 1);
    },
    findParentByNode(node) {
      const parentKey = this.rootNode.find(el => el === node).parent;
      const parent = this.rootNode.find(el => el.nodeKey === parentKey).node;
      return parent
    }
  }
};
</script>
  <style>
.ptree span:hover {
  background-color: lightgray;
}

.spansel {
  background-color: lightgray;
}
</style>
