<!-- 
 * @Description: 寝室管理
 * @Author: wwp
 * @Date: 2024-7-25
-->
<template>
  <div class="main-box">
    <TreeFilter
      ref="treeFilter"
      title="宿舍楼管理"
      label="name"
      id="id"
      width="300px"
      :show-all="true"
      :request-api="userManageDormitoryApi.list"
      @change="changeTreeFilter"
    >
      <template v-slot:header>
        <s-button suffix="宿舍楼" @click="addDormitory(FormOptEnum.ADD)" style="margin-bottom: 15px" />
        <el-button @click="settingTime" style="margin-bottom: 15px">归寝时间设置</el-button>
      </template>
      <template v-slot:label="{ row }">
        <span class="custom-tree-node">
          <span>{{ row.node.data.name }}</span>
          <span v-if="row.node.data.id != ''">
            <a :title="FormOptEnum.EDIT" @click.stop="addDormitory(FormOptEnum.EDIT, row.node.data)">
              <el-icon><Edit /></el-icon>
            </a>
            <a :title="FormOptEnum.DELETE" style="margin-left: 8px" @click.stop="addDelete(row.node.data.id, '删除宿舍楼')">
              <el-icon><Delete /></el-icon>
            </a>
          </span>
        </span>
      </template>
    </TreeFilter>
    <div class="table-box">
      <ProTable ref="proTable" title="寝室管理" :columns="columns" rowKey="id" :request-api="userManageDormitoryApi.page">
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <s-button v-auth="dormitoryButtonCode.add" suffix="寝室" @click="onOpen(FormOptEnum.ADD, { buildId: buildId, gender: buildGender })" />
          <s-button
            v-auth="dormitoryButtonCode.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="dormitoryButtonCode.edit" link :opt="FormOptEnum.EDIT" @click="onOpen(FormOptEnum.EDIT, scope.row)" />
            <s-button v-auth="dormitoryButtonCode.delete" link :opt="FormOptEnum.DELETE" @click="onDelete([scope.row.id], `删除寝室`)" />
            <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.AddPerson)">
                    {{ cmdEnum.AddPerson }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-space>
        </template>
      </ProTable>
      <ClassUserselector
        ref="userSelectorRef"
        :org-tree-api="userManageClassManageApi.page"
        :user-selector-api="userManagePersonnelApi.page"
        multiple
        @successful="handleChooseUser"
      >
      </ClassUserselector>
    </div>
    <!-- 寝室新增/编辑表单 -->
    <Form ref="formRef"></Form>
    <!-- 宿舍楼新增/编辑表单 -->
    <FormDormitory ref="formRefD" />
    <!-- 预览头像 -->
    <el-dialog v-model="timeVisible" title="归寝时间设置" :before-close="closeTime">
      <el-form :model="timeForm" :rules="timeRules" ref="timeFormRef" label-width="100px">
        <el-row>
          <el-col :span="16">
            <el-form-item label="功能有效期:" prop="dateArr">
              <el-date-picker
                v-model="timeForm.dateArr"
                type="daterange"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :size="size"
              />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="布防时间:" prop="timeArr">
              <el-time-picker
                v-model="timeForm.timeArr"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
                is-range
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="onTimeSubmit">提交</el-button>
          <el-button @click="closeTime">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="tsx" name="SysDormitory">
import { userManageDormitoryApi,dormitoryButtonCode,SysDormitory,userManagePersonnelApi,userManageClassManageApi,SysUser } from "@/api";
import { useHandleData } from "@/hooks/useHandleData";
import { FormOptEnum } from "@/enums";
import Form from "./components/form/index.vue";
import FormDormitory from "./components/formDormitory/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";
import { UserSelectorInstance } from "@/components/Selectors/UserSelector/interface";
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）

const proTable = ref<ProTableInstance>();
const treeFilter = ref<InstanceType<typeof TreeFilter> | null>(null);
const userStore = useUserStore();
const { accessToken } = userStore;
const defaultValue = ref("");
// 表格配置项
const columns: ColumnProps<SysDormitory.ChamberInfo>[] = [
  { type: "selection", fixed: "left", width: 50 },
  {
    prop: "name",
    label: "寝室名称"
  },
  {
    prop: "personCount",
    label: "人员数量"
  },
  {
    prop: "createTime",
    label: "创建时间"
  },
  { prop: "operation", label: "操作", width: 250, fixed: "right" }
];
const size = ref<'default' | 'large' | 'small'>('default')
const timeVisible = ref(false); //是否显示时间设置
const timeForm = reactive<any>({
  dateArr: [],
  timeArr: [],
  
});

const timeRules = ref({
  dateArr: [{ required: true, message: "请选择功能有效期", trigger: "change" }],
  timeArr: [{ required: true, message: "请选择布防时间", trigger: "change" }],
});
const timeFormRef = ref<any>(null);
const settingTime = () => {
  timeVisible.value = true;
  getTimeDetail()
};
const getTimeDetail = () => {
  userManageDormitoryApi.getReturnTime().then((res:any) => {
    let {data} = res
    timeForm.dateArr = [data.funcStart,data.funcEnd] as never[];
    timeForm.timeArr = [data.timeBegin,data.timeEnd] as never[];
  });
}
const closeTime = () => {
  timeForm.dateArr = [];
  timeForm.timeArr = [];
  
  timeVisible.value = false;
};
// 提交分组
const onTimeSubmit = () => {
  timeFormRef.value.validate((valid: any) => {
    if (valid) {
      let params: any = reactive({
        funcStart: timeForm.dateArr[0],
        funcEnd: timeForm.dateArr[1],
        timeBegin: timeForm.timeArr[0],
        timeEnd: timeForm.timeArr[1]
      });
      userManageDormitoryApi.setReturnTime(params).then((res:any) => {
          if (res.code == 200) {
            // getGroupList();
            ElMessage({
              message: res.msg,
              type: 'success'
            });
            closeTime();
          }
        });
     
    } else {
      return false;
    }
  });
};
// 确定人员
 function handleChooseUser(data: SysUser.SysUserInfo[]) {
   //组装参数
   const grantUser: SysDormitory.ChamberPersonnel = {
    // id: roleId.value,
    // grantInfoList: data.map(item => item.id) as number[] | string[],
    dormitoryId: chamberId.value,
    personIds: data.map((item:any) => item.personId) as number[] | string[],
  };
  userManageDormitoryApi.setAssignPerson(grantUser).then(res => {
    ElMessage({
      message: res.msg,
      type: 'success'
    });
    RefreshTable();
  })
}
// 寝室表单引用
const formRef = ref<InstanceType<typeof Form> | null>(null);
// 宿舍楼表单引用
const formRefD = ref<InstanceType<typeof FormDormitory> | null>(null);


/**
 * 打开表单
 * @param opt  操作类型
 * @param record  记录
 */
function onOpen(opt: FormOptEnum, record: {} | SysDormitory.ChamberInfo = {}) {
  if(!buildId.value && opt == '新增') {
    ElMessage({
      message: '请选择宿舍楼',
      type: 'warning'
    });
  } else {
    formRef.value?.onOpen({ opt: opt, record: record, successful: RefreshTable });
    
  }
  
}

/**
 * 打开宿舍楼表单
 * @param opt  操作类型
 * @param record  记录
 */

 function addDormitory(opt: FormOptEnum, record: {} | SysDormitory.DormitoryInfo = {}) {
  formRefD.value?.onOpen({ opt: opt, record: JSON.parse(JSON.stringify(record)), successful: RefreshTree });
}
/**
 * 宿舍楼删除
 * @param ids  id数组
 */
 async function addDelete(id: string[],msg: string) {
  // 二次确认 => 请求api => 刷新表格
  await useHandleData(userManageDormitoryApi.deleteDormitory, { id }, msg);
  RefreshTree(); //刷新表格
}

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

// 刷新表格
const RefreshTable = () => {
  proTable.value?.refresh();
}
// 同时刷新列表和树并恢复初始状态
const RefreshTree = () => {
  proTable.value!.pageable.pageNum = 1;
  proTable.value!.searchParam.buildId = null;
  proTable.value!.searchParam.gender =null;
  treeFilter.value?.refresh(); //刷新树形筛选器
  proTable.value!.search();
}


/** 更多下拉菜单命令枚举 */
enum cmdEnum {
  AddPerson = "添加人员",
}
/** 下拉菜单参数接口 */
interface Command {
  row: SysDormitory.ChamberInfo;
  command: cmdEnum;
}

/**配置command的参数 */
function command(row: SysDormitory.ChamberInfo, command: cmdEnum): Command {
  return {
    row: row,
    command: command
  };
}
/**
 * 列表更多下拉菜单点击事件
 * @param command
 */
 const userSelectorRef = ref<UserSelectorInstance>(); //用户选择器引用
const chamberId = ref<number | string>(); //寝室id
function handleCommand(command: Command) {
  switch (command.command) {
    case cmdEnum.AddPerson:
      // addPerson(FormOptEnum.add, command.row)
      userManageDormitoryApi.detail({ id: command.row.id }).then((res:any) => {
        userSelectorRef.value?.showSelector(res.data.personInfos); //显示用户选择器
      });
      chamberId.value = command.row.id; //获取寝室id
      break;
  }
}
// function addPerson(opt: FormOptEnum, record: {} | SysDormitory.DormitoryInfo = {}) {
//   formRefU.value?.onOpen({ opt: opt, record: record, successful: RefreshTable });
// }
/** 宿舍楼切换 */
const buildId = ref<number | string>()
const buildGender = ref<boolean>()
function changeTreeFilter(val: number | string, data: any) {
  buildId.value = data.id;
  buildGender.value = data.gender;
  proTable.value!.pageable.pageNum = 1;
  proTable.value!.searchParam.buildId = data.id;
  proTable.value!.searchParam.gender = data.gender;
  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>
