<template>
  <el-dialog
    :visible="visible"
    :title="title"
    :close-on-click-modal="false"
    :show-close="false"
    width="780px"
    append-to-body
  >
    <el-row>
      <el-col :span="12">
        <div style="line-height:28px">{{$t('UserMixed.selectdialog.5205ueoh6ew0')}}</div>
        <div class="treebox">
          <el-tabs v-model="tabName" type="border-card">
            <el-tab-pane v-if="showOrgTab" :label="$t('UserMixed.selectdialog.5205ueoh7io0')" name="org">
              <org-tree
                v-model="tagValue"
                :treeData="orgTreeData"
                :closeTag="closeTag"
                :multiple="multiple"
                :defaultExpandedKeys="orgDefaultExpandedKeys"
                :defaultCheckedKeys="orgDefaultCheckedKeys"
                :currentNodeKey="orgCurrentNodeKey"
                :tags="tags"
                :tagDict="tagDict"
              />
            </el-tab-pane>
            <el-tab-pane v-if="roleTreeData" :label="$t('UserMixed.selectdialog.5205ueoh7qo0')" name="role">
              <role-tree
                v-model="tagValue"
                :treeData="roleTreeData"
                :closeTag="closeTag"
                :multiple="multiple"
                :defaultExpandedKeys="roleDefaultExpandedKeys"
                :defaultCheckedKeys="roleDefaultCheckedKeys"
                :currentNodeKey="roleCurrentNodeKey"
                :tags="tags"
                :tagDict="tagDict"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-col>
      <el-col :span="12">
        <div style="line-height:28px">{{$t('UserMixed.selectdialog.5205ueoh7w40')}}</div>
        <div class="tagbox">
          <div class="tagbox-content">
            <el-table
              ref="multipleTable"
              :data="tagValue"
              tooltip-effect="dark"
              style="width: 100%"
              :show-header="false"
            >
              <el-table-column width="40">
                <template slot-scope="scope">
                  <span class="tag-image"
                    ><img
                      :src="getImageUrl(scope.row)"
                      style="object-fit: cover;"
                  /></span>
                </template>
              </el-table-column>
              <el-table-column prop="label" width="*">
                <template slot-scope="scope"> {{ scope.row.Label }}</template>
              </el-table-column>
              <el-table-column prop="value" width="50">
                <template slot-scope="scope">
                  <el-button
                    @click="handleCloseTag(scope.row.Type, scope.row.Id)"
                    icon="el-icon-close"
                    size="small"
                    circle
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-col>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose()" size="small">{{$t('UserMixed.selectdialog.5205ueoh8200')}}</el-button>
      <el-button @click="handleOK()" size="small" type="primary"
        >{{$t('UserMixed.selectdialog.5205ueoh88w0')}}</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
// import UserTree from './usertree.vue'
import OrgTree from "./orgtree.vue";
import RoleTree from "./roletree.vue";

export default {
  name: "selectdialog",
  components: {
    // UserTree,
    OrgTree,
    RoleTree
  },
  props: {
    value: { required: true },
    visible: { type: Boolean, default: false },
    multiple: Boolean,
    userData: { dafault: null },
    orgData: { dafault: null },
    roleData: { dafault: null },
    rootNode: { default: null },
    tags: { default: null },
    tagDict: { default: null },
    tabs: {
      default: () => {
        return [];
      }
    } //'org','role'
  },
  data() {
    return {
      title: this.$t('UserMixed.selectdialog.5205ueoh8e00'),
      tagValue: null,
      tabName: "",
      closeTag: null,
      userTreeData: null,
      orgTreeData: null,
      roleTreeData: null,
      orgDefaultExpandedKeys: null,
      orgDefaultCheckedKeys: null,
      orgCurrentNodeKey: null,
      roleDefaultExpandedKeys: null,
      roleDefaultCheckedKeys: null,
      roleCurrentNodeKey: null
    };
  },
  computed: {
    showOrgTab() {
      return this.tabs.includes("org");
    }
  },
  methods: {
    deepClone(obj) {
      var _obj = JSON.stringify(obj),
        objClone = JSON.parse(_obj);
      return objClone;
    },
    handleClose() {
      this.$emit("update:visible", false);
    },
    handleOK() {
      this.$emit("input", this.tagValue);
      this.$emit("update:visible", false);
    },
    setOrgNode(orgData, userData) {
      let excludedUserIds = this.excludedUserIds;
      let buildUserNode = function(orgid) {
        let userNode = [];
        if (!userData) {
          return userNode;
        }
        if (orgid == 0) {
          userData
            .filter(user => {
              if (excludedUserIds) {
                const userId = user.id ? user.id : user.Id;
                if (excludedUserIds.findIndex(x => x == userId) > -1) {
                  return false;
                }
              }
              const userOrgIds = user.orgIds ? user.orgIds : user.OrgIds;
              return (
                !userOrgIds ||
                userOrgIds.length == 0 ||
                userOrgIds.findIndex(x => x == 0) > -1
              );
            })
            .forEach(node => {
              const userId = node.id ? node.id : node.Id;
              const userLabel = node.label ? node.label : node.Label;
              const userImageUrl = node.imageUrl
                ? node.imageUrl
                : node.ImageUrl;
              const userValue = `user_${userId}`;
              const userJobTitle = node.jobTitle
                ? node.jobTitle
                : node.JobTitle;
              const userLabelTitle = userJobTitle
                ? `${userLabel} (${userJobTitle})`
                : userLabel;
              userNode.push({
                id: userId,
                value: userValue,
                label: userLabelTitle,
                icon: "el-icon-user",
                imageUrl: userImageUrl,
                type: "user",
                parentId: `org_${orgid}`
              });
            });
        } else {
          userData
            .filter(user => {
              if (excludedUserIds) {
                const userId = user.id ? user.id : user.Id;
                if (excludedUserIds.findIndex(x => x == userId) > -1) {
                  return false;
                }
              }
              const userOrgIds = user.orgIds ? user.orgIds : user.OrgIds;
              return userOrgIds.findIndex(x => x == orgid) > -1;
            })
            .forEach(node => {
              const userId = node.id ? node.id : node.Id;
              const userLabel = node.label ? node.label : node.Label;
              const userImageUrl = node.imageUrl
                ? node.imageUrl
                : node.ImageUrl;
              const userValue = `user_${userId}`;
              const userJobTitle = node.jobTitle
                ? node.jobTitle
                : node.JobTitle;
              const userLabelTitle = userJobTitle
                ? `${userLabel} (${userJobTitle})`
                : userLabel;
              userNode.push({
                id: userId,
                value: userValue,
                label: userLabelTitle,
                icon: "el-icon-user",
                imageUrl: userImageUrl,
                type: "user",
                parentId: `org_${orgid}`
              });
            });
        }
        return userNode;
      };

      let buildOrgNode = function(parentId) {
        let orgNode = [];
        if (!orgData) {
          return orgNode;
        }
        orgData
          .filter(node => {
            const orgParentId =
              node.parentId != undefined ? node.parentId : node.ParentId;
            return orgParentId === parentId;
          })
          .forEach(node => {
            const orgId = node.id ? node.id : node.Id;
            const orgLabel = node.label ? node.label : node.Label;
            const orgValue = `org_${orgId}`;
            let childrenNode = buildOrgNode(orgId);
            orgNode.push({
              id: orgId,
              value: orgValue,
              label: orgLabel,
              icon: "el-icon-folder",
              imageUrl: null,
              type: "org",
              parentId: `org_${parentId}`,
              children: childrenNode
            });
          });
        let userNode = buildUserNode(parentId);
        return orgNode.concat(userNode);
      };

      let children = buildOrgNode(0);

      if (this.rootNode) {
        const rootId =
          this.rootNode.id != undefined ? this.rootNode.id : this.roleData.Id;
        let rootLabel = this.rootNode.label
          ? this.rootNode.label
          : this.roleData.Label;
        rootLabel += "(全部组织)";
        this.orgTreeData = [
          {
            id: rootId,
            value: `org_${rootId}`,
            label: rootLabel,
            icon: "el-icon-school",
            type: "org",
            parentId: ``,
            children: children
          }
        ];
        this.orgDefaultExpandedKeys = [`org_${rootId}`];
      } else {
        this.orgDefaultExpandedKeys = null;
        this.orgTreeData = children;
      }
      this.orgDefaultCheckedKeys = [];
      if (this.value) {
        this.value.filter(x => {
          if (x.Type == "org" || x.Type == "user") {
            this.orgDefaultCheckedKeys.push(`${x.Type}_${x.Id}`);
          }
        });
        if (!this.multiple) {
          this.orgCurrentNodeKey = `${this.value[0].Type}_${this.value[0].Id}`;
        }
      }
    },
    setRoleNode(roleData) {
      let buildRoleNode = function() {
        let roleNode = [];
        if (!roleData) {
          return roleNode;
        }
        roleData.forEach(node => {
          const roleId = node.id ? node.id : node.Id;
          const roleabel = node.label ? node.label : node.Label;
          const roleImageUrl = "/img/role.png";
          const roleValue = `role_${roleId}`;
          roleNode.push({
            id: roleId,
            value: roleValue,
            label: roleabel,
            icon: "el-icon-folder",
            imageUrl: roleImageUrl,
            type: "role"
          });
        });
        return roleNode;
      };

      let children = buildRoleNode();
      if (this.rootNode) {
        const rootId =
          this.rootNode.id != undefined ? this.rootNode.id : this.roleData.Id;
        let rootLabel = this.rootNode.label
          ? this.rootNode.label
          : this.roleData.Label;
        rootLabel += "(全部角色)";
        this.roleTreeData = [
          {
            id: rootId,
            value: `role_${rootId}`,
            label: rootLabel,
            icon: "el-icon-school",
            type: "role",
            parentId: ``,
            children: children
          }
        ];
        this.roleDefaultExpandedKeys = [`role_${rootId}`];
      } else {
        this.roleDefaultExpandedKeys = null;
        this.roleTreeData = children;
      }
      this.roleDefaultCheckedKeys = [];
      if (this.value) {
        this.value.filter(x => {
          if (x.Type == "role") {
            this.roleDefaultCheckedKeys.push(`${x.Type}_${x.Id}`);
          }
        });
        if (!this.multiple) {
          this.roleCurrentNodeKey = `${this.value[0].Type}_${this.value[0].Id}`;
        }
      }
    },
    getImageUrl(item) {
      if (item.Type == "org") {
        return "/img/org.png";
      }
      if (item.Type == "role") {
        return "/img/role.png";
      }
      if (item.Type == "user") {
        let user = this.userData.find(
          user => user.Id == item.Id || user.id == item.Id
        );
        return user.imageUrl ? user.imageUrl : user.ImageUrl;
      }
      return "";
    },
    getJobTitle(item) {
      if (item.Type == "user") {
        let user = this.userData.find(
          user => user.Id == item.Id || user.id == item.Id
        );
        let jobTitle = user.jobTitle ? user.jobTitle : user.JobTitle;
        return jobTitle ? `(${jobTitle})` : "";
      }
      return "";
    },
    handleCloseTag(type, id) {
      this.closeTag = this.tagValue.find(
        tag => tag.Id == id && tag.Type == type
      );
      let index = this.tagValue.findIndex(
        tag => tag.Id == id && tag.Type == type
      );
      this.tagValue.splice(index, 1);
      if (!this.multiple) {
        this.orgCurrentNodeKey = null;
        this.roleCurrentNodeKey = null;
      }
    }
  },
  watch: {
    visible(value) {
      if (value) {
        this.tagValue = [];

        if (this.tabs.includes("org")) {
          if (this.orgData) {
            this.tabName = "org";
            this.setOrgNode(this.orgData, this.userData);
          }
        }

        if (this.tabs.includes("role")) {
          if (this.roleData) {
            if (!this.tabName) {
              this.tabName = "role";
            }
            this.setRoleNode(this.roleData);
          }
        }

        this.tagValue = this.deepClone(this.value);
      } else {
        this.tagValue = [];
        this.orgTreeData = null;
        this.roleTreeData = null;
        this.tabName = null;
      }
    }
  }
};
</script>

<style lang="scss">
.tag-group {
  padding: 5px;
  .el-tag {
    margin: 2px;
  }
}
.el-tree {
  background: none;
}
.treebox {
  margin-right: 5px;
  // border: 1px solid #ebeef5;
  overflow: hidden;
  background-color: #f4f6f8;
  .el-tabs__content {
    padding: 5px;
  }
  .treebox-header {
    margin: 5px 0;
    height: 28px;
  }
  .treebox-tags {
    height: 28px;
    margin: 5px 0;
  }
  .treebox-content {
    height: 351px;
    overflow: auto;
  }
}

.tagbox {
  // margin-left: 5px;
  border: 1px solid #dcdfe6;
  padding: 5px;
  overflow: hidden;
  background-color: #f4f6f8;
  .tagbox-content {
    height: 428px;
    overflow: auto;

    .tag-image {
      display: block;
      overflow: hidden;
      width: 28px;
      height: 28px;
      line-height: 28px;
      border-radius: 50%;

      img {
        object-fit: cover;
        display: block;
        height: 100%;
        vertical-align: middle;
      }
    }

    .el-tag {
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      margin: 2px 0 2px 6px;
    }
  }
}
</style>
