<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <ele-split-layout
        width="330px"
        allow-collapse
        :right-style="{ overflow: 'hidden' }"
      >
        <div>
          <!-- 操作按钮 -->
          <ele-toolbar class="ele-toolbar-actions">
            <div style="margin: 5px 0">
              <el-button
                size="small"
                type="primary"
                icon="el-icon-plus"
                class="ele-btn-icon"
                @click="openEdit()"
              >
                添加
              </el-button>
              <el-button
                size="small"
                type="warning"
                icon="el-icon-edit"
                class="ele-btn-icon"
                :disabled="!current"
                @click="openEdit(current)"
              >
                修改
              </el-button>
              <el-button
                size="small"
                type="danger"
                icon="el-icon-delete"
                class="ele-btn-icon"
                :disabled="!current"
                @click="remove"
              >
                删除
              </el-button>
              <el-button
                size="small"
                type="primary"
                class="ele-btn-icon"
                icon="el-icon-download"
                @click="exportData"
              >
                导出
              </el-button>
            </div>
          </ele-toolbar>
          <div class="ele-border-lighter sys-groups-list">
            <el-tree
              ref="tree"
              :data="data"
              highlight-current
              node-key="groupsId"
              :props="{ label: 'groupsName' }"
              :expand-on-click-node="false"
              :default-expand-all="true"
              @node-click="onNodeClick"
            />
          </div>
        </div>
        <template v-slot:content>
          <gro-user-list
            v-if="current"
            :data="current"
            :groups-id="current.groupsId"
            :organization-list="organizationList"
            :team-list="teamList"
          />
        </template>
      </ele-split-layout>
    </el-card>
    <!-- 编辑弹窗 -->
    <gro-edit
      :visible.sync="showEdit"
      :data="editData"
      :activity-id="activityId"
      :parent-id="parentId"
      :groups-list="data"
      :statistics-type-list="statisticsTypeList"
      :organization-list="organizationList"
      @done="query"
    />
  </div>
</template>

<script>
  import GroUserList from './components/gro-user-list.vue';
  import GroEdit from './components/gro-edit.vue';
  import {
    listGroups,
    removeGroups,
    exportGroupsConsultant
  } from '@/api/sylive/groups';
  import { listOrganizations } from '@/api/institution/organization';
  import { listTeams } from '@/api/institution/team';
  import { listDictionaries } from '@/api/system/dictionary';
  import { utils, writeFile } from 'xlsx';
  const ROUTE_PATH = '/sylive/groups';

  export default {
    name: 'SyliveGroups',
    components: { GroUserList, GroEdit },
    data() {
      return {
        // 加载状态
        loading: true,
        // 列表数据
        data: [],
        // 选中数据
        current: null,
        // 机构数据
        organizationList: [],
        // 团队数据
        teamList: [],
        // 统计类型数据
        statisticsTypeList: [],
        // 是否显示表单弹窗
        showEdit: false,
        // 编辑回显数据
        editData: null,
        // 上级id
        parentId: null,
        // 活动id
        activityId: null
      };
    },
    created() {
      this.organizationQuery();
      this.teamQuery();
      this.statisticsTypeQuery();
    },
    methods: {
      /* 查询 */
      query() {
        this.loading = true;
        listGroups({ activityId: this.activityId })
          .then((list) => {
            this.loading = false;
            this.data = this.$util.toTreeData({
              data: list,
              idField: 'groupsId',
              parentIdField: 'parentId'
            });
            this.$nextTick(() => {
              this.onNodeClick(this.data[0]);
            });
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
      },
      /* 查询机构 */
      organizationQuery() {
        listOrganizations({
          unOrganizationType: 4,
          activityId: this.activityId
        })
          .then((list) => {
            this.organizationList = this.$util.toTreeData({
              data: list,
              idField: 'organizationId',
              parentIdField: 'parentId'
            });
          })
          .catch((e) => {
            this.$message.error(e.message);
          });
      },
      /* 查询团队 */
      teamQuery() {
        listTeams({ unTeamType: 3 })
          .then((list) => {
            this.teamList = this.$util.toTreeData({
              data: list,
              idField: 'teamId',
              parentIdField: 'parentId'
            });
          })
          .catch((e) => {
            this.$message.error(e.message);
          });
      },
      /* 查询统计类型 */
      statisticsTypeQuery() {
        listDictionaries({ dictCode: 'groups_level' })
          .then((list) => {
            this.statisticsTypeList = list;
          })
          .catch((e) => {
            this.$message.error(e.message);
          });
      },
      /* 选择数据 */
      onNodeClick(row) {
        if (row) {
          this.current = row;
          this.parentId = row.groupsId;
          this.$refs.tree.setCurrentKey(row.groupsId);
        } else {
          this.current = null;
          this.parentId = null;
        }
      },
      /* 显示编辑 */
      openEdit(item) {
        this.editData = item;
        this.showEdit = true;
      },
      /* 删除 */
      remove() {
        this.$confirm('确定要删除选中的分组吗?', '提示', {
          type: 'warning'
        })
          .then(() => {
            const loading = this.$loading({ lock: true });
            removeGroups(this.current.groupsId)
              .then((msg) => {
                loading.close();
                this.$message.success(msg);
                this.query();
              })
              .catch((e) => {
                loading.close();
                this.$message.error(e.message);
              });
          })
          .catch(() => {});
      },
      /* 导出数据 */
      exportData() {
        const loading = this.$loading({ lock: true });
        const activityId = this.activityId;
        exportGroupsConsultant({ activityId })
          .then((data) => {
            loading.close();
            const array = [data.columns];
            data.list.forEach((d) => {
              let arrayItem = [];
              for (let key in d) {
                arrayItem.push(d[key]);
              }
              array.push(arrayItem);
            });
            writeFile(
              {
                SheetNames: ['Sheet1'],
                Sheets: {
                  Sheet1: utils.aoa_to_sheet(array)
                }
              },
              '分组顾问' + '.xlsx'
            );
          })
          .catch((e) => {
            loading.close();
            this.$message.error(e.message);
          });
      }
    },
    watch: {
      $route: {
        handler(route) {
          const { path } = route;
          if (path !== ROUTE_PATH) {
            return;
          }
          const activityId = this.$route.query.id;
          if (!activityId || activityId == this.activityId) {
            return;
          }
          this.activityId = Number(activityId);
          this.query();
        },
        immediate: true
      }
    }
  };
</script>

<style lang="scss" scoped>
  .sys-groups-list {
    height: calc(100vh - 264px);
    box-sizing: border-box;
    border-width: 1px;
    border-style: solid;
    overflow: auto;
  }

  .sys-groups-list :deep(.el-tree-node__content) {
    height: 40px;

    & > .el-tree-node__expand-icon {
      margin-left: 10px;
    }
  }
</style>
