<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="usercode">
        <el-input
            v-model="queryParams.usercode"
            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="mobile">
        <el-input
            v-model="queryParams.mobile"
            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="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['xq:user:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            @click="handleUserTagUpdate"
            v-hasPermi="['xq: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="用户类型" align="center" prop="userType" >
        <template v-slot="scope">
          <cai-dict-tag :options="appUserTypeList" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="标签" align="center" prop="tag">
        <template v-slot="scope">
          <cai-dict-tag :options="userTagList" :value="scope.row.tag" />
        </template>
      </el-table-column>
      <el-table-column label="编号" align="center" prop="usercode" />
      <el-table-column label="昵称" align="center" prop="nickname" />
      <el-table-column label="手机号" align="center" prop="mobile" />
      <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>
        <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="residenceCityName" show-overflow-tooltip />
      <el-table-column label="基础资料" align="center" prop="finishBaseStatus" >
        <template v-slot="scope">
          <cai-dict-tag :options="finishStatusList" :value="scope.row.finishBaseStatus" />
        </template>
      </el-table-column>
      <el-table-column label="最后登陆时间" align="center" prop="lastLoginTime" width="140"/>
      <el-table-column label="登陆IP" align="center" prop="lastLoginIp" width="125"/>
      <el-table-column label="注册时间" align="center" prop="regTime" width="140"/>
      <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="handleUpdate(scope.row)"
            v-hasPermi="['xq:user:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleInfo(scope.row)"
          >详情</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-hasPermi="['xq:user:restPwd']" command="handleResetPwd" icon="el-icon-key">重置密码</el-dropdown-item>
              <el-dropdown-item v-hasPermi="['xq:user:updateMobile']" command="handleResetMobile" icon="el-icon-phone">修改手机</el-dropdown-item>
              <el-dropdown-item v-hasPermi="['xq:user:lock']" v-if="scope.row.status === 0" command="handleUserLock" icon="el-icon-lock"><span style="color: red">封禁</span></el-dropdown-item>
              <el-dropdown-item v-hasPermi="['xq:user:unlock']" v-if="scope.row.status === 1" command="handleUserUnlock" icon="el-icon-unlock"><span style="color: blue">解封</span></el-dropdown-item>
              <el-dropdown-item v-hasPermi="['xq: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="['xq:user:bindInvite']" v-if="!scope.row.inviteId" command="handleUserBindInvite" icon="el-icon-link">绑定邀请</el-dropdown-item>
              <el-dropdown-item v-hasPermi="['xq:user:resetAvatar']" command="handleUserResetAvatar" icon="el-icon-refresh-right">重置头像</el-dropdown-item>
              <el-dropdown-item v-hasPermi="['xq:user:resetNickname']" command="handleUserResetNickname" icon="el-icon-refresh-right">重置昵称</el-dropdown-item>
              <el-dropdown-item v-hasPermi="['xq: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"
    />

    <bind-invite-dialog v-if="bindInviteDialogVisible" ref="bindInviteDialog" @refreshDataList="getList" />
    <user-info-dialog v-if="userInfoDialogVisible" ref="userInfoDialog" />
    <add-user-dialog v-if="addUserDialogVisible" ref="addUserDialog" @refreshDataList="getList" />
    <update-user-dialog v-if="updateUserDialogVisible" ref="updateUserDialog" @refreshDataList="getList" />
    <update-user-tag-dialog v-if="updateUserTagDialogVisible" ref="updateUserTagDialog" @refreshDataList="getList" />

  </div>
</template>

<script>
import {
  listUser,
  resetUserMobile,
  delUser,
  resetUserPassword,
  userUnBindInvite,
  getUser,
  userResetAvatar,
  userResetNickname,
  userLock, userUnlock
} from '@/api/xq/user'
import { appUserTypeList, finishStatusList, genderList, userStatusList, userTagList } from '@/constant/statusMap'
import BindInviteDialog from '@/views/xq/user/bind-invite-dialog.vue'
import UserInfoDialog from '@/views/xq/user/user-info-dialog.vue'
import AddUserDialog from '@/views/xq/user/add-user-dialog.vue'
import UpdateUserDialog from '@/views/xq/user/update-user-dialog.vue'
import UpdateUserTagDialog from '@/views/xq/user/update-user-tag-dialog.vue'

export default {
  name: "User",
  components: { BindInviteDialog,UserInfoDialog,AddUserDialog,UpdateUserDialog,UpdateUserTagDialog},
  data() {
    return {
      userStatusList,genderList,appUserTypeList,finishStatusList,userTagList,
      bindInviteDialogVisible: false,
      userInfoDialogVisible: false,
      addUserDialogVisible: false,
      updateUserDialogVisible: false,
      updateUserTagDialogVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户管理表格数据
      userList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        usercode: undefined,
        nickname: undefined,
        id: undefined,
        mobile: undefined,
      }
    };
  },
  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
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.addUserDialogVisible = true
      this.$nextTick(() => {
        this.$refs.addUserDialog.init()
      })
    },
    handleUserTagUpdate(){
      this.updateUserTagDialogVisible = true
      this.$nextTick(() => {
        this.$refs.updateUserTagDialog.init(this.ids)
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.updateUserDialogVisible = true
      this.$nextTick(() => {
        this.$refs.updateUserDialog.init(row)
      })
    },
    handleInfo(row) {
      this.userInfoDialogVisible = true
      this.$nextTick(() => {
        this.$refs.userInfoDialog.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;
      });
    },
    /** 重置密码按钮操作 */
    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(() => {});
    },
    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
        })
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除用户"' + row.name + '"的数据项？').then(() => {
        this.loading = true;
        return delUser(row.id);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    handleUserLock(row){
      this.$modal.confirm('是否确认封禁用户（"' + row.nickname + '"）？').then(() => {
        this.loading = true;
        return userLock(row.id);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("封禁成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    handleUserUnlock(row){
      this.$modal.confirm('是否确认解封用户（"' + row.nickname + '"）？').then(() => {
        this.loading = true;
        return userUnlock(row.id);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("解封成功");
      }).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 "handleUserLock":
          this.handleUserLock(row);
          break;
        case "handleUserUnlock":
          this.handleUserUnlock(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>
