<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm"  
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
        <el-form-item label="人员名称" prop="userName">
          <el-input
            v-model="queryParams.userInfo"
            placeholder="请输入姓名、手机号"
            clearable
            style="width: 240px"
            @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 statusList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </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-row>

        <el-table v-loading="loading" :data="userList"> 
        <el-table-column label="姓名" align="center"  prop="nickName">
         <template slot-scope="scope">
          <a @click="handleUpdate(scope.row)" style="color: blue">{{ scope.row.nickName }}</a>
        </template>
        </el-table-column>
        <el-table-column label="手机号" align="center"  prop="phonenumber"/>
        <el-table-column label="角色" align="center">
          <template slot-scope="scope">{{formatterRoles(scope.row.roles)}}</template>
        </el-table-column>
        <el-table-column label="备注" align="center"  prop="remark"/> 
        <el-table-column label="状态" align="center"  prop="status">
          <template slot-scope="scope">
            <span v-if="scope.row.status=='0'">启用</span>
            <span v-if="scope.row.status=='1'">停用</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.userId !== 1">              
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['system:user:remove']">删除</el-button >
              <el-button v-show="scope.row.status == '1'" size="mini" type="text" icon="el-icon-edit" @click="handleStatus(scope.row,'0')"
                v-hasPermi="['system:material:edit']">启用</el-button>
              <el-button v-show="scope.row.status == '0'" size="mini" type="text" icon="el-icon-edit" @click="handleStatus(scope.row,'1')"
                v-hasPermi="['system:material:edit']">停用</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"
        />
      </el-col>
    </el-row>
    <!-- 添加或修改人员配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">        
        <el-form-item label="姓名" prop="nickName">
          <el-input  v-model="form.nickName" placeholder="请输入人员姓名" maxlength="30" />
        </el-form-item>  
        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号" maxlength="11"/>
        </el-form-item>
         <el-form-item label="角色" prop="roleIds">         
            <el-select v-model="form.roleIds" multiple placeholder="请选择" clearable>
            <el-option
              v-for="item in roleOptions"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" >
          <el-input v-model="form.email" placeholder="请输入邮箱" mmaxlength="50" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea"  placeholder="请输入内容" ></el-input>
        </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>
  </div>
</template>

<script>
import {listUser,getUser,delUser,addUser,updateUser,resetUserPwd,changeUserStatus,} from "@/api/system/user";
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 Second from '../../../components/Crontab/second.vue';
export default {
  name: "User",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  // components: { TreeselectSecond },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 人员表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 默认密码
      initPassword: undefined,     
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {
        roleIds: []
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userInfo: null,
        status: null
      },  
      // 表单校验
      rules: {
        nickName: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
        ],
        roleIds: [
          { required: true, message: "角色不能为空", trigger: "blur" },
        ],
        phonenumber: [
          {required: true,pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,message: "请输入正确的手机号码",trigger: "blur"}
        ],
      },
      statusList:[
        {value:0,label:"启用"},
        {value:1,label:"停用"}
      ]
    };
  },
  created() {
    this.getList();
    this.getConfigKey("sys.user.initPassword").then((response) => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    formatterRoles(roleList){
      let roleNames=[];
      if(roleList.length>0){
        for(let i=0;i<roleList.length;i++){          
          roleNames.push(roleList[i].roleName);          
        }
        return roleNames.join();
      }
    },
    /** 查询人员列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then((response) => {
        if(response.code=="200"){
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }        
      });
    },
    /** 启用、禁用按钮操作 */
    handleStatus(row,tag) {
      let mess="";
      let sta="";
      if(tag=='0'){
        mess="启用";
        sta="0";
      }else if(tag=='1'){
        mess="停用";
        sta="1";
      }
      this.$modal
        .confirm('是否确认' + mess + '该数据项？')
        .then(function () {
          return updateUser({id:row.userId,status:sta});
        })
        .then((response) => {
          if(response.code="200"){
            this.getList();
            this.$modal.msgSuccess('' + mess + '成功');
          }          
        })
        .catch(() => { });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        userName: null,
        nickName: null,
        password: null,
        phonenumber: null,
        email: null,
        status: "0",
        remark: null,
        roleIds: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      getUser().then((response) => {    
        if(response.code=="200"){
          this.roleOptions = response.roles;
          this.open = true;
          this.title = "添加人员";
          this.form.password = this.initPassword;
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids;
      getUser(userId).then((response) => {
        if(response.code=="200"){
          this.form = response.data;       
          this.roleOptions = response.roles;
          this.form.roleIds = response.roleIds;
          this.open = true;
          this.title = "修改人员";
          this.form.password = "";
        }
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.userName=this.form.phonenumber;
          if (this.form.userId != null) {
            updateUser(this.form).then((response) => {
              if(response.code=="200"){
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }              
            });
          } else {
            addUser(this.form).then((response) => {
              if(response.code=="200"){
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }              
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal
        .confirm('是否确认删除人员编号为"' + row.nickName + '"的数据项？')
        .then(function () {
          return delUser(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    }
  },
};
</script>
