<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="systemName+'号'" prop="usercode">
        <el-input
          v-model="queryParams.usercode"
          :placeholder="'请输入'+systemName+'号'"
          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="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="性别" clearable size="small">
          <el-option
              v-for="dict in genderList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
              @keyup.enter.native="handleQuery"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-input
          v-model="queryParams.city"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['cai:user:edit']"
        >修改</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="systemName+'号'" align="center" prop="usercode" />
      <el-table-column label="昵称" align="center" prop="nickname" />
      <el-table-column label="手机号" align="center" prop="mobile" width="120"/>
      <el-table-column label="头像" align="center" prop="avatar" >
        <template v-slot="scope">
          <image-avatar :src="scope.row.avatar"/>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="gender">
        <template v-slot="scope">
          <cai-dict-tag :options="genderList" :value="scope.row.gender" />
        </template>
      </el-table-column>
      <el-table-column label="邀请人" align="center" prop="inviteId" show-overflow-tooltip width="60">
        <template v-slot="scope">
          <span v-if="!scope.row.inviteId">-</span>
          <span v-if="scope.row.inviteId">{{scope.row.inviteNickname}}({{scope.row.inviteUsercode}})</span>
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="所在城市" align="center" prop="city" />
      <el-table-column label="主播" align="center" prop="isAnchor">
        <template v-slot="scope">
          <cai-dict-tag :options="isAnchorList" :value="scope.row.isAnchor"/>
        </template>
      </el-table-column>
      <el-table-column label="会长" align="center" prop="isUnion">
        <template v-slot="scope">
          <cai-dict-tag :options="isAnchorList" :value="scope.row.isAnchor"/>
        </template>
      </el-table-column>
      <el-table-column label="自拍认证" align="center" prop="cameraStatus">
        <template v-slot="scope">
          <cai-dict-tag :options="authList" :value="scope.row.cameraStatus" />
        </template>
      </el-table-column>
      <el-table-column label="最后登陆时间" align="center" prop="lastLoginTime" width="150"/>
      <el-table-column label="登陆IP" align="center" prop="lastLoginIp" width="125"/>
      <el-table-column label="注册时间" align="center" prop="regTime" width="150"/>
<!--      <el-table-column label="加入IP" align="center" prop="regIp" width="125"/>-->
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <cai-dict-tag :options="userStatusList" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
        <template v-slot="scope">
          <el-button
              size="mini"
              type="text"
              @click="handleInfo(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['cai:user:edit']"
          >修改</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['cai:userUnion:remove']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
<!--              <el-dropdown-item command="handleDelete" icon="el-icon-info">完整信息</el-dropdown-item>-->
              <el-dropdown-item v-hasPermi="['cai:user:restPwd']" command="handleResetPwd" icon="el-icon-key">重置密码</el-dropdown-item>
              <el-dropdown-item v-hasPermi="['cai:user:updateMobile']" command="handleResetMobile" icon="el-icon-phone">修改手机</el-dropdown-item>
              <el-dropdown-item v-hasPermi="['cai:user:lock']" command="handleUserForbid" icon="el-icon-lock">封禁</el-dropdown-item>
              <el-dropdown-item v-hasPermi="['cai:user:unBindInvite']" v-if="scope.row.inviteId" command="handleUserUnBindInvite" icon="el-icon-unlock"><span style="color: red">解绑邀请</span></el-dropdown-item>
              <el-dropdown-item v-hasPermi="['cai:user:bindInvite']" v-if="!scope.row.inviteId" command="handleUserBindInvite" icon="el-icon-link">绑定邀请</el-dropdown-item>
              <el-dropdown-item v-hasPermi="['cai:user:resetAvatar']" command="handleUserResetAvatar" icon="el-icon-refresh-right">重置头像</el-dropdown-item>
              <el-dropdown-item v-hasPermi="['cai:user:resetNickname']" command="handleUserResetNickname" icon="el-icon-refresh-right">重置昵称</el-dropdown-item>
              <el-dropdown-item v-hasPermi="['cai:user:remove']" command="handleDelete" icon="el-icon-delete" ><span style="color: red">删除</span></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

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

    <user-add-update-dialog v-if="userAddUpdateDialogVisible" ref="userAddUpdateDialog" @refreshDataList="getList" />
    <user-info-dialog v-if="userInfoDialogVisible" ref="userInfoDialog" />
    <user-forbid-dialog v-if="userForbidVisible" ref="userForbid" @refreshDataList="getList" />
    <bind-invite-dialog v-if="bindInviteDialogVisible" ref="bindInviteDialog" @refreshDataList="getList" />
  </div>
</template>

<script>
import {
  delUser,
  getFullUser, getUser,
  listUser,
  resetUserMobile,
  resetUserPassword,
  userResetAvatar,
  userResetNickname, userUnBindInvite
} from '@/api/cai/user'
import {authList, genderList, isAnchorList, userStatusList, videoStatusList} from '@/constant/statusMap'
import UserAddUpdateDialog from '@/views/cai/user/user-add-update-dialog.vue'
import UserInfoDialog from "@/views/cai/user/user-info-dialog";
import UserForbidDialog from "@/views/cai/user/user-forbid-dialog";
import BindInviteDialog from '@/views/cai/user/bind-invite-dialog.vue'

export default {
  name: "User",
  components:{
    UserForbidDialog,BindInviteDialog,
    UserAddUpdateDialog,UserInfoDialog
  },
  data() {
    return {
      genderList,authList,userStatusList,isAnchorList,videoStatusList,
      systemName: process.env.VUE_APP_SYSTEM_HOME,
      userForbidVisible: false,
      bindInviteDialogVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        usercode: undefined,
        nickname: undefined,
        mobile: undefined,
        gender: undefined,
        city: undefined,
      },
      userAddUpdateDialogVisible: false,
      userInfoDialogVisible: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    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
    },
    handleUpdate(row){
      this.userAddUpdateDialogVisible = true
      this.$nextTick(() => {
        const id = row.id || this.ids
        this.$refs.userAddUpdateDialog.init(id)
      })
    },
    handleInfo(row){
      this.userInfoDialogVisible = true
      this.$nextTick(() => {
        this.$refs.userInfoDialog.init(row.id)
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      getFullUser(row.id).then(response => {
        let user = response.data.user
        let account = response.data.account
        let anchor = response.data.anchor
        let userCount = response.data.userCount
        if(user.isUnion === 1){
          this.$modal.msgError("该用户检测为工会会长，请先解散工会后再删除用户")
          return;
        }
        let html = `<p>确认删除用户:<span style="color: red">` + user.nickname + `</span> 吗？</p>`
            + `<p>用户余额:<span style="color: red">` + account.incomeCoin + `</span></p>`
            + `<p>用户收益:<span style="color: red">` + account.totalBuyMoney + `</span></p>`
            + `<p>粉丝数:<span style="color: red">` + userCount.fansCount + `</span></p>`
        if(anchor){
          html = html + `<p style="color: red"> 并且用户为主播，是否继续删除？</p>`
        }
        html = html + `<p style="color: red">删除后将无法撤回，请谨慎操作</p>`
        this.$confirm(html, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          type: 'warning'
        }).then(() => {
          this.loading = true
          return delUser(row.id)
        }).then(() => {
          this.loading = false
          this.getList()
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        }).finally(()=>{
          this.loading = false
        })
      })
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.usercode + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间"
      }).then(({ value }) => {
        resetUserPassword({
          userId: row.id,
          password: value,
        }).then(response => {
          this.$modal.msgSuccess("修改成功，新密码是：" + value);
        });
      }).catch(() => {});
    },
    handleResetMobile(row){
      this.$prompt('请输入"' + row.nickname + '"的新手机号', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^1[0-9]{10}$/,
        inputErrorMessage: "请输入正确格式的手机号"
      }).then(({ value }) => {
        resetUserMobile({
          id: row.id,
          mobile: value,
        }).then(response => {
          this.getList()
          this.$modal.msgSuccess("修改成功，新手机号是：" + value);
        });
      }).catch(() => {});
    },
    handleUserForbid(row){
      this.userForbidVisible = true
      this.$nextTick(() => {
        this.$refs.userForbid.init(row.id)
      })
    },
    handleUserResetAvatar(row){
      this.$modal.confirm('是否确认重置用户"' + row.nickname + '"的头像？').then(() => {
        this.loading = true;
        return userResetAvatar(row.id);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("重置成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    handleUserResetNickname(row){
      this.$modal.confirm('是否确认重置用户"' + row.nickname + '"的昵称？').then(() => {
        this.loading = true;
        return userResetNickname(row.id);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("重置成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    handleUserBindInvite(row){
      this.bindInviteDialogVisible = true
      this.$nextTick(() => {
        this.$refs.bindInviteDialog.init(row.id)
      })
    },
    handleUserUnBindInvite(row){
      getUser(row.inviteId).then(response => {
        let inviteUser = response.data;
        if(!inviteUser){
          this.$modal.msgError("该用户不存在推荐人，无需解除")
          return;
        }
        let html = `<p>确认解除用户:<span style="color: cadetblue">` + row.nickname + `</span> 的推荐人？</p>`
            + `<p>推荐人蜜瓜号:<span style="color: red">` + inviteUser.usercode + `</span></p>`
            + `<p>推荐人昵称:<span style="color: red">` + inviteUser.nickname + `</span></p>`
        this.$confirm(html, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          type: 'warning'
        }).then(() => {
          this.loading = true
          return userUnBindInvite(row.id)
        }).then(() => {
          this.$modal.msgSuccess("解除成功");
          this.loading = false
          this.getList()
        }).catch(() => {
        }).finally(()=>{
          this.loading = false
        })
      })
    },
    handleCommand(command, row) {
      switch (command) {
        case "handleDelete":
          this.handleDelete(row);
          break;
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleResetMobile":
          this.handleResetMobile(row);
          break;
        case "handleUserForbid":
          this.handleUserForbid(row);
          break;
        case "handleUserResetAvatar":
          this.handleUserResetAvatar(row);
          break;
        case "handleUserResetNickname":
          this.handleUserResetNickname(row);
          break;
        case "handleUserBindInvite":
          this.handleUserBindInvite(row);
          break;
        case "handleUserUnBindInvite":
          this.handleUserUnBindInvite(row);
          break;
        default:
          break;
      }
    },
  }
};
</script>
