<template>
  <div class="app-container">
    <!--form 组件-->
    <eForm ref="form" :is-add="isAdd" />
    <user-form ref="userForm"></user-form>
    <!--用户数据-->
    <!--工具栏-->
    <div class="head-container">
      <!-- 搜索 -->
      <el-input
        v-model="query.value"
        clearable
        placeholder="登录账号、用户姓名或员工号"
        style="width: 250px;"
        class="filter-item"
        @keyup.enter.native="toQuery"
      />
      <el-select
        v-model="query.userType"
        clearable
        placeholder="用户类型"
        class="filter-item"
        style="width: 130px"
      >
        <el-option
          v-for="item in userTypeOptions"
          :key="item.key"
          :label="item.display_name"
          :value="item.key"
        />
      </el-select>
      <el-select
        v-model="query.enabled"
        clearable
        placeholder="登录状态"
        class="filter-item"
        style="width: 150px"
      >
        <el-option
          v-for="item in enabledTypeOptions"
          :key="item.key"
          :label="item.display_name"
          :value="item.key"
        />
      </el-select>
      <el-select
        v-model="query.role"
        clearable
        placeholder="用户角色"
        class="filter-item"
        style="width: 130px"
      >
        <el-option
          v-for="item in roleOptions"
          :key="item.key"
          :label="item.display_name"
          :value="item.key"
        />
      </el-select>
      <!-- <el-select v-model="query.auditStatus" clearable placeholder="审核状态" class="filter-item" style="width: 130px">
        <el-option v-for="item in auditStatusOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select> -->
      <el-button
        class="filter-item"
        size="mini"
        type="success"
        icon="el-icon-search"
        @click="toQuery"
        >搜索</el-button
      >
      <!-- 新增 -->
      <!--
        v-permission="['ADMIN','USER_ALL','USER_CREATE']"
      -->

      <div style="display: inline-block;margin: 0px 2px;">
        <el-button
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-plus"
          @click="add"
          >新增</el-button
        >
      </div>
      <!-- 导出 -->
      <!-- <div style="display: inline-block;">
        <el-button
          v-permission="['ADMIN']"
          :loading="downloadLoading"
          size="mini"
          class="filter-item"
          type="warning"
          icon="el-icon-download"
          @click="download"
        >导出</el-button>
      </div> -->
    </div>
    <!--表格渲染-->
    <el-table
      v-loading="loading"
      :data="data"
      size="small"
      style="width: 100%;"
    >
      <el-table-column type="index" label="序号" align="center" />
      <el-table-column prop="staffNo" label="登录账号" align="center" />
      <el-table-column prop="name" label="用户姓名" align="center" />
      <el-table-column prop="upId" label="员工号" align="center" />
      <el-table-column prop="userType" label="用户类型" align="center">
        <template slot-scope="scope">
          <div>
            {{
              scope.row.userType === 1
                ? "投顾"
                : scope.row.userType === 2
                ? "非投顾"
                : ""
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="mobile" label="用户手机号" align="center">
        <template slot-scope="scope">
          <div>{{ scope.row.mobile ? scope.row.mobile : "--" }}</div>
        </template>
      </el-table-column>
      <el-table-column label="登录状态" align="center">
        <template slot-scope="scope">
          <div>{{ scope.row.status | getUserStatus }}</div>
        </template>
      </el-table-column>
      <el-table-column
        :show-overflow-tooltip="true"
        prop="deptName"
        label="所属营业部"
        align="center"
      >
        <template slot-scope="scope">
          <div>
            {{ (scope.row.deptList || []).map(item => item.name).join(",") }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center" width="230px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            v-if="scope.row.userType === 2"
            type="text"
            @click="editUserDept(scope.row)"
            >部门配置</el-button
          >
          <el-button size="mini" type="text" @click="editUser(scope.row)"
            >编辑</el-button
          >
          <el-button size="mini" type="text" @click="editPassword(scope.row)"
            >重置密码</el-button
          >
          <el-button
            v-if="scope.row.status === 3"
            size="mini"
            type="text"
            style="color: #f7ae4f"
            @click="updataStatus(1, scope.row.loginId)"
            >解除冻结</el-button
          >
          <el-button
            v-if="scope.row.status === 1"
            size="mini"
            type="text"
            style="color: #dd1e36"
            @click="updataStatus(2, scope.row.loginId)"
            >禁用</el-button
          >
          <el-button
            v-if="scope.row.status === 2"
            size="mini"
            type="text"
            style="color: #608920"
            @click="updataStatus(1, scope.row.loginId)"
            >启用</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :visible.sync="dialog"
      title="重置密码"
      append-to-body
      width="500px"
      :close-on-click-modal="false"
      @close="close"
    >
      <el-form
        ref="form"
        label-position="left"
        size="small"
        label-width="100px"
      >
        <el-form-item label="用户密码">
          <el-input
            v-model="password"
            style="width:300px;"
            :type="passwordType"
          >
            <i
              slot="suffix"
              class="el-input__icon el-icon-view"
              @click="changepPasswordType"
            ></i>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doSubmit">确认</el-button>
        <el-button type="text" @click="close">取消</el-button>
      </div>
    </el-dialog>
    <!--分页组件-->
    <el-pagination
      :total="total"
      :current-page="page + 1"
      style="margin-top: 8px;"
      layout="total, prev, pager, next, sizes"
      @size-change="sizeChange"
      @current-change="pageChange"
    />
    <DeptConfig ref="deptConfigRef" @callback="init" />
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import checkPermission from "@/utils/permission";
import { getRoleByUserId, getAll } from "@/api/role";
import { changeStatus, list, resetPassword } from "@/api/user";
import { getDepts } from "@/api/dept";
import { parseTime } from "@/utils/index";
import eForm from "./form";
import userForm from "./userForm.vue";
import { querySafety } from "@/api/systemSafety.js";
import { COMPOSITION_TYPE } from "@/utils/options";
import DeptConfig from "./components/DeptConfig.vue";
export default {
  name: "userManage",
  components: { eForm, userForm, DeptConfig },
  data() {
    return {
      isAdd: false,
      loading: true,
      data: [],
      size: 10,
      page: 0,
      query: {
        userType: null,
        auditStatus: null,
        role: null,
        value: "",
        enabled: null
      },
      time: 170,
      total: 0,
      delLoading: false,
      deptName: "",
      depts: [],
      downloadLoading: false,
      userTypeOptions: [
        { key: 1, display_name: "投顾" },
        { key: 2, display_name: "非投顾" }
      ],
      auditStatusOptions: [
        { key: 1, display_name: "待审核" },
        { key: 2, display_name: "审核通过" },
        { key: 3, display_name: "审核驳回" }
      ],
      roleOptions: [],
      enabledTypeOptions: [
        { key: 1, display_name: "启用" },
        { key: 2, display_name: "禁用" },
        { key: 3, display_name: "冻结" }
      ],
      dialog: false,
      password: "",
      loginId: "",
      passwordType: "password"
    };
  },
  computed: {
    ...mapGetters(["user"])
  },
  created() {
    this.getDeptDatas();
    this.getRoleList();
    this.$nextTick(() => {
      this.init({ current: this.page + 1, size: this.size });
    });
  },

  mounted: function() {},
  methods: {
    parseTime,
    checkPermission,
    async init(data = { current: this.page + 1, size: this.size }) {
      const res = await list(data);
      if (res.code === 0) {
        this.total = res.data.total;
        this.data = res.data.list;
      } else {
        this.$message.error(res.message);
      }
      this.loading = false;
    },
    async querySafetyFn() {
      const res = await querySafety();
      if (res.code === 0) {
        this.$store.commit("SET_SYSTEM_SAFETY", res.data);
      }
    },
    beforeInit() {
      const data = { current: this.page + 1, size: this.size };
      if (this.query.value !== null && this.query.value !== "") {
        data["keyword"] = this.query.value;
      }
      if (this.query.userType !== null && this.query.userType !== "") {
        data["userType"] = this.query.userType;
      }

      if (this.query.auditStatus !== null && this.query.auditStatus !== "") {
        data["auditStatus"] = this.query.auditStatus;
      }

      if (this.query.enabled) {
        data["status"] = this.query.enabled;
      }
      if (this.query.role !== null && this.query.role !== "") {
        data["roleId"] = this.query.role;
      }
      return data;
    },
    close() {
      this.password = "";
      this.dialog = false;
    },
    async doSubmit() {
      var regExp = new RegExp(this.$store.state.user.systemSafety.regexPattern);
      if (!this.password) {
        this.$message({
          message: "用户密码不能为空",
          type: "error"
        });
        return;
      } else if (!regExp.test(this.password)) {
        this.$message({
          message: `密码应由${this.getComposition()}组成，长度不得低于${
            this.$store.state.user.systemSafety.passwordMin
          }位且不能与前${
            this.$store.state.user.systemSafety.passwordSame
          }次密码相同`,
          type: "error"
        });
        return;
      }

      const { code, message } = await resetPassword({
        loginId: this.loginId,
        password: this.password
      });
      if (code === 0) {
        this.$notify({
          title: "重置成功",
          type: "success",
          duration: 2500
        });
        this.password = "";
        this.dialog = false;
        this.init();
      } else {
        this.$notify({
          title: message,
          type: "error",
          duration: 2500
        });
      }
    },
    getComposition() {
      const composition = this.$store.state.user.systemSafety.passwordComposition.split(
        ","
      );
      const arr = composition.map(item => {
        return COMPOSITION_TYPE[Number(item)];
      });
      return arr.join("、");
    },
    async editPassword(item) {
      this.loginId = item.loginId;
      this.dialog = true;
      // await this.querySafetyFn()
    },
    toQuery() {
      this.page = 0;
      this.init(this.beforeInit());
    },
    pageChange(e) {
      this.page = e - 1;
      this.init(this.beforeInit());
    },
    sizeChange(e) {
      this.page = 0;
      this.size = e;
      this.init(this.beforeInit());
    },
    formQuery() {
      this.init(this.beforeInit());
    },
    subDelete(user) {
      this.delLoading = true;
      const status = user.status === 1 ? 2 : 1;
      changeStatus({ userId: user.id, status })
        .then(res => {
          this.delLoading = false;
          this.$refs[user.id].doClose();
          this.init();
          const title = status === 1 ? "上架成功" : "下架成功";
          this.$notify({
            title: title,
            type: "success",
            duration: 2500
          });
        })
        .catch(err => {
          this.delLoading = false;
          this.$refs[user.id].doClose();
          console.log(err);
        });
    },
    async getRoleList() {
      const res = await getAll({ current: 1, size: 100000 });
      if (res.code === 0) {
        const options = res.data.list.map(item => {
          return { key: item.id, display_name: item.name };
        });
        this.roleOptions = options;
      } else {
        this.$message({
          message: res.message,
          type: "error",
          center: true
        });
      }
    },
    getDeptDatas() {
      const sort = "id,desc";
      const params = { sort: sort };
      if (this.deptName) {
        params["keyword"] = this.deptName;
      }
      getDepts(params).then(res => {
        this.depts = res.data;
      });
    },
    // 新增
    async add() {
      this.$refs.userForm.title = "新增";
      this.$refs.userForm.getDepts();
      this.$refs.userForm.getRoles();
      this.$refs.userForm.dialog = true;
      // await this.querySafetyFn()
    },
    // 修改用户状态
    async updataStatus(status, loginId) {
      const res = await changeStatus({ status, loginId });
      if (res.code === 0) {
        if (status === 1) {
          this.$message.success("启用成功!");
        } else {
          this.$message.success("禁用成功!");
        }
        this.init(this.beforeInit());
      } else {
        this.$message.error(res.message);
      }
    },
    // 导出
    download() {
      this.downloadLoading = true;
      import("@/utils/export2Excel").then(excel => {
        const tHeader = [
          "ID",
          "用户名",
          "电话",
          "邮箱",
          "部门",
          "状态",
          "注册日期"
        ];
        const filterVal = [
          "id",
          "name",
          "phone",
          "email",
          "deptName",
          "status",
          "createTime"
        ];
        const data = this.formatJson(filterVal, this.data);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "table-list"
        });
        this.downloadLoading = false;
      });
    },
    // 数据转换
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "createTime" || j === "lastPasswordResetTime") {
            return parseTime(v[j]);
          } else if (j === "status") {
            return v[j] === 1 ? "启用" : "禁用";
          } else {
            return v[j];
          }
        })
      );
    },
    async editUser(data) {
      console.log(data);
      const _this = this.$refs.userForm;
      _this.title = "编辑";
      _this.roleIds = [];
      Object.assign(_this.ruleForm, data);
      if (data.userType === 1) {
        _this.ruleForm.deptId = data.deptList ? data.deptList[0].id : "";
        _this.getRoles();
        _this.getDepts();
        //查询用户角色
        await getRoleByUserId({ userId: data.loginId })
          .then(res => {
            if (res.code === 0) {
              res.data.forEach(item => {
                if (item.id !== 2) {
                  _this.roleIds.push(item.id);
                }
              });
            }
          })
          .catch(err => {
            console.log(err.response.data.message);
          });
      }
      _this.dialog = true;
    },
    async edit(data) {
      this.isAdd = false;
      const _this = this.$refs.form;
      _this.status = data.status === 1;
      _this.getRoles();
      _this.getDepts();
      _this.roleIds = [];
      _this.form = {
        userId: data.id,
        name: data.name,
        deptName: data.deptName
      };
      console.log(_this.form);
      // //查询用户角色
      await getRoleByUserId({ userId: data.id })
        .then(res => {
          if (res.code === 0) {
            res.data.forEach(item => {
              if (item.id !== 2) {
                _this.roleIds.push(item.id);
              }
            });
          }
        })
        .catch(err => {
          console.log(err.response.data.message);
        });
      // data.roles.forEach(function(data, index) {
      //   _this.roleIds.push(data.id)
      // })
      _this.deptId = 1;
      _this.dialog = true;
    },
    changepPasswordType() {
      if (this.passwordType === "password") {
        this.passwordType = "text";
      } else {
        this.passwordType = "password";
      }
    },
    editUserDept(row) {
      const deptConfigComp = this.$refs.deptConfigRef;
      deptConfigComp.loginId = row.loginId;
      deptConfigComp.dialog = true;
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .span-ellipsis {
  display: block;
  width: 100%;
}
::v-deep .notallow {
  cursor: not-allowed;
  display: block;
  width: 100%;
  height: 100%;
}
::v-deep .treespan {
  display: block;
  width: 100%;
  height: 100%;
  font-size: 14px;
}
.el-table .cell {
  text-align: center;
}
::v-deep .el-pagination {
  display: flex;
  justify-content: flex-end;
}
</style>
