<template>
  <el-dialog
    :visible="visible"
    :title="title"
    :close-on-click-modal="false"
    :show-close="false"
    :width="dialogWidth"
    append-to-body
  >
    <el-row>
      <el-col :span="leftSpan">
        <div style="line-height:28px">{{$t('User.selectdialog.5205rmgbap00')}}</div>
        <div class="userbox">
          <div class="userbox-header">
            <el-input
              :placeholder="$t('User.selectdialog.5205rmgbbtc0')"
              v-model="filterKey"
              size="mini"
              clearable
            >
              <el-select
                v-if="tags && tags.length > 0"
                v-model="tagIds"
                slot="prepend"
                style="width:200px;"
                multiple
                collapse-tags
                :placeholder="$t('User.selectdialog.5205rmgbc280')"
              >
                <el-option
                  v-for="item in tags"
                  :key="item.Id"
                  :label="item.Name"
                  :value="item.Id"
                >
                </el-option>
              </el-select>
            </el-input>
          </div>
          <div class="userbox-container">
            <el-row v-if="filterKey || (tagIds && tagIds.length > 0)">
              <el-col>
                <div class="userbox-filter">
                  <filter-user-list
                    v-model="tagValue"
                    ref="userlist"
                    :closeTag="closeTag"
                    :filterKay="filterKey"
                    :userData="userList"
                    :multiple="multiple"
                    :tags="tags"
                    :tagDict="tagDict"
                    :tagIds="tagIds"
                  />
                </div>
              </el-col>
            </el-row>
            <el-row v-else>
              <el-col v-if="showTree" :span="12">
                <div class="userbox-tree">
                  <div class="userbox-tags" v-if="showTags">
                    <el-button-group style="width:100%;">
                      <el-button
                        size="mini"
                        style="width:50%"
                        round
                        :type="orgTag"
                        @click="handleOrgClick"
                        >{{$t('User.selectdialog.5205rmgbc880')}}</el-button
                      >
                      <el-button
                        size="mini"
                        style="width:50%"
                        round
                        :type="roleTag"
                        @click="handleRoleClick"
                        >{{$t('User.selectdialog.5205rmgbchk0')}}</el-button
                      >
                    </el-button-group>
                  </div>
                  <div class="userbox-content" :class="noTags">
                    <org-tree
                      v-if="tabName == 'org'"
                      v-model="filterOrgId"
                      :treeData="orgTreeData"
                      :defaultExpandedKeys="orgDefaultExpandedKeys"
                      :currentNodeKey="orgCurrentNodeKey"
                    />
                    <org-tree
                      v-if="tabName == 'role'"
                      v-model="filterRoleId"
                      :treeData="roleTreeData"
                      :defaultExpandedKeys="roleDefaultExpandedKeys"
                      :currentNodeKey="roleCurrentNodeKey"
                    />
                  </div>
                </div>
              </el-col>
              <el-col :span="listSpan">
                <div class="userbox-list">
                  <user-list
                    v-model="tagValue"
                    ref="userlist"
                    :closeTag="closeTag"
                    :filterKay="filterKey"
                    :filterOrgId="filterOrgId"
                    :filterRoleId="filterRoleId"
                    :userData="userList"
                    :multiple="multiple"
                  />
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-col>
      <el-col v-if="showSelected" :span="rightSpan">
        <div style="line-height:28px">{{$t('User.selectdialog.5205rmgbcs80')}}</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('User.selectdialog.5205rmgbcy80')}}</el-button>
      <el-button @click="handleOK()" size="small" type="primary"
        >{{$t('User.selectdialog.5205rmgbd380')}}</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import UserList from "./userlist.vue";
import FilterUserList from "./filteruserlist.vue";
import OrgTree from "./orgtree.vue";

export default {
  name: "selectdialog",
  components: {
    UserList,
    FilterUserList,
    OrgTree
  },
  props: {
    value: { required: true },
    visible: { type: Boolean, default: false },
    multiple: Boolean,
    userData: { dafault: null },
    orgData: { dafault: null },
    roleData: { dafault: null },
    rootNode: { default: null },
    excludedUserIds: { dafault: null },
    showInvalid: { default: false }, //显示禁用用户
    tags: { default: null },
    tagDict: { default: null },
    tabs: {
      default: () => {
        return [];
      }
    } //'org','role'
  },
  data() {
    return {
      title: this.$t('User.selectdialog.5205rmgbdaw0'),
      tabName: "",
      filterValue: null,
      filterKey: "",
      tagIds: null,
      filterOrgId: 0,
      filterRoleId: null,
      tagValue: null,
      closeTag: null,
      userList: null,
      orgTreeData: null,
      roleTreeData: null,
      showUserList: true,
      orgDefaultExpandedKeys: null,
      orgCurrentNodeKey: null,
      roleDefaultExpandedKeys: null,
      roleCurrentNodeKey: null
    };
  },
  computed: {
    orgTag() {
      return this.tabName == "org" ? "primary" : "";
    },
    roleTag() {
      return this.tabName == "role" ? "primary" : "";
    },
    noTags() {
      // if (!(this.orgData && this.roleData)) {
      if (this.tabs.includes("org") && this.tabs.includes("role")) {
        return "";
      } else {
        return "no-tags";
      }
    },
    showSelected() {
      if (this.multiple) {
        return true;
      } else {
        return false;
      }
    },
    showTree() {
      return this.tabs.includes("org") || this.tabs.includes("role");
      // if ((this.orgData && this.orgData.length>0) || (this.roleData&& this.roleData.length>0)) {
      //   return true
      // } else {
      //   return false
      // }
    },
    showTags() {
      return this.tabs.includes("org") && this.tabs.includes("role");
      // return this.orgData && this.orgData.length>0 && this.roleData && this.roleData.length>0
    },
    dialogWidth() {
      let width = 480;
      if (this.showSelected) {
        width += 300;
      }
      if (this.showTree) {
        width += 300;
      }
      return `${width}px`;
    },
    rightSpan() {
      if (this.showTree) {
        return 8;
      }
      return 12;
    },
    leftSpan() {
      if (this.showSelected) {
        if (this.showTree) {
          return 16;
        } else {
          return 12;
        }
      }
      return 24;
    },
    listSpan() {
      // if ((this.orgData && this.orgData.length>0) || (this.roleData&& this.roleData.length>0)) {
      if (this.tabs.includes("org") || this.tabs.includes("role")) {
        return 12;
      } else {
        return 24;
      }
    }
  },
  methods: {
    deepClone(obj) {
      var _obj = JSON.stringify(obj),
        objClone = JSON.parse(_obj);
      return objClone;
    },
    handleClose() {
      this.tagValue = [];
      this.$emit("update:visible", false);
    },
    handleOK() {
      this.$emit("input", this.tagValue);
      this.$emit("update:visible", false);
    },
    handleOrgClick() {
      this.tabName = "org";
      this.filterRoleId = null;
      this.filterOrgId = 0;
    },
    handleRoleClick() {
      this.tabName = "role";
      this.filterOrgId = null;
      this.filterRoleId = 0;
    },
    setUserList(userData) {
      let excludedUserIds = this.excludedUserIds;
      let showInvalid = this.showInvalid;
      let builUserList = function() {
        let userList = [];
        if (!userData) {
          return userList;
        }
        userData
          .filter(user => {
            if (!showInvalid) {
              if (user.status == 0) {
                return false;
              }
            }
            if (excludedUserIds) {
              const userId = user.id ? user.id : user.Id;
              return excludedUserIds.findIndex(x => x == userId) == -1;
            } else {
              return true;
            }
          })
          .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 orgIds = node.orgIds ? node.orgIds : node.OrgIds;
            const roleIds = node.roleIds ? node.roleIds : node.RoleIds;
            userList.push({
              id: userId,
              value: userValue,
              label: userLabel,
              icon: "el-icon-user",
              imageUrl: userImageUrl,
              jobTitle: userJobTitle,
              orgIds: orgIds,
              roleIds: roleIds,
              type: "user"
            });
          });
        return userList;
      };

      this.userList = builUserList();
    },
    setOrgTree(orgData) {
      let that = this;
      let buildOrgNode = function(parentId) {
        let orgNode = [];
        let orgTreeData = null;
        if (!orgData) {
          return orgNode;
        } else {
          orgTreeData = that.deepClone(orgData);
          orgTreeData.push({
            Id: -1,
            Label: that.$t('User.selectdialog.5205rmgbdi80'),
            Icon: "org",
            ParentId: 0
          });
        }
        orgTreeData
          .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
            });
          });
        return orgNode;
      };

      let children = buildOrgNode(0);
      let rootLabel = this.$t('User.selectdialog.5205rmgbdog0');
      if (this.rootNode) {
        let rootLabel = this.rootNode.label
          ? this.rootNode.label
          : this.rootNode.name;
      }

      // rootLabel += '(全部组织)'
      this.orgTreeData = [
        {
          id: 0,
          value: `org_0`,
          label: rootLabel,
          icon: "el-icon-school",
          type: "org",
          parentId: ``,
          children: children
        }
      ];
      this.orgDefaultExpandedKeys = [`org_0`];
      this.orgCurrentNodeKey = `org_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.rootNode.name
      //   // rootLabel += '(全部组织)'
      //   this.orgTreeData = [{ id: rootId, value: `org_${rootId}`, label: rootLabel, icon: 'el-icon-school', type: 'org', parentId: ``, children: children }]
      //   this.orgDefaultExpandedKeys = [`org_${rootId}`]
      //   this.orgCurrentNodeKey = `org_${rootId}`
      // } else {
      //   this.orgTreeData = children
      //   this.orgDefaultExpandedKeys = null
      //   this.orgCurrentNodeKey = null
      // }
    },
    setRoleNode(roleData) {
      let that = this;
      let buildRoleNode = function() {
        let roleNode = [];
        let roleTreeData = null;
        if (!roleData) {
          return roleNode;
        } else {
          roleTreeData = that.deepClone(roleData);
          roleTreeData.push({
            Id: -1,
            Label: that.$t('User.selectdialog.5205rmgbdyo0'),
            Icon: "org",
            ParentId: 0
          });
        }
        roleTreeData.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();
      let rootLabel = "(全部)";
      this.roleTreeData = [
        {
          id: 0,
          value: `role_0`,
          label: rootLabel,
          icon: "el-icon-school",
          type: "role",
          parentId: ``,
          children: children
        }
      ];
      this.roleDefaultExpandedKeys = [`role_0`];
      this.roleCurrentNodeKey = `role_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.rootNode.name
      //   rootLabel += '(全部用户)'
      //   this.roleTreeData = [{ id: rootId, value: `role_${rootId}`, label: rootLabel, icon: 'el-icon-school', type: 'role', parentId: ``, children: children }]
      //   this.roleDefaultExpandedKeys = [`role_${rootId}`]
      //   this.roleCurrentNodeKey = `role_${rootId}`
      // } else {
      //   this.roleTreeData = children
      //   this.roleDefaultExpandedKeys = null
      //   this.roleCurrentNodeKey = null
      // }
    },
    getImageUrl(item) {
      let user = this.userData.find(
        user => user.Id == item.Id || user.id == item.Id
      );
      return user.imageUrl ? user.imageUrl : user.ImageUrl;
    },
    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);
    }
  },
  watch: {
    visible(value) {
      if (value) {
        this.tagValue = [];
        this.filterKey = "";
        this.filterOrgId = 0;
        this.filterRoleId = null;
        if (this.userData) {
          this.setUserList(this.userData);
        }
        if (this.tabs.includes("org")) {
          if (this.orgData) {
            this.tabName = "org";
            this.setOrgTree(this.orgData);
          }
        }

        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;
      }
    }
  }
};
</script>

<style lang="scss">
.tag-group {
  padding: 5px;
  .el-tag {
    margin: 2px;
  }
}
.el-tree {
  background: none;
}
.userbox {
  //   margin-right: 5px;
  border: 1px solid #ebeef5;
  overflow: hidden;
  background-color: #f4f6f8;
  .userbox-header {
    height: 28px;
    margin: 5px;
  }
  .userbox-container {
    background-color: #fff;

    .userbox-filter {
      height: 400px;
      background-color: #f1f1f2;
      border-right: 1px solid #ebeef5;
      padding: 5px;

      .userbox-content {
        height: 390px;
        overflow: auto;

        .userbox-content-item {
          cursor: pointer;
          .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;
            }
          }
        }
      }
    }

    .userbox-tree {
      height: 400px;
      background-color: #f1f1f2;
      border-right: 1px solid #ebeef5;
      padding: 5px;

      .userbox-tags {
        height: 28px;
        margin-bottom: 5px;
      }

      .userbox-content {
        height: 357px;
        overflow: auto;
      }

      .no-tags {
        height: 395px;
      }
    }
    .userbox-list {
      height: 400px;
      padding: 5px;

      .userbox-content {
        height: 390px;
        overflow: auto;

        .userbox-content-item {
          cursor: pointer;
          .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;
            }
          }
        }
      }
    }
  }
}

.tagbox {
  margin-left: 5px;
  border: 1px solid #ebeef5;
  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>
