<template>
  <page-layer>
    <template #header>
      <el-input v-model="queryConditions.name" style="width: 300px" placeholder="请输入人员姓名或工号" clearable
                prefix-icon="Search"
                @keydown.enter="clickToQuery"/>
      是否停用:
      <el-select v-model="queryConditions.whetherToDisable" style="width: 80px">
        <el-option v-for="item in dropDownSelection" :key="item.code" :value="item.code"
                   :label="item.name"></el-option>
      </el-select>
      是否有医保码:
      <el-select v-model="queryConditions.isThereAMedicalInsuranceCode" style="width: 80px">
        <el-option v-for="item in dropDownSelection" :key="item.code" :value="item.code"
                   :label="item.name"></el-option>
      </el-select>
      医保码:
      <el-input v-model="queryConditions.ybCode" style="width: 120px" clearable></el-input>
      <el-button icon="Search" type="primary" @click="clickToQuery"> 查询</el-button>
      <el-button icon="Plus" type="success" @click="addEmployees"> 添加</el-button>
    </template>
    <template #aside>
      <el-input v-model="searchDeptContent" placeholder="请输入科室名称" clearable
                @clear="queryConditions.deptCode = ''"
                prefix-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 - 20 + 'px', overflowY: 'scroll' }"
          ref="tree"
          @node-click="handleClickDeptTreeNode"
      >
      </el-tree>
    </template>
    <template #main>
      <el-table :data="users" border :height="tableHeight - 40" stripe highlight-current-row>
        <el-table-column prop="delFlag" label="停用" width="35">
          <template #default="scope">
            <span v-if="scope.row.delFlag === '1'">√</span>
          </template>
        </el-table-column>
        <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="partTimeDeptName" label="兼诊科室"/>
        <el-table-column prop="title" label="职称"></el-table-column>
        <el-table-column prop="position" label="职务"></el-table-column>
        <el-table-column prop="markName" label="在院标志"></el-table-column>
        <el-table-column prop="ifcadreName" label="干工标志"></el-table-column>
        <el-table-column prop="orderYn" label="医生处方权">
          <template #default="scope">
            <span v-if="scope.row.orderYn === '1'"> 普通处方权</span>
            <span v-else-if="scope.row.orderYn === '2'">毒麻药处方权</span>
          </template>
        </el-table-column>
        <el-table-column prop="ysjbName" label="病历级别"></el-table-column>
        <el-table-column prop="ghChargeTypeName" label="挂号号别"></el-table-column>
        <el-table-column prop="doctorXzYpName" label="限制药品级别" show-overflow-tooltip></el-table-column>
        <el-table-column prop="loginFlag" label="病区允许就诊">
          <template #default="scope">
            <span>{{ scope.row.loginFlag === '1' ? '允许' : '不允许' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="socialNo" label="身份证"></el-table-column>
        <el-table-column prop="phoneNo" label="手机号码"></el-table-column>
        <el-table-column prop="ybCode" label="医保编码"></el-table-column>
        <el-table-column label="操作" fixed="right">
          <template v-slot="scope">
            <el-button type="primary" text @click="clickToEdit(scope.$index, scope.row)">编辑</el-button>
            <br/>
            <el-button text size="small" v-if="competence" @click="viewUserRoles(scope.row)">角色</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryConditions.currentPage"
          :page-sizes="[30, 50, 75]"
          :page-size="queryConditions.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="queryConditions.total"
          style="margin-top: 5px"
      ></el-pagination>
      <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="Edit" @click="beforeAddRole">添加角色</el-button>
            <el-button type="primary" icon="Upload" @click="saveRoles">保存更改</el-button>
          </div>
        </el-footer>
      </el-dialog>
      <PersonnelInformationEditing :userInfo="userInfo"
                                   v-if="editDialog"
                                   @close="editDialog = false"
                                   :index="roleIndex"
                                   @changeTheData="changeTheData"/>
    </template>
  </page-layer>
</template>

<script setup name="UserRoleSettings">
import store from '@/store'
import {
  addNewRole,
  getAllRoles,
  getAllUsers,
  getDeptTree,
  getUserRoles,
  saveUserRoles
} from '@/api/settings/permission-settings'
import {ElMessage, ElMessageBox} from 'element-plus'
import PersonnelInformationEditing from '@/components/settings/permissions/PersonnelInformationEditing.vue'
import {needRule} from '@/utils/public'
import PageLayer from "@/layout/PageLayer";

const windowSize = store.state.app.windowSize
const tableHeight = windowSize.h - 10

const competence = needRule(1)

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

let queryConditions = $ref({
  code: '',
  deptCode: '',
  ybCode: '',
  whetherToDisable: 0,
  isThereAMedicalInsuranceCode: 9,
  pageSize: 30,
  currentPage: 1,
  total: 0,
})

let userInfo = $ref({})
let editDialog = $ref(false)
let roleIndex = $ref(-1)

const searchDeptContent = 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) => {
  searchDeptContent.value = row.name
  queryConditions.deptCode = row.code
  clickToQuery()
}

const handleSizeChange = (val) => {
  queryConditions.pageSize = val
  clickToQuery()
}
const handleCurrentChange = (val) => {
  queryConditions.currentPage = val
  getAllUsers(queryConditions).then((res) => {
    users.value = res.records
  })
}

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 clickToEdit = (index, row) => {
  editDialog = true
  userInfo = row
  roleIndex = index
}

const changeTheData = (index, data) => {
  clickToQuery()
  editDialog = false
}

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,
    })
  })
}

const clickToQuery = () => {
  queryConditions.total = 0
  queryConditions.currentPage = 1
  getAllUsers(queryConditions).then((res) => {
    users.value = res.records
    queryConditions.total = res.total
  })
}

const addEmployees = () => {
  roleIndex = -1
  editDialog = true
  userInfo = {}
}

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

const dropDownSelection = [
  {code: 0, name: '否'},
  {code: 1, name: '是'},
  {code: 9, name: '全部'},
]
</script>
