<template>
  <section class="Organization">
    <div class="organizations_content">
      <header>
        <i class="iconfont iconModal_Warning"></i>
        <p>
          并非所有单位都需要参加社区活动，对于需要参加社区活动的单位，请在下方“应报到单位名单”中进行修改，无需参加活动的单位请勿勾选。
        </p>
      </header>
      <div class="organizations_tree">
        <p class="top">
          <span class="word">应报到单位名单</span>
          <el-button
            type="text"
            icon="iconfont iconEdit"
            @click="editDialog = true"
            >修改</el-button
          >
        </p>
        <el-input
          size="mini"
          v-model.trim="selectFilterText"
          style="margin-top: 8px"
          placeholder="请输入单位..."
          suffix-icon="iconfont iconSearch"
          @keyup.native="$refs.selectTree.filter(selectFilterText)"
          clearable
          @clear="$refs.selectTree.filter(selectFilterText)"
        />
        <div class="left_cont">
          <el-tree
            :data="selectTreeData"
            :props="defaultProps"
            ref="selectTree"
            node-key="partyOrgId"
            :default-expanded-keys="[user.info.organizationId]"
            empty-text="搜索不到相关内容"
            :filter-node-method="filterNode"
            :highlight-current="true"
            v-if="selectTreeData.length > 0"
          />
          <div v-else class="no-data" style="height: 300px"></div>
        </div>
      </div>
    </div>
    <el-dialog
      class="mask"
      :visible.sync="editDialog"
      width="520px"
      title="修改应报到单位"
      :close-on-click-modal="false"
    >
      <div class="tree">
        <el-input
          size="mini"
          v-model="filterText"
          placeholder="请输入单位..."
          suffix-icon="iconfont iconSearch"
          clearable
        />
        <div class="left_cont">
          <el-tree
            v-if="editDialog"
            :data="originTreeData"
            :props="defaultProps"
            ref="tree_edit"
            node-key="partyOrgId"
            show-checkbox
            empty-text="搜索不到相关内容"
            :filter-node-method="filterNode"
            :default-expanded-keys="[user.info.organizationId]"
            :default-checked-keys="defaultKeys"
            :current-node-key="user.info.organizationId"
            :highlight-current="true"
          />
          <div v-else class="no-data" style="height: 300px"></div>
        </div>
      </div>
      <div slot="footer" style="text-align: center">
        <el-button
          style="width: 92px"
          size="small"
          class="delete-btn"
          @click="editDialog = false"
          >取消</el-button
        >
        <el-button
          style="width: 92px"
          size="small"
          type="primary"
          @click="selectTree()"
          >确认</el-button
        >
      </div>
    </el-dialog>
  </section>
</template>

<script>
import { mapState } from "vuex";

export default {
  name: "Organization",
  props: {
    instance: Function,
    dict: Object,
    permissions: Function,
  },
  data() {
    return {
      treeData: [],
      editDialog: false,
      filterText: "",
      selectFilterText: "",
    };
  },
  computed: {
    ...mapState(["user"]),
    defaultProps() {
      return {
        children: "children",
        label: "partyOrgName",
      };
    },
    defaultKeys() {
      return this.selectTreeData.map((e) => e.partyOrgId) || [];
    },
    originTreeData() {
      let data = [];
      if (this.editDialog) {
        let origin = JSON.parse(JSON.stringify(this.treeData)) || [];
        data = origin.filter(
          (e) => e.partyOrgId == this.user.info.organizationId
        );
        data.map((t) => this.addChildParty(t, origin));
      }
      return data;
    },
    selectTreeData() {
      let treeMeta = [],
        arr = JSON.parse(
          JSON.stringify(this.treeData.filter((e) => e.checked))
        );
      treeMeta = this.findParent(arr, {
        id: "partyOrgId",
        parent: "partyOrgParentId",
      });
      treeMeta.map((t) => this.addChildParty(t, arr));
      return treeMeta;
    },
  },
  watch: {
    filterText(val) {
      this.$refs.tree_edit.filter(val);
    },
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.partyOrgName.indexOf(value) !== -1;
    },
    // 根据登录用户单位查 树形结构
    searchSysAll() {
      this.treeData = [];
      this.instance.post("/app/apppartyreportconfig/list").then((res) => {
        if (res?.data) {
          this.treeData = res.data;
        }
      });
    },
    selectTree() {
      let selectArr = this.$refs.tree_edit.getCheckedNodes();
      this.updateTree(selectArr);
    },
    updateTree(arr) {
      arr = arr.map((e) => {
        delete e.children;
        return { ...e, checked: true };
      });
      this.instance.post("/app/apppartyreportconfig/addOrUpdate", arr).then((res) => {
        if (res?.code == 0) {
          this.$message.success("修改成功");
          this.searchSysAll();
          this.editDialog = false;
        }
      });
    },
    findParent(data, ops) {
      ops = {
        id: "self",
        parent: "parentId",
        parents: {},
        pending: [],
        ...ops,
      };
      let parentsObj = {};
      data
        .filter(
          (e) => ops.pending.length == 0 || ops.pending.includes(e[ops.id])
        )
        .map((e) => {
          if (e[ops.parent]) {
            parentsObj[e[ops.parent]] = 0;
          } else {
            ops.parents[e[ops.id]] = e;
          }
        });
      let pending = {};
      Object.keys(parentsObj).map((p) => {
        let item = data.find((e) => e[ops.id] == p);
        if (item) {
          item[ops.parent] && (pending[p] = item[ops.parent]);
        } else {
          if (!ops.parents[p]) {
            data
              .filter((e) => e[ops.parent] == p)
              .map((e) => {
                ops.parents[e[ops.id]] = e;
              });
          }
        }
      });
      ops.pending = Object.values(pending);
      if (ops.pending.length) {
        return this.findParent(data, ops);
      } else return Object.values(ops.parents);
    },
  },
  mounted() {
    this.$nextTick(() => this.searchSysAll());
  },
};
</script>

<style lang="scss" scoped>
.Organization {
  width: 100%;
  height: 100%;
  padding: 16px 0;
  overflow: auto;
  display: flex;
  justify-content: center;
  align-items: flex-start;

  .organizations_content {
    width: 1200px;
    height: 100%;
    overflow-y: hidden;

    header {
      width: 100%;
      background: rgba(255, 243, 232, 1);
      border-radius: 4px;
      border: 1px solid rgba(255, 136, 34, 1);
      padding: 8px;
      box-sizing: border-box;
      overflow: hidden;

      .iconfont.iconModal_Warning {
        color: #ff8822;
        height: 100%;
        float: left;
        width: 20px;
      }

      p {
        float: left;
        width: 800px;
        font-size: 12px;
        color: #ff8822;
      }
    }

    .organizations_tree {
      margin-top: 16px;
      width: 100%;
      min-height: 500px;
      background: rgba(255, 255, 255, 1);
      border-radius: 4px;
      padding: 0 16px 16px 16px;
      box-sizing: border-box;
      margin-bottom: 48px;

      .top {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 56px;
        border-bottom: 1px solid #eee;

        .word {
          font-size: 16px;
          color: #333333;
          font-weight: bold;
        }

        :deep( .el-button--text [class*="iconfont"] ){
          color: #5088ff;
        }
      }
    }
  }

  :deep( .el-dialog ){
    .el-dialog__body {
      padding: 16px;
    }
  }

  :deep( .el-tree ){
    margin-top: 16px;
    min-height: 300px;
    max-height: 600px;
    overflow: auto;

    .el-tree-node.is-focusable.is-checked {
      .el-tree-node__label {
        color: #5088ff;
        background: rgba(239, 246, 255, 1);
      }
    }
  }

  :deep( .organizations_tree .el-tree .is-current>.el-tree-node__content ){
    background-color: #26f;
    color: #fff;
  }
}
</style>
