<script>
import {Delete, Edit, Search, User} from "@element-plus/icons-vue";
import {mapState,mapActions} from "vuex";
import ZooUserFormDialog from "@/components/ZooUserFormDialog.vue";
import {copy, fuzzyMatching, generateUsers, splitKeyWords} from "@/utils/common.js";


export default {
  name: "ZooUser",
  components: {ZooUserFormDialog},
  computed: {
    //返回图标
    // region
    Search() {
      return Search
    },
    User() {
      return User
    },
    Delete() {
      return Delete
    },
    Edit() {
      return Edit
    },

    // endregion

    ...mapState(["users"])
  },
  watch: {
    searchInput: {
      deep: true,
      handler(val) {
        this.searchUser();
      }
    }
  },
  data() {
    return {
      tableData: [],//用来显示在界面的数据
      searchInput: {
        auth: '',
        keyword: ''
      },
      dialog: {
        addDialogVisible: false,//添加用户对话框
        editDialogVisible: false,//编辑用户对话框
        editData: {}
      }
    }
  },
  methods: {
    ...mapActions(['getUsers']),
    showEditDialog(user) {
      // console.log('点击了编辑',user)
      //这里使用user的用户名查询后端的特定用户再赋值，这里用假数据代替一下
      this.dialog.editData = this.users.find(e => e.username === user.username)
      console.log('点击了编辑', this.dialog.editData)
      this.dialog.editDialogVisible = true
    },
    // 判断表单是否为空
    isEmpty(form) {
      if (!form.username || !form.password) {
        //返回提示
        return ElMessage({
          message: '用户名和密码不能为空',
          type: 'warning',
        })
      }
    },
    editUser(form) {
      console.log('确认编辑用户', form)
      //判断是否为空
      return this.isEmpty(form);
      //编辑失败
      if (false) {
        return ElMessage({
          message: '编辑失败',
          type: 'warning',
        })
      }
      //编辑成功
      if (false) {
        return ElMessage({
          message: '编辑成功',
          type: 'success',
        })
      }
      // 此处重新拉取数据
      this.dialog.editDialogVisible = false//添加成功关闭窗口
    },
    deleteUser(user) {
      //这里使用user的用户名查询后端的特定用户再赋值，这里用假数据代替一下
      user = this.users.find(e => e.username === user.username)
      console.log('删除用户', user)
      return ElMessageBox.confirm(
          '该操作不可撤销，是否继续？',
          '删除用户：' + user.username,
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(() => {
        //进行删除操作
        // ……
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
    },
    addUser(form) {
      console.log('添加用户', form)
      //验证是否为空
      return this.isEmpty(form);
      //添加失败
      if (false) {
        return ElMessage({
          message: '该用户已存在',
          type: 'warning',
        })
      }
      //添加成功
      if (false) {
        return ElMessage({
          message: '添加成功',
          type: 'success',
        })
      }
      // 此处重新拉取数据
      this.dialog.addDialogVisible = false//添加成功关闭窗口

    },
    searchUser() {
      console.log('用户搜索',this.searchInput)
      let searchResult = []//搜索结果数组
      //第一步匹配搜索选项，如果选择了特定用户身份
      if (typeof this.searchInput.auth ==='number') {
        this.users.forEach(e=>{
          if (e.auth === this.searchInput.auth) {
            searchResult.push(copy(e))//如果符合特定权限，则添加到搜索结果
          }
        })
      }
      else { //如果没有选择特定用户身份，代表所有数据都需要参加到下一轮的模糊搜索
        searchResult = copy(this.users)
      }

      let searchResult2 = []
      let keyset = splitKeyWords(this.searchInput.keyword)//切割关键字

      //第二步进行模糊搜索
      searchResult.forEach(e=>{
        //如果该对象能匹配上所有关键字，则添加到结果
        // console.log('开始进行模糊匹配,对象、关键字集合分别为',e,keyset)
        let is = fuzzyMatching(e,keyset);
        if (is) {
          searchResult2.push(e)
        }
        // console.log('结束模糊匹配，结果为',e,keyset,is)
      })
      searchResult = searchResult2

      this.tableData = searchResult
    },
    //鼠标悬浮显示密码
    //region
    showPassword(event,password){
      console.log('showPassword')
      event.target.innerText = password
    },
    hidePassword(event) {
      event.target.innerText = '••••••••'
    }
    //endregion
  },
  mounted() {
    this.getUsers()//获取用户数据
    this.tableData = copy(this.users);//复制一份给表格展示
  }
}
</script>

<template>
  <div id="users-root">
    <div class="select">
      <div class="left">
        <el-button type="primary" :icon="User" @click="dialog.addDialogVisible = true">创建用户</el-button>
      </div>
      <div class="right">
        <el-input
            v-model="searchInput.keyword"
            style="max-width: 300px"
            placeholder="搜索用户"
        >
          <template #prepend>
            <el-select v-model="searchInput.auth" placeholder="身份" style="width: 90px">
              <el-option label="不选择" value=""/>
              <el-option label="管理员" :value="0"/>
              <el-option label="饲养员" :value="1"/>
              <el-option label="兽医" :value="2"/>
            </el-select>
          </template>
          <template #append>
            <el-button :icon="Search" @click="searchUser()"/>
          </template>
        </el-input>
      </div>
    </div>

    <!--    <hr/>-->
    <div class="table">
      <el-table :data="tableData" style="height: 100%" empty-text="暂无数据" border>
        <el-table-column fixed prop="username" label="用户名" width="150"/>
        <!--        <el-table-column prop="password" label="密码" />-->
        <el-table-column prop="password" label="密码" width="150">
          <template #default="scope">
            <div @mouseover="showPassword($event,scope.row.password)" @mouseleave="hidePassword($event)">••••••••</div>
          </template>
        </el-table-column>
        <el-table-column prop="auth" label="身份" width="700">
          <template #default="scope">
            <span v-if="scope.row.auth===0" style="color: blue">管理员</span>
            <span v-else-if="scope.row.auth===1" style="color: green">饲养员</span>
            <span v-else-if="scope.row.auth===2" style="color: orange">兽医</span>
            <span v-else>未知</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="130">
          <template #default="scope">
            <el-button link type="primary" size="small" :icon="Edit" @click="showEditDialog(scope.row)">
              编辑
            </el-button>
            <el-button link type="danger" size="small" :icon="Delete" @click="deleteUser(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>

  <!--  添加用户对话框-->
  <el-dialog v-model="dialog.addDialogVisible" title="添加用户" width="400" align-center draggable overflow>
    <ZooUserFormDialog>
      <template #default="scope">
        <el-button @click="dialog.addDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="addUser(scope.form)">
          添加
        </el-button>
      </template>
    </ZooUserFormDialog>
  </el-dialog>

  <!--  编辑用户对话框-->
  <el-dialog v-model="dialog.editDialogVisible" title="编辑用户" width="400" align-center draggable overflow
             destroy-on-close>
    <ZooUserFormDialog :user="dialog.editData">
      <template #default="scope">
        <el-button @click="dialog.editDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="editUser(scope.form)">
          修改
        </el-button>
      </template>
    </ZooUserFormDialog>
  </el-dialog>
</template>

<style scoped>
.table {
  /*width: 1300px;*/
  height: 516px;
  margin: 0 30px;
}

.left {
  margin-left: 30px;
}

.right {
  margin-right: 30px;
}

.select {
  width: 100%;
  height: 60px;
  line-height: 60px;
}
</style>