<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="拼桌名称" prop="teamName">
        <el-input
          v-model="queryParams.teamName"
          placeholder="请输入拼桌名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户角色" prop="role">
        <el-select v-model="queryParams.role" placeholder="请选择用户角色类型" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.team_user_role"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="加入方式" prop="joinType">
        <el-select v-model="queryParams.joinType" placeholder="请选择加入方式" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.team_join_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择用户状态" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.team_user_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="teamUserList" @selection-change="handleSelectionChange" :default-sort="defaultSort"  @sort-change="onSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <template v-for="column of showColumns">
        <el-table-column
            :key="column.key"
            :label="column.label"
            :prop="column.key"
            :align="column.align"
            :min-width="column.minWidth"
            :sort-orders="orderSorts"
            :sortable="column.sortable"
            :show-overflow-tooltip="column.overflow"
            :width="column.width"
        >
          <template slot-scope="d">
            <template v-if="column.key === 'id'">
              {{d.row[column.key]}}
            </template>
            <template v-else-if="column.key === 'role'">
              <dict-tag :options="dict.type.team_user_role" :value="d.row[column.key]"/>
            </template>
            <template v-else-if="column.key === 'joinType'">
              <dict-tag :options="dict.type.team_join_type" :value="d.row[column.key]"/>
            </template>
            <template v-else-if="column.key === 'nickName'">
              <i class="el-icon-user"/>
              <user-link :id="d.row.userId" :text="d.row.nickName"/>
            </template>
            <template v-else-if="column.key === 'status'">
              <dict-tag :options="dict.type.team_user_status" :value="d.row[column.key]"/>
            </template>
            <template v-else-if="column.key === 'inviterName'">
              <i class="el-icon-user" v-if="d.row.inviterId"/>
              <user-link v-if="d.row.inviterId" :id="d.row.inviterId" :text="d.row.inviterName"/>
            </template>
            <template v-else-if="column.key === 'teamName'">
              <i class="el-icon-s-custom" v-if="d.row.teamId"/>
              <team-link v-if="d.row.teamId" :id="d.row.teamId" :name="d.row.teamName"/>
            </template>
            <template v-else-if="column.key === 'storeName'">
              <i class="el-icon-takeaway-box"/>
              <store-link :id="d.row.storeId" :name="d.row.storeName"/>
            </template>
            <template v-else>
              {{d.row[column.key]}}
            </template>
          </template>
        </el-table-column>
      </template>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-remove"
            @click="handleKick(scope.row)"
            v-has-permi="['bst:teamUser:kick']"
            v-if="scope.row.status === TeamUserStatus.JOINED"
          >强制踢出</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改拼桌用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <form-col :span="span"  label="拼桌ID" prop="teamId">
            <el-input v-model="form.teamId" placeholder="请输入拼桌ID" />
          </form-col>
          <form-col :span="span"  label="用户ID" prop="userId">
            <el-input v-model="form.userId" placeholder="请输入用户ID" />
          </form-col>
          <form-col :span="span"  label="邀请人ID" prop="inviterId">
            <el-input v-model="form.inviterId" placeholder="请输入邀请人ID" />
          </form-col>
          <form-col :span="span"  label="用户角色 1-发起人 2-普通成员" prop="role">
            <el-input v-model="form.role" placeholder="请输入用户角色 1-发起人 2-普通成员" />
          </form-col>
          <form-col :span="span"  label="加入方式 1-创建拼桌 2-主动加入3-受邀加入" prop="joinType">
            <el-select v-model="form.joinType" placeholder="请选择加入方式 1-创建拼桌 2-主动加入3-受邀加入">
              <el-option
                v-for="dict in dict.type.team_join_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </form-col>
          <form-col :span="span"  label="状态 1-已加入 2-已退出" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in dict.type.team_user_status"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </form-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listTeamUser, getTeamUser, delTeamUser, addTeamUser, updateTeamUser, kick} from "@/api/bst/teamUser";
import { $showColumns } from '@/utils/mixins';
import FormCol from "@/components/FormCol/index.vue";
import UserLink from "@/views/system/user/UserLink.vue";
import {TeamStatus, TeamUserStatus} from "@/utils/constants";
import StoreLink from "@/views/bst/store/StoreLink.vue";
import TeamLink from "@/views/bst/team/TeamLink.vue";

  // 默认排序字段
const defaultSort = {
  prop: "createTime",
  order: "descending"
}

export default {
  name: "TeamUser",
  computed: {
    TeamUserStatus() {
      return TeamUserStatus
    },
    TeamStatus() {
      return TeamStatus
    }
  },
  mixins: [$showColumns],
  props: {
    query: {
      type: Object,
      default: () => ({})
    }
  },
  dicts: ['team_join_type', 'team_user_status',"team_user_role"],
  components: {TeamLink, StoreLink, UserLink, FormCol},
  data() {
    return {
      span: 24,
      // 字段列表
      columns: [
        {key: 'teamName', visible: true, label: '拼桌名称', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'nickName', visible: true, label: '用户名称', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'joinType', visible: true, label: '加入方式', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'role', visible: true, label: '用户角色', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'status', visible: true, label: '状态', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'storeName', visible: true, label: '所属店铺', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'inviterName', visible: true, label: '邀请人', minWidth: null, sortable: true, overflow: false, align: 'center', width: "120"},
        {key: 'createTime', visible: true, label: '加入时间', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
      ],
      // 排序方式
      orderSorts: ['ascending', 'descending', null],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 拼桌用户表格数据
      teamUserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      defaultSort,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: defaultSort.prop,
        isAsc: defaultSort.order,
        teamId: null,
        userId: null,
        inviterId: null,
        role: null,
        joinType: null,
        status: null,
        teamName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        teamId: [
          { required: true, message: "拼桌ID不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.queryParams = {
      ...this.queryParams,
      ...this.query
    }
    this.getList();
  },
  methods: {
    /** 当排序按钮被点击时触发 **/
    onSortChange(column) {
      if (column.order == null) {
        this.queryParams.orderByColumn = defaultSort.prop;
        this.queryParams.isAsc = defaultSort.order;
      } else {
        this.queryParams.orderByColumn = column.prop;
        this.queryParams.isAsc = column.order;
      }
      this.getList();
    },
    /** 查询拼桌用户列表 */
    getList() {
      this.loading = true;
      listTeamUser(this.queryParams).then(response => {
        this.teamUserList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        teamId: null,
        userId: null,
        inviterId: null,
        role: null,
        joinType: null,
        status: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加拼桌用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTeamUser(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改拼桌用户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTeamUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTeamUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除拼桌用户编号为"' + ids + '"的数据项？').then(function() {
        return delTeamUser(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 强制踢出按钮操作 */
    handleKick(row) {
      const teamId = row.teamId;
      const userId = row.userId;
      this.$modal.confirm('是否确认踢出id为"' + userId + '"的用户？').then(function() {
        return kick(teamId,userId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("强制踢出成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bst/teamUser/export', {
        ...this.queryParams
      }, `teamUser_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
