<!-- 
 * @Description: 人员管理
 * @Author: syy 
 * @Date: 2024-7-15
-->
<template>
  <div class="main-box">
    <TreeFilter
      ref="treeFilter"
      label="personSetName"
      id="personSetId"
      width="300px"
      :show-all="true"
      :request-api="userManageClassManageApi.page"
      @change="changeTreeFilter"
    >
      <template v-slot:header>
        <s-button suffix="班级" @click="addClass(FormOptEnum.ADD)" style="margin-bottom: 15px" />
      </template>
      <template v-slot:label="{ row }">
        <span class="custom-tree-node">
          <span>{{ row.node.label }}</span>
          <span v-if="row.node.label != '全部'">
            <a @click.stop="addClass(FormOptEnum.EDIT, row.node.data)">
              <el-icon><Edit /></el-icon>
            </a>
            <a style="margin-left: 8px" @click.stop="addDelete(row.node.data.personSetId, '删除班级')">
              <el-icon><Delete /></el-icon>
            </a>
            <a style="margin-left: 8px" @click.stop>
              <el-dropdown @command="handleCommandTree">
                <el-link :underline="false" :icon="More"> </el-link>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item v-if="!row.node.data.userId" :command="commander(row.node.data, cmdEnumTree.AddTeacher)">
                      {{ cmdEnumTree.AddTeacher }}
                    </el-dropdown-item>
                    <el-dropdown-item v-if="row.node.data.userId" :command="commander(row.node.data, cmdEnumTree.UpdateTeacher)">
                      {{ cmdEnumTree.UpdateTeacher }}
                    </el-dropdown-item>
                    <el-dropdown-item v-if="row.node.data.userId" :command="commander(row.node.data, cmdEnumTree.DeleteTeacher)">
                      {{ cmdEnumTree.DeleteTeacher }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </a>
          </span>
        </span>
      </template>
    </TreeFilter>
    <div class="table-box">
      <ProTable ref="proTable" title="人员管理" :columns="columns" rowKey="personId" :request-api="userManagePersonnelApi.page">
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <s-button v-auth="userPerButtonCode.add" suffix="人员" @click="onOpen(FormOptEnum.ADD, { personSetId: personSetId })" />
          <s-button
            v-auth="userPerButtonCode.delete"
            type="danger"
            :opt="FormOptEnum.DELETE"
            plain
            suffix="人员"
            :disabled="!scope.isSelected"
            @click="onDelete(scope.selectedListIds, '删除所选人员')"
          />
        </template>
        <!-- 表格操作栏 -->
        <template #operation="scope">
          <el-space>
            <s-button v-auth="userPerButtonCode.edit" link :opt="FormOptEnum.EDIT" @click="onOpen(FormOptEnum.EDIT, scope.row)" />
            <s-button v-auth="userPerButtonCode.delete" link :opt="FormOptEnum.DELETE" @click="onDelete([scope.row.personId], `删除人员`)" />
            <el-dropdown @command="handleCommand">
              <el-link type="primary" :underline="false" :icon="ArrowDown"> 更多 </el-link>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="command(scope.row, cmdEnum.AddFace)"
                    ><el-upload
                      ref="upload"
                      class="upload-demo"
                      action="/api/business/personApi/uploadFile"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccess"
                      accept=".jpg, .jpeg, .png"
                      :headers="{
                        Authorization: `${TokenEnum.TOKEN_PREFIX} ${accessToken}`
                      }"
                    >
                      <template #trigger>
                        {{ cmdEnum.AddFace }}
                      </template>
                    </el-upload>
                  </el-dropdown-item>
                  <el-dropdown-item :command="command(scope.row, cmdEnum.UnderpantsUnBinding)">
                    {{ cmdEnum.UnderpantsUnBinding }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-space>
        </template>
      </ProTable>
    </div>
    <!-- 人员新增/编辑表单 -->
    <Form ref="formRef"></Form>
    <!-- 班级新增/编辑表单 -->
    <FormClass ref="formRefC" />
    <!-- 班主任绑定/修改 -->
    <FormTeacher ref="formRefT" />
    <!-- 预览头像 -->
    <el-dialog v-model="visible" title="查看头像" width="830px" :before-close="handleClose">
      <div style="display: flex; align-items: center; justify-content: center">
        <img style="max-width: 100%; max-height: 600px" class="detailpic" :src="faceUrl" alt="" />
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="tsx" name="SysUserPersonnel">
import { userManagePersonnelApi,userPerButtonCode,SysUserPersonnel,userManageClassManageApi,userManageTeacherApi } from "@/api";
import { useHandleData } from "@/hooks/useHandleData";
import { FormOptEnum } from "@/enums";
import Form from "./components/form/index.vue";
import FormClass from "./components/formClass/index.vue";
import FormTeacher from "./components/formTeacher/index.vue";
import { ArrowDown,More } from "@element-plus/icons-vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { useUserStore } from "@/stores/modules";
import { TokenEnum } from "@/enums";
import type { UploadProps } from "element-plus";
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const faceUrl = ref('');
const visible = ref(false); //是否显示人员表单
const proTable = ref<ProTableInstance>();
const treeFilter = ref<InstanceType<typeof TreeFilter> | null>(null);
const userStore = useUserStore();
const { accessToken } = userStore;
// 表格配置项
const columns: ColumnProps<SysUserPersonnel.SysUserPerInfo>[] = [
  { type: "selection", fixed: "left", width: 50 },
  {
    prop: "faceUrl",
    label: "人脸",
    render: scope => {
      return (
        <img src={scope.row.faces.length > 0 ? scope.row.faces[0].faceUrl : ''} onClick={() => viewHeadImage(scope)} style='width:50px;height:50px;' alt=''/>
      );
    }
  },
  {
    prop: "name",
    label: "姓名"
  },
  {
    prop: "personId",
    label: "人员ID"
  },
  {
    prop: "phone",
    label: "手机号"
  },
  {
    prop: "personSetName",
    label: "所属班级",
  },
  { prop: "operation", label: "操作", width: 250, fixed: "right" }
];
const viewHeadImage = (scope: any) => {
  faceUrl.value = scope.row.faces[0].faceUrl;
  visible.value = true
  console.log(faceUrl);
};
const handleClose = () => {
  visible.value = false;
};


// 人员表单引用
const formRef = ref<InstanceType<typeof Form> | null>(null);
// 班级表单引用
const formRefC = ref<InstanceType<typeof FormClass> | null>(null);
// 班级表单引用
const formRefT = ref<InstanceType<typeof FormTeacher> | null>(null);

/**
 * 打开表单
 * @param opt  操作类型
 * @param record  记录
 */
function onOpen(opt: FormOptEnum, record: {} | SysUserPersonnel.SysUserPerInfo = {}) {
  formRef.value?.onOpen({ opt: opt, record: record, successful: RefreshTable });
}

/**
 * 打开班级表单
 * @param opt  操作类型
 * @param record  记录
 */

 function addClass(opt: FormOptEnum, record: {} | SysUserPersonnel.ClassPage = {}) {
  formRefC.value?.onOpen({ opt: opt, record: JSON.parse(JSON.stringify(record)), successful: RefreshTable });
}
/**
 * 班级删除
 * @param ids  id数组
 */
 async function addDelete(id: string[],msg: string) {
  // 二次确认 => 请求api => 刷新表格
  await useHandleData(userManageClassManageApi.delete, { id }, msg);
  RefreshTable(); //刷新表格
}

/**
 * 人员删除
 * @param ids  id数组
 */
 async function onDelete(ids: string[], msg: string) {
  if(ids.length === 0){
    ElMessage({
      message: '请选择要删除的人员',
      type: 'warning'
    });
    return
  }
  // 二次确认 => 请求api => 刷新表格
  await useHandleData(userManagePersonnelApi.delete, {id: ids.join(",") }, msg);
  RefreshTable(); //刷新表格
}

// 刷新表格
const RefreshTable = () => {
  proTable.value?.refresh();
  treeFilter.value?.refresh(); //刷新树形筛选器
}


/** 更多下拉菜单命令枚举 */
enum cmdEnum {
  AddFace = "添加人脸",
  UnderpantsUnBinding = "底库解绑"
}
/** 下拉菜单参数接口 */
interface Command {
  row: SysUserPersonnel.SysUserPerInfo;
  command: cmdEnum;
}

/**配置command的参数 */
function command(row: SysUserPersonnel.SysUserPerInfo, command: cmdEnum): Command {
  return {
    row: row,
    command: command
  };
}
/**
 * 列表更多下拉菜单点击事件
 * @param command
 */
const personId = ref<number | string>(); //人员id
function handleCommand(command: Command) {
  switch (command.command) {
    case cmdEnum.AddFace:
      personId.value = command.row.personId; //获取人员id
      break
    case cmdEnum.UnderpantsUnBinding:
      userManagePersonnelApi.personUnBindDfie({
        personId:command.row.personId,
        personSetId: command.row.personSetId
      }).then(res=>{
          ElMessage.success('底库解绑成功');
          RefreshTable()
      })
      break;
  }
}



/** 更多下拉菜单命令枚举 */
enum cmdEnumTree {
  AddTeacher = "绑定班主任",
  UpdateTeacher = "修改班主任",
  DeleteTeacher = "解绑班主任",
}

/** 树下拉菜单参数接口 */
interface CommandTree {
  row: SysUserPersonnel.ClassPage;
  commander: cmdEnumTree;
}

/**配置command的参数 */
function commander(row: SysUserPersonnel.ClassPage, commander: cmdEnumTree): CommandTree {
  return {
    row: row,
    commander: commander,
  };
}
/**
 * 树更多下拉菜单点击事件
 * @param commandtree
 */
 async function handleCommandTree(commander: CommandTree) {
  switch (commander.commander) {
    case cmdEnumTree.AddTeacher:
      formRefT.value?.onOpen({ opt: commander.commander, record: commander.row, successful: RefreshTable });
      break
    case cmdEnumTree.UpdateTeacher:
      formRefT.value?.onOpen({ opt: commander.commander, record: commander.row, successful: RefreshTable });
      break;
    case cmdEnumTree.DeleteTeacher:
       // 二次确认 => 请求api => 刷新表格
      await useHandleData(userManageTeacherApi.delete, {id: commander.row.id}, '解绑教师');
      RefreshTable(); //刷新表格
    
    break;
  }
}

const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  if (response.code === 200) {
    userManagePersonnelApi.addFace({
      personId: personId.value,
      faceUrl: response.data
    }).then(res=>{
      RefreshTable()
    })
  } else {
    ElMessage.error(response.msg);
  }
};

/** 部门切换 */
const personSetId = ref<number | string>()
function changeTreeFilter(val: number | string) {
  personSetId.value = val
  proTable.value!.pageable.pageNum = 1;
  proTable.value!.searchParam.personSetId = val;
  proTable.value!.search();
}
</script>
<style scoped lang="scss">
.table-box {
  width: 100%;
  height: 100%;
}
.custom-tree-node {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  font-size: 14px;
}
</style>
