<template>
  <el-container>
    <el-main>
      <el-row :gutter="5">
        <el-col :span="6">
          <div style="height: 10px"></div>
          <el-input v-model="searchDeptContent" placeholder="请输入科室名称" clearable prefix-icon="el-icon-search"></el-input>
          <div style="height: 5px"></div>
          <el-tree
            :data="depts"
            :props="defaultProps"
            default-expand-all
            :filter-node-method="filterNode"
            :style="{ height: tableHeight + 'px', overflowY: 'scroll' }"
            ref="tree"
            @node-click="handleClickDeptTreeNode"
          >
          </el-tree>
        </el-col>
        <el-col :span="18">
          <div style="height: 10px"></div>
          <el-input v-model="searchUserContent" style="width: 300px" placeholder="请输入人员姓名或工号" clearable prefix-icon="el-icon-search"></el-input>
          <div style="height: 5px"></div>
          <el-table :data="cptUsers.slice((currentPage - 1) * pageSize, currentPage * pageSize)" :height="tableHeight - 40" stripe highlight-current-row>
            <el-table-column prop="name" label="姓名"></el-table-column>
            <el-table-column prop="code" label="编号"></el-table-column>
            <el-table-column prop="codeRs" label="工号"></el-table-column>
            <el-table-column prop="deptName" label="科室"></el-table-column>
            <el-table-column prop="title" label="职称"></el-table-column>
            <el-table-column prop="position" label="职务"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button type="text" icon="el-icon-edit" @click="viewUserRoles(scope.row)">人员角色</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[25, 50, 75]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="cptUsers.length"
            style="margin-top: 5px"
          ></el-pagination>
        </el-col>
      </el-row>
      <el-dialog title="人员角色" v-model="roleDialog">
        <div style="padding: 10px 0">
          <el-tag type="info" size="small">编号：{{ currentUser.code }}</el-tag>
          <el-tag size="small">姓名：{{ currentUser.name }}</el-tag>
          <el-tag type="warning" size="small">科室：{{ currentUser.deptName }}</el-tag>
          <el-tag type="danger" size="small">职称：{{ currentUser.title }}</el-tag>
        </div>
        <el-table ref="roleTable" :data="roles" :height="tableHeight / 2" stripe @selection-change="handleSelectRoles">
          <el-table-column type="selection"></el-table-column>
          <el-table-column prop="id" label="序号" width="60"></el-table-column>
          <el-table-column prop="name" label="角色名称"></el-table-column>
          <el-table-column prop="createDatetime" label="创建时间"></el-table-column>
          <el-table-column prop="createStaff" label="创建人"></el-table-column>
        </el-table>
        <el-footer>
          <div style="width: 100%; text-align: right; padding-top: 25px">
            <el-button type="primary" icon="el-icon-edit" @click="beforeAddRole">添加角色</el-button>
            <el-button type="primary" icon="el-icon-upload" @click="saveRoles">保存更改</el-button>
          </div>
        </el-footer>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
import { computed, onMounted, ref, watchEffect } from 'vue'
import store from '@/store'
import { addNewRole, getAllRoles, getAllUsers, getDeptTree, getUserRoles, saveUserRoles } from '@/api/settings/permission-settings'
import { ElMessage, ElMessageBox } from 'element-plus'
export default {
  setup() {
    const windowSize = store.state.app.windowSize
    const tableHeight = windowSize.h - 45

    const depts = ref([])
    const users = ref([])
    const roles = ref([])

    const cptUsers = computed(() => {
      return users.value.filter((item) => {
        return item.deptCode.indexOf(currentDeptCode.value) !== -1 && (item.name.indexOf(searchUserContent.value) !== -1 || item.codeRs.indexOf(searchUserContent.value) !== -1)
      })
    })
    const currentDeptCode = ref('')
    const searchDeptContent = ref('')
    const searchUserContent = ref('')

    const defaultProps = {
      id: 'code',
      label: 'name',
      children: 'children',
    }
    const tree = ref(null)
    watchEffect(() => {
      if (searchDeptContent.value) {
        if (tree.value) {
          tree.value.filter(searchDeptContent.value)
        }
      } else {
        if (tree.value) {
          tree.value.filter(null)
        }
      }
    })
    const filterNode = (value, data) => {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    }
    const handleClickDeptTreeNode = (row) => {
      currentDeptCode.value = row.code
    }

    const pageSize = ref(25)
    const currentPage = ref(1)
    const handleSizeChange = (val) => {
      pageSize.value = val
    }
    const handleCurrentChange = (val) => {
      currentPage.value = val
    }

    const viewUserRoles = (val) => {
      currentUser.value = val
      roleDialog.value = true
      getUserRoles(val.code).then((res) => {
        toggleSelection(res)
      })
    }

    const currentUser = ref({})
    const roleDialog = ref(false)
    const roleTable = ref(null)
    const selectedRoles = ref([])
    const handleSelectRoles = (val) => {
      selectedRoles.value = val
    }
    const toggleSelection = (rows) => {
      roleTable.value.clearSelection()
      if (rows && rows.length > 0) {
        rows.forEach((row) => {
          roles.value.forEach((role) => {
            if (row === role.id) {
              roleTable.value.toggleRowSelection(role)
            }
          })
        })
      }
    }

    const beforeAddRole = () => {
      ElMessageBox.prompt('请输入要添加的角色名称', '添加新角色', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(({ value }) => {
          addNewRole(value).then(() => {
            ElMessage({
              message: '添加成功。',
              type: 'success',
              duration: 2500,
              showClose: true,
            })
            getAllRoles().then((res) => {
              roles.value = res
            })
          })
        })
        .catch(() => {})
    }

    const saveRoles = () => {
      const param = {
        code: currentUser.value.code,
        roles: selectedRoles.value,
      }
      saveUserRoles(param).then(() => {
        roleDialog.value = false
        ElMessage({
          message: '保存成功',
          type: 'success',
          duration: 2500,
          showClose: true,
        })
      })
    }

    onMounted(() => {
      getAllUsers().then((res) => {
        users.value = res
      })
      getAllRoles().then((res) => {
        roles.value = res
      })
      getDeptTree().then((res) => {
        depts.value = res
      })
    })

    return {
      tree,
      depts,
      tableHeight,
      searchDeptContent,
      searchUserContent,
      users,
      cptUsers,
      filterNode,
      defaultProps,
      pageSize,
      currentPage,
      handleSizeChange,
      handleCurrentChange,
      viewUserRoles,
      currentUser,
      roleDialog,
      roles,
      handleClickDeptTreeNode,
      handleSelectRoles,
      saveRoles,
      roleTable,
      beforeAddRole,
    }
  },
}
</script>
