<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="专家姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入专家姓名"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="审核状态"
          clearable
          size="small"
          style="width: 240px"
          @clear="delete queryParams.status"
        >
          <el-option label="已通过" :value="1" />
          <el-option label="未通过" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属站点" prop="tenant_id" v-if="is_super">
        <el-cascader
          size="small"
          style="width: 240px"
          v-model="queryParams.tenant_id"
          clearable
          separator="-"
          placeholder="请选择，支持搜索"
          :options="tenantOptions"
          filterable
          :props="{ emitPath: false, value: 'id', label: 'name' }"
        ></el-cascader>
      </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-table v-loading="loading" :data="userList">
      <el-table-column
        label="数据编号"
        align="center"
        key="id"
        prop="id"
        v-if="columns[0].visible"
      />
      <!-- <el-table-column
            label="专家账号"
            align="center"
            key="account"
            prop="account"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
          /> -->
      <el-table-column
        label="专家姓名"
        align="center"
        key="name"
        prop="name"
        v-if="columns[1].visible"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="状态"
        align="center"
        key="status"
        v-if="columns[4].visible"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.status == 1">正常</span>
          <span v-else>停用</span>
          <!-- <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="2"
                @change="handleStatusChange(scope.row)"
              ></el-switch> -->
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="created_at"
        v-if="columns[5].visible"
        width="160"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.created_at) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope" v-if="scope.row.id !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            v-if="scope.row.is_admin !== 1"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-key"
            @click="handleResetPwd(scope.row)"
            >重置</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page_num"
      :limit.sync="queryParams.page_size"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
} from "@/api/system/user";
import { roleSelect } from "@/api/system/role";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import { tenantSelect } from "@/api/subPlatform/tenant";

export default {
  components: { Treeselect },
  data() {
    return {
      is_super: this.$store.getters.is_super,
      tenantOptions: [], // 站点
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 专家表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      name: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "name",
      },
      // 专家导入参数
      upload: {
        // 是否显示弹出层（专家导入）
        open: false,
        // 弹出层标题（专家导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的专家数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { "x-token": getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData",
      },
      // 查询参数
      queryParams: {
        page_num: 1,
        page_size: 10,
        name: undefined,
        mobile: undefined,
        status: undefined,
        department_ids: [],
      },
      // 列信息
      columns: [
        { key: 0, label: `专家编号`, visible: true },
        { key: 1, label: `专家姓名`, visible: true },
        // { key: 2, label: `专家账号`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true },
      ],
      // 表单校验
      rules: {
        name: [
          { required: true, message: "专家姓名不能为空", trigger: "blur" },
        ],
        account: [
          { required: true, message: "专家账号不能为空", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "专家姓名长度必须介于 2 和 20 之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "专家密码不能为空", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "专家密码长度必须介于 5 和 20 之间",
            trigger: "blur",
          },
        ],
        email: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        mobile: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    name(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
    this.getTreeselect();
    this.getRoleSelect();
    tenantSelect().then((res) => {
      for (const key in res.data) {
        if (Object.hasOwnProperty.call(res.data, key)) {
          const item = res.data[key];
          this.tenantOptions.push(item);
        }
      }
    });
  },
  methods: {
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    /** 查询专家列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then((response) => {
        this.userList = response.data.data;
        this.total = response.data.count;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    /** 查询角色下拉结构 */
    getRoleSelect() {
      roleSelect().then((response) => {
        this.roleOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data, e) {
      this.queryParams.department_ids = [];
      this.queryParams.department_ids.push(data.id);
      this.getAllChild(data);
      this.getList();
    },
    getAllChild(obj) {
      if (Object.prototype.hasOwnProperty.call(obj, "children")) {
        for (const item of obj.children) {
          if (Object.prototype.hasOwnProperty.call(item, "children")) {
            this.queryParams.department_ids.push(item.id);
            this.getAllChild(item);
          } else {
            this.queryParams.department_ids.push(item.id);
          }
        }
        this.getAllChild(obj.children);
      } else {
        return null;
      }
    },

    // 专家状态修改
    handleStatusChange(row) {
      let text = row.status === 1 ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '""' + row.userName + '"专家吗？')
        .then(function () {
          return changeUserStatus(row.id, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === 1 ? 2 : 1;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        department_id: undefined,
        account: undefined,
        password: undefined,
        mobile: undefined,
        email: undefined,
        gender: 1,
        status: 1,
        remark: undefined,
        role_ids: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page_num = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      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 = "添加专家";
      this.form.password = this.initPassword;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // this.getTreeselect();
      const userId = row.id || this.ids;
      this.form = Object.assign({}, row);
      this.form.department_id = row.department.id;
      this.open = true;
      this.title = "修改专家";
      this.form.password = "";
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.mobile + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "专家密码长度必须介于 5 和 20 之间",
      })
        .then(({ value }) => {
          resetUserPwd({ id: row.id, password: this.md5(value) }).then(
            (response) => {
              this.$modal.msgSuccess("修改成功，新密码是：" + value);
            }
          );
        })
        .catch(() => {});
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.id;
      this.$router.push("/system/user-auth/role/" + userId);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id) {
            updateUser(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.password = this.md5(this.form.password);
            addUser(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除数据编号为"' + userIds + '"的数据项？')
        .then(function () {
          return delUser({ id: userIds });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>