<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="主键ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入主键ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户账号" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户账号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上级ID" prop="superisuperiorUuidorId">
        <el-input
          v-model="queryParams.superiorUuid"
          placeholder="请输入上级ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="用户状态" clearable style="width: 240px">
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="归属部门" prop="deptId">
        <treeselect
          v-model="queryParams.deptId"
          :options="deptOptions"
          :normalizer="deptNormalizer"
          placeholder="全部"
          clearable
          style="width: 220px"
        />
      </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="['ai: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="['ai:user:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ai:user:export']"
        >导出</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="主键ID" align="center" prop="id" width="90" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="用户账号" align="center" prop="username" />
      <el-table-column label="上级ID" align="center" prop="superiorUuid" />
      <el-table-column label="上级账号" align="center" prop="superiorName" />
      <el-table-column label="用户昵称" align="center" prop="nickname" />
      <el-table-column label="归属部门" align="center" prop="deptName" width="120" show-overflow-tooltip />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="性别" align="center" prop="gender">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.gender === 1">男</el-tag>
          <el-tag v-else type="danger">女</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" key="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="邀请码" align="center" prop="invitationCode" />
      <el-table-column label="登录时间" align="center" prop="loginTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.loginTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="余额" align="center" prop="balance" />
      <el-table-column label="source" align="center" prop="source" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="310">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-office-building"
            @click="handleOpenAssignDept(scope.row)"
            v-hasPermi="['ai:user:edit']"
          >分配部门</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="updatePassword(scope.row)"
            v-hasPermi="['ai:user:edit']"
          >修改密码</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="updateBalance(scope.row)"
            v-hasPermi="['ai:user:remove']"
          >修改余额</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ai:user:remove']"
          >删除</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"
    />

    <!-- 添加或修改ai-用户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="520px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="88px">
        <el-form-item label="用户账号" prop="username">
          <el-input
            v-model="form.username"
            placeholder="门户登录账号，必填"
            :disabled="form.id != null"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            show-password
            :placeholder="form.id != null ? '不填表示不修改密码' : '请输入登录密码'"
            autocomplete="new-password"
          />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-input v-model="form.gender" placeholder="请输入性别：1-男，2-女" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            clearable
            v-model="form.birthday"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择生日"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="余额" prop="balance">
          <el-input v-model="form.balance" placeholder="请输入余额" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </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>

    <!-- 修改密码对话框 -->
    <el-dialog :title="title" :visible.sync="openUpdatePassword" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpdatePassword">确 定</el-button>
        <el-button @click="cancelPassword">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配部门 -->
    <el-dialog title="分配归属部门" :visible.sync="assignDeptOpen" width="480px" append-to-body @close="cancelAssignDept">
      <el-form label-width="88px">
        <el-form-item label="归属部门">
          <treeselect
            v-model="assignForm.deptId"
            :options="deptOptions"
            :normalizer="deptNormalizer"
            placeholder="不选则不归属任何部门"
            clearable
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAssignDept">确 定</el-button>
        <el-button @click="cancelAssignDept">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改余额对话框 -->
    <el-dialog :title="title" :visible.sync="openUpdateBalance" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="余额" prop="balance">
          <el-input v-model="form.balance" placeholder="请输入余额" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleChangeBalance">确 定</el-button>
        <el-button @click="cancelBalance">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  changeBalance,
  changeUserStatus,
  updatePassword,
  assignAiUserDept
} from "@/api/ai/user";
import { listDept } from "@/api/ai/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // ai-用户信息表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openUpdatePassword: false,
      openUpdateBalance: false,
      assignDeptOpen: false,
      deptOptions: [],
      assignForm: {
        id: null,
        deptId: null
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickname: null,
        gender: null,
        avatar: null,
        phone: null,
        password: null,
        openid: null,
        status: null,
        email: null,
        birthday: null,
        invitationCode: null,
        paymentUrl: null,
        loginTime: null,
        balance: null,
        superiorName: null,
        deptId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        username: [{ required: true, message: "用户账号不能为空", trigger: "blur" }],
        password: [
          {
            validator: (rule, value, callback) => {
              if (this.form.id == null && (!value || !String(value).trim())) {
                callback(new Error("密码不能为空"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.loadDeptTree();
    this.getList();
  },
  methods: {
    loadDeptTree() {
      listDept().then(res => {
        this.deptOptions = this.handleTree(res.data, "deptId");
      });
    },
    deptNormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    handleOpenAssignDept(row) {
      getUser(row.id).then(res => {
        this.assignForm = {
          id: res.data.id,
          deptId: res.data.deptId
        };
        this.assignDeptOpen = true;
      });
    },
    submitAssignDept() {
      const payload = {
        id: this.assignForm.id,
        deptId: this.assignForm.deptId != null ? this.assignForm.deptId : null
      };
      assignAiUserDept(payload).then(() => {
        this.$modal.msgSuccess("已保存");
        this.assignDeptOpen = false;
        this.getList();
      });
    },
    cancelAssignDept() {
      this.assignDeptOpen = false;
      this.assignForm = { id: null, deptId: null };
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "updatePassword":
          this.updatePassword(row);
          break;
        case "updateBalance":
          this.updateBalance(row);
          break;
        default:
          break;
      }
    },
    updatePassword(row) {
      this.reset();
      this.form.id = row.id;
      this.title = "修改密码";
      this.openUpdatePassword = true;
    },
    submitUpdatePassword() {
      updatePassword(this.form.id, this.form.password).then(() => {
        this.$modal.msgSuccess("修改成功");
        this.openUpdatePassword = false;
      });
      return;
    },
    updateBalance(row) {
      this.reset();
      const id = row.id || this.ids;
      getUser(id).then(response => {
        this.form = response.data;
        this.openUpdateBalance = true;
        this.title = "修改余额";
      });
    },
    /** 查询ai-用户信息列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === 0 ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '""' + row.userId + '"用户吗？')
        .then(function() {
          return changeUserStatus(row.id, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function() {
          row.status = row.status === 0 ? 1 : 0;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelBalance() {
      this.openUpdateBalance = false;
      this.reset();
    },
    cancelPassword() {
      this.openUpdatePassword = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        username: null,
        nickname: null,
        gender: null,
        avatar: null,
        phone: null,
        password: null,
        openid: null,
        status: null,
        email: null,
        birthday: null,
        invitationCode: null,
        paymentUrl: null,
        loginTime: null,
        balance: null,
        superiorId: 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 = "添加ai-用户信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getUser(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改ai-用户信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            const payload = { ...this.form };
            if (!payload.password || !String(payload.password).trim()) {
              delete payload.password;
            }
            updateUser(payload).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleChangeBalance() {
      changeBalance;
      this.$refs["form"].validate(valid => {
        changeBalance(this.form.id, this.form.balance).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.openUpdateBalance = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row && row.id != null ? row.id : this.ids;
      if (ids == null || (Array.isArray(ids) && !ids.length)) {
        this.$modal.msgWarning("请选择要删除的数据");
        return;
      }
      const idParam = Array.isArray(ids) ? ids.join(",") : ids;
      this.$modal
        .confirm('是否确认删除ai-用户信息编号为"' + idParam + '"的数据项？')
        .then(() => {
          return delUser(idParam);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "ai/user/export",
        {
          ...this.queryParams
        },
        `user_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>
