<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="nickName" v-if="isShow('nickName')">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="归属部门" prop="deptId" v-if="isShow('deptName')">
        <dept-select
          v-model="queryParams.deptId"
          placeholder="请选择归属部门"
          clearable
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item label="账号" prop="userName" v-if="isShow('nickName')">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入账号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email" v-if="isShow('email')">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入邮箱"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status" v-if="isShow('status')">
        <el-select
          v-model="queryParams.status"
          placeholder="用户状态"
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="dict in dict.type.user_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="实名状态" prop="isReal" v-if="isShow('isReal')">
        <el-select
          v-model="queryParams.isReal"
          placeholder="实名状态"
          clearable
          @change="handleQuery"
        >
          <el-option label="已实名" :value="true" />
          <el-option label="未实名" :value="false" />
        </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">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:user:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:user:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" 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 === 'userId'">
              {{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" size="mini"/>
              <dict-tag :options="dict.type.user_status" :value="d.row.status" size="mini" style="margin-left: 4px;"/>
              <br/>
              <user-link :id="d.row.userId" :text="d.row.userName" size="mini"/>
            </template>
            <template v-else-if="column.key === 'mchId'">
              <i class="el-icon-user"/>
              <user-link :id="d.row.mchId" :text="d.row.mchNickName" size="mini"/>
              <br/>
              <user-link :id="d.row.mchId" :text="d.row.mchName" size="mini"/>
            </template>
            <template v-else-if="column.key === 'deptId'">
              {{d.row.dept == null ? '' : d.row.dept.deptName}}
            </template>
            <template v-else-if="column.key === 'status'">
              <dict-tag :value="d.row.status" :options="dict.type.user_status" size="small"/>
            </template>
            <template v-else-if="column.key === 'isReal'">
              <boolean-tag :value="d.row.isReal" size="small"/>
            </template>
            <template v-else-if="column.key === 'point'">
              {{ d.row.point | fix2 | dv }} %
            </template>
            <template v-else-if="column.key === 'balance'">
              {{ d.row.balance | fix2 | dv }} 元
            </template>
            <template v-else-if="column.key === 'withdrawServiceValue'">
              <dict-tag :value="d.row.withdrawServiceType" :options="dict.type.withdraw_service_type" size="small"/>
              {{ d.row.withdrawServiceValue | fix2 | dv }}
              <template v-if="d.row.withdrawServiceType == WithdrawServiceType.FIXED">元</template>
              <template v-else-if="d.row.withdrawServiceType == WithdrawServiceType.POINT">%</template>
            </template>
            <template v-else-if="column.key === 'bonusDelay'">
              {{ d.row.bonusDelay }} 小时
            </template>
            <template v-else-if="column.key === 'roles'">
              <template v-for="(role, index) in d.row.roles">
                <el-tag :key="index" v-if="!isEmpty(role.roleName)" size="small" style="margin-right: 4px;">{{role.roleName}}</el-tag>
              </template>
            </template>
            <template v-else>
              {{d.row[column.key]}}
            </template>
          </template>
        </el-table-column>
      </template>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope" v-if="scope.row.userId !== '1'">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['system:user:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:user:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:user:remove']"
          >删除</el-button>
          <el-button
            type="text"
            icon="el-icon-present"
            size="mini"
            @click="handleOpenGift(scope.row)"
            v-has-permi="['bst:lightingNum:gift']"
          >赠送次数</el-button>

          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:user:resetPwd', 'system:user:edit']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleResetPwd" icon="el-icon-key"
                v-hasPermi="['system:user:resetPwd']">重置密码</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-form-dialog
      :visible.sync="open"
      :userId="userId"
      :user-type="userType"
      @success="getList"
      ref="userFormDialog"
    />

    <gift-lighting-dialog
      :visible.sync="openGift"
      :user-id="userId"
      :store-options="storeOptions"
      title="赠送用户爆灯次数"
      @success="getList"
    />

  </div>
</template>

<script>
import {
  changeUserStatus,
  delUser,
  listUser,
  resetUserPwd
} from '@/api/system/user'
import FormCol from '@/components/FormCol/index.vue'
import { $showColumns } from '@/utils/mixins'
import { isEmpty } from '@/utils/index'
import UserFormDialog from '@/views/system/user/components/UserFormDialog'
import DeptSelect from '@/components/Business/Dept/DeptSelect.vue'
import { UserType, WithdrawServiceType } from '@/utils/enums'
import BooleanTag from '@/components/BooleanTag/index.vue'
import UserLink from "@/views/system/user/UserLink.vue";
import GiftLightingDialog from "@/views/bst/lightingNum/components/giftLightingNumDialog.vue";
import {listStore} from "@/api/bst/store";

export default {
  name: "User",
  mixins: [$showColumns],
  dicts: ['user_status', 'sys_user_sex', 'user_employ_status', 'withdraw_service_type'],
  components: {GiftLightingDialog, UserLink, UserFormDialog, FormCol, DeptSelect, BooleanTag },
  data() {
    return {
      WithdrawServiceType,
      // 排序方式
      orderSorts: ['ascending', 'descending', null],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 是否显示弹出层
      open: false,

      openGift: false,
      // 当前编辑的用户ID
      userId: null,
      // 店铺选择列表
      storeOptions:[],
      deptName: undefined,
      // 日期范围
      dateRange: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      dialogVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: "createTime",
        isAsc: "desc",
        excludeUserId: 1,
        userName: null,
        phonenumber: null,
        status: null,
        deptId: null,
        isReal: null,
        realName: null,
        realIdCard: null
      },
      // 列信息
      columns: [
        {key: 'userId', visible: false, label: 'ID', 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: 'userName', visible: true, label: '账号', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'roles', visible: true, label: '角色', minWidth: null, sortable: true, overflow: false, align: 'center', width: '100'},
        {key: 'mchId', visible: true, label: '所属商户', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'lightingNum', visible: true, label: '爆灯次数', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'isReal', visible: true, label: '实名状态', minWidth: null, sortable: true, overflow: false, align: 'center', width: "100"},
        {key: 'deptName', visible: true, label: '归属部门', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'email', visible: false, label: '邮箱', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'loginIp', visible: true, label: '登录IP', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'loginDate', visible: true, label: '登录时间', minWidth: null, sortable: true, overflow: false, align: 'center', width: "100"},
        {key: 'createTime', visible: true, label: '创建时间', minWidth: null, sortable: true, overflow: false, align: 'center', width: "100"},
        // {key: 'agentName', visible: true, label: '所属代理', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        // {key: 'point', visible: true, label: '分成比例', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        // {key: 'withdrawServiceValue', visible: true, label: '提现服务费', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        // {key: 'bonusDelay', visible: true, label: '到账延迟', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        //{key: 'balance', 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},

      ],
      userType: null,
    };
  },
  created() {
    // 判断用户类型，若是系统用户，则不显示实名状态、真实姓名、身份证号、分成比例
    // 若是普通用户，则不显示登录账号
    this.userType = this.$route.query.userType;
    if (this.userType == UserType.ADMIN) {
      this.removeColumn(['isReal', 'realName', 'realIdCard', 'appName']);
    } else {
      this.removeColumn(['deptName']);
      // 非系统管理员，无法查看用户的提现服务费、到账延迟
      if (!this.isSysAdmin()) {
        this.removeColumn(['withdrawServiceValue', 'bonusDelay']);
      }
    }
    this.queryParams.userType = this.userType;
    this.getList();
    this.getStoreList();
  },
  methods: {
    getStoreList() {
      this.loading = true;
      listStore().then (response => {
        this.storeOptions = response.rows;
      })
    },
    handleOpenGift(row){
      this.userId = row.userId
      this.openGift = true
    },
    handleView(row) {
      this.$router.push(`/view/user/${row.userId}`);
    },
    isEmpty,
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function() {
        return changeUserStatus(row.userId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.userId = null;
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.userId = row.userId || this.ids;
      this.open = true;
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.nickName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
        inputValidator: (value) => {
          if (/<|>|"|'|\||\\/.test(value)) {
            return "不能包含非法字符：< > \" ' \\\ |"
          }
        },
      }).then(({ value }) => {
          resetUserPwd(row.userId, value).then(response => {
            this.$modal.msgSuccess("修改成功，新密码是：" + value);
          });
        }).catch(() => {});
    },
    /** 分配角色操作 */
    handleAuthRole: function(row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function() {
        return delUser(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    }
  }
};
</script>
