<template>
  <ele-modal
    width="70%"
    :visible="visible"
    title="添加分组用户"
    @update:visible="updateVisible"
  >
    <div class="ele-body" style="padding: 0px">
      <el-card shadow="never" body-style="padding: 0px;">
        <el-row :gutter="15">
          <el-col v-bind="styleResponsive ? { md: 12 } : { span: 12 }">
            <!-- 未选择的用户数据表格 -->
            <ele-pro-table
              :datasource="unChooseUsers"
              :columns="columns"
              sub-title=""
              height="535px"
              emptyText="无未选用户"
              :toolkit="[]"
              layout="total, prev, pager, next, jumper"
            >
              <template v-slot:toolkit>
                <el-row :gutter="15">
                  <el-col style="width: 45%">
                    <ele-tree-select
                      v-show="userFrom == 0 ? true : false"
                      :data="organizationList"
                      label-key="organizationName"
                      value-key="organizationId"
                      v-model="organizationIds"
                      :multiple="true"
                      :clearable="true"
                      placeholder="请选择机构"
                      :disabled="false"
                      size="small"
                      :check-strictly="false"
                    />
                    <ele-tree-select
                      v-show="userFrom == 1 ? true : false"
                      :data="teamList"
                      label-key="teamName"
                      value-key="teamId"
                      v-model="teamIds"
                      :multiple="true"
                      :clearable="true"
                      placeholder="请选择团队"
                      :disabled="false"
                      size="small"
                      :check-strictly="false"
                    />
                  </el-col>
                  <el-col style="width: 25%">
                    <el-input
                      clearable
                      v-model="keyword"
                      placeholder="姓名或手机"
                      size="small"
                    />
                  </el-col>
                  <el-col style="width: 12%">
                    <el-button
                      class="ele-btn-icon"
                      size="small"
                      @click="search"
                    >
                      搜索
                    </el-button>
                  </el-col>
                  <el-col style="width: 18%">
                    <el-button
                      class="ele-btn-icon"
                      size="small"
                      @click="addAll"
                    >
                      全部添加
                    </el-button>
                  </el-col>
                </el-row>
              </template>
              <template v-slot:action="{ row }">
                <el-button size="mini" @click="add(row)">添加</el-button>
              </template>
            </ele-pro-table>
          </el-col>
          <el-col v-bind="styleResponsive ? { md: 12 } : { span: 12 }">
            <!-- 已选择的用户数据表格 -->
            <ele-pro-table
              :datasource="chooseUsers"
              :columns="columns"
              sub-title="已选用户:"
              height="535px"
              emptyText="未选择用户"
              :toolkit="[]"
              layout="total, prev, pager, next, jumper"
            >
              <template v-slot:toolkit>
                <el-button
                  type="primary"
                  class="ele-btn-icon"
                  :loading="loading"
                  size="small"
                  @click="save"
                >
                  保存已选用户
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  plain
                  class="ele-btn-icon"
                  @click="removeAll"
                >
                  全部移除
                </el-button>
              </template>
              <template v-slot:action="{ row }">
                <el-button type="danger" plain size="mini" @click="remove(row)">
                  移除
                </el-button>
              </template>
            </ele-pro-table>
          </el-col>
        </el-row>
      </el-card>
    </div>
  </ele-modal>
</template>

<script>
  import { listUsers } from '@/api/institution/organization-user';
  import { listTeamUser } from '@/api/institution/team-user';
  import { addGroupsUser } from '@/api/sylive/groups-user';

  export default {
    name: 'groupsUserAdd',
    props: {
      // 全部机构
      organizationList: Array,
      // 全部团队
      teamList: Array,
      // 分组id
      groupsId: Number,
      // 用户来源
      userFrom: Number,
      // 活动id
      activityId: Number,
      // 弹窗是否打开
      visible: Boolean
    },
    data() {
      return {
        organizationIds: [],
        teamIds: [],
        keyword: null,
        // 加载状态
        loading: false,
        // 全部用户
        classes: [],
        // 已选择的用户数据
        chooseUsers: [],
        // 表格列配置
        columns: []
      };
    },
    computed: {
      /* 未选择的用户数据 */
      unChooseUsers() {
        return this.classes.filter((d) => this.chooseUsers.indexOf(d) === -1);
      },
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      }
    },
    created() {},
    methods: {
      /* 获取机构用户 */
      search() {
        if (this.userFrom == 1) {
          this.queryTeam();
        } else {
          this.query();
        }
      },
      /* 获取机构用户 */
      query() {
        if (this.organizationIds.length <= 0 && !this.keyword) {
          this.$message.error('请选择机构/姓名或手机');
          return;
        }
        if (this.keyword) {
          this.organizationIds = [];
        }
        listUsers({
          activityId: this.activityId,
          organizationIds: this.organizationIds,
          keyword: this.keyword
        })
          .then((data) => {
            this.classes = [];
            if (this.chooseUsers.length > 0) {
              data.forEach((item) => {
                let choose = false;
                this.chooseUsers.forEach((d) => {
                  if (item.userId == d.userId) {
                    choose = true;
                  }
                });
                if (!choose) {
                  this.classes.push(item);
                }
              });
            } else {
              this.classes = data;
            }
          })
          .catch((e) => {
            this.$message.error(e.message);
          });
      },
      /* 获取团队用户 */
      queryTeam() {
        if (this.teamIds.length <= 0 && !this.keyword) {
          this.$message.error('请选择团队/姓名或手机');
          return;
        }
        if (this.keyword) {
          this.teamIds = [];
        }
        listTeamUser({
          activityId: this.activityId,
          teamIds: this.teamIds,
          keyword: this.keyword
        })
          .then((data) => {
            this.classes = [];
            if (this.chooseUsers.length > 0) {
              data.forEach((item) => {
                let choose = false;
                this.chooseUsers.forEach((d) => {
                  if (item.userId == d.userId) {
                    choose = true;
                  }
                });
                if (!choose) {
                  this.classes.push(item);
                }
              });
            } else {
              this.classes = data;
            }
          })
          .catch((e) => {
            this.$message.error(e.message);
          });
      },
      /* 添加 */
      add(row) {
        if (row.groups == 1) {
          this.$message.error('此用户已添加过分组了');
          return;
        }
        this.chooseUsers.push(row);
      },
      /* 移除 */
      remove(row) {
        this.chooseUsers.splice(this.chooseUsers.indexOf(row), 1);
      },
      /* 添加全部 */
      addAll() {
        this.unChooseUsers.forEach((d) => {
          if (d.groups == 0) {
            this.chooseUsers.push(d);
          }
        });
      },
      /* 移除所有 */
      removeAll() {
        this.chooseUsers.splice(0, this.chooseUsers.length);
      },
      save() {
        if (this.chooseUsers.length <= 0) {
          this.$message.error('未选择用户');
          return;
        }
        addGroupsUser({
          groupsId: this.groupsId,
          userFrom: this.userFrom,
          activityId: this.activityId,
          chooseUsers: this.chooseUsers
        })
          .then((msg) => {
            this.loading = false;
            this.$message.success(msg);
            this.updateVisible(false);
            this.$emit('done');
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
      },
      /* 更新visible */
      updateVisible(value) {
        this.$emit('update:visible', value);
      }
    },
    watch: {
      visible(visible) {
        this.columns = [
          {
            columnKey: 'action',
            label: '操作',
            width: 100,
            align: 'center',
            slot: 'action'
          },
          {
            prop: 'uname',
            label: '姓名',
            showOverflowTooltip: true,
            minWidth: 100
          },
          {
            prop: 'mobile',
            label: '手机号',
            showOverflowTooltip: true,
            minWidth: 100
          },
          {
            prop: this.userFrom == 0 ? 'organizationName' : 'teamName',
            label: this.userFrom == 0 ? '机构' : '团队',
            showOverflowTooltip: true,
            minWidth: 150
          }
        ];
        if (visible) {
          //
        } else {
          this.organizationIds = [];
          this.teamIds = [];
          this.keyword = null;
          this.classes = [];
          this.chooseUsers = [];
        }
      }
    }
  };
</script>
