<template>
  <div class="content-box">
    <div class="left">
      <!-- <el-icon :size="23" class="camera"><VideoCameraFilled /></el-icon> -->
      <span class="cameratxt">寝室信息管理</span>
    </div>
    <div class="scroll">
      <div class="middle">
        <div class="filter">
          <div class="condition">
            <span>校区名称 :</span>
            <el-select
              clearable
              @change="schoolChange"
              v-model="searchInput.schoolId"
              placeholder="请选择校区名称"
            >
              <el-option
                v-for="i in schoolData"
                :key="i.id"
                :label="i.school"
                :value="i.id"
              />
            </el-select>
          </div>
          <div class="condition">
            <span>楼栋名称 :</span>
            <el-select
              clearable
              v-model="searchInput.buildId"
              placeholder="请选择楼栋名称"
              @change="buildChange"
            >
              <el-option
                v-for="i in buildData"
                :key="i.id"
                :label="i.build"
                :value="i.id"
              />
            </el-select>
          </div>
          <div class="condition">
            <span>寝室号 :</span>
            <el-select
              v-model="searchInput.dormitoryId"
              placeholder="请选择寝室号"
              clearable
            >
              <el-option
                v-for="i in dormitoryData"
                :key="i.id"
                :label="i.dormitory"
                :value="i.id"
              />
            </el-select>
          </div>
          <div class="condition">
            <span>寝室性别 :</span>
            <el-select
              clearable
              v-model="searchInput.sex"
              placeholder="请选择楼栋性别"
            >
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </div>
          <div class="condition">
            <span>所属学院 :</span>
            <el-select
              @change="collegeChange"
              v-model="searchInput.collegeId"
              placeholder="请选择所属学院"
              clearable
            >
              <el-option
                v-for="i in collegeData"
                :key="i.id"
                :label="i.name"
                :value="i.id"
              />
            </el-select>
          </div>
          <!-- <div class="condition">
            <span>专业 :</span>
            <el-select
              clearable
              v-model="searchInput.majorId"
              placeholder="请选择专业"
            >
              <el-option
                v-for="i in majorData"
                :key="i.id"
                :label="i.name"
                :value="i.id"
              />
            </el-select>
          </div> -->
          <div class="condition">
            <span>入住情况 :</span>
            <el-select
              clearable
              v-model="searchInput.status"
              placeholder="请选择入住情况"
            >
              <el-option label="满员" value="1" />
              <el-option label="全空" value="2" />
              <el-option label="缺额" value="3" />
            </el-select>
          </div>
          <div class="condition">
            <span>是否保留 :</span>
            <el-select
              clearable
              v-model="searchInput.retentionState"
              placeholder="请选择是否保留"
            >
              <el-option label="是" value="2" />
              <el-option label="否" value="1" />
            </el-select>
          </div>

          <el-button
            style="margin-left: 20px"
            color="rgba(38, 151, 255, 1)"
            type="primary"
            class="search"
            @click="searchBtn"
            ><span>查询</span></el-button
          >
          <el-button @click="resetBtn" plain color="rgba(43, 153, 255, 1)"
            >重置</el-button
          >
        </div>
        <!-- 按钮列表 -->
        <div class="gongneng">
          <el-button
            v-if="store.BtnRole('dormitoryManagementSetting1')"
            type="primary"
            color="rgba(38, 151, 255, 1)"
            @click="buildImportBtn"
            >导入</el-button
          >
          <el-button
            v-if="store.BtnRole('dormitoryManagementSetting2')"
            type="primary"
            style="margin-left: 0"
            color="rgba(48, 201, 191, 1)"
            @click="buildExportbtn"
            >导出</el-button
          >
          <el-button
            v-if="store.BtnRole('dormitoryManagementSetting3')"
            type="primary"
            style="margin-left: 0"
            color="rgba(38, 151, 255, 1)"
            @click="addlist"
            >新增</el-button
          >
          <el-button
            v-if="store.BtnRole('dormitoryManagementSetting4')"
            type="primary"
            style="margin-left: 0"
            color="rgba(38, 151, 255, 1)"
            @click="batchRetainS('批量保留', 2)"
            >批量保留</el-button
          >
          <el-button
            v-if="store.BtnRole('dormitoryManagementSetting5')"
            type="primary"
            style="margin-left: 0"
            color="rgba(38, 151, 255, 1)"
            @click="batchRetainS('批量开放', 1)"
            >批量开放</el-button
          >
        </div>
      </div>
      <div class="footer" v-loading="loading">
        <el-table
          :row-class-name="tableRowClassName"
          :data="tableData.list"
          @selection-change="handleSelectionChange"
          style="width: 100%"
          :header-cell-style="{
            background: 'rgba(240, 243, 247, 1)',
            height: '50px',
            border: 0,
          }"
        >
          <el-table-column type="selection" align="center" width="55" />
          <el-table-column align="center" prop="school" label="校区名称" />
          <el-table-column align="center" prop="build" label="楼栋名称" />
          <el-table-column align="center" prop="dormitory" label="寝室号" />
          <el-table-column
            width="100"
            align="center"
            prop="sex"
            label="寝室性别"
          />
          <el-table-column align="center" prop="college" label="所属学院" />
          <!-- <el-table-column align="center" prop="major" label="专业" /> -->
          <el-table-column
            width="100"
            align="center"
            prop="bedNumber"
            label="床位数"
          />
          <el-table-column
            align="center"
            width="120"
            prop="freeBedNumber"
            label="空闲床位数"
          />
          <el-table-column
            width="100"
            align="center"
            prop="status"
            label="入住情况"
          >
            <template #default="{ row }">
              <span v-if="row.status == 1">满员</span>
              <span v-if="row.status == 2">全空</span>
              <span v-if="row.status == 3">缺额</span>
            </template>
          </el-table-column>
          <el-table-column width="100" align="center" label="是否保留">
            <template #default="{ row }">
              <span v-if="row.retentionState == 2">是</span>
              <span v-if="row.retentionState == 1">否</span>
            </template>
          </el-table-column>
          <el-table-column
            width="200"
            align="center"
            show-overflow-tooltip
            prop="remark"
            label="备注"
          />
          <el-table-column
            align="center"
            label="操作"
            fixed="right"
            width="200"
          >
            <template #default="{ row }">
              <div class="options">
                <span
                  class="open"
                  v-if="
                    row.retentionState == 1 &&
                    store.BtnRole('dormitoryManagementSetting6')
                  "
                  @click="retainS(row, 2)"
                  >保留</span
                >
                <span
                  class="open"
                  v-if="
                    row.retentionState == 2 &&
                    store.BtnRole('dormitoryManagementSetting7')
                  "
                  @click="retainS(row, 1)"
                  >开放</span
                >
                <span
                  class="edit"
                  v-if="store.BtnRole('dormitoryManagementSetting8')"
                  @click="updateS(row)"
                  >编辑</span
                >
                <span
                  class="delete"
                  v-if="store.BtnRole('dormitoryManagementSetting9')"
                  @click="deleteS(row)"
                  >删除</span
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div class="pageSize">
          <span></span>
          <el-pagination
            background
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 30, 40]"
            layout="total,sizes, prev, pager, next, jumper, slot"
            :total="total"
            @size-change="handleSizeChange"
            @update:current-page="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <!-- 添加账号弹窗 -->
    <el-dialog
      class="addStaff"
      v-model="addDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="dialongTitle"
      align-center
      width="560"
      :before-close="cancelAdd"
      destroy-on-close
      draggable
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
        :size="formSize"
        label-position="right"
        status-icon
      >
        <el-form-item label="校区名称 :" prop="school">
          <el-select
            :disabled="dialongTitle == '编辑寝室信息'"
            @change="schoolFormChange"
            v-model="ruleForm.school"
            clearable
            placeholder="请选择校区名称"
          >
            <el-option
              v-for="i in schoolData"
              :key="i.id"
              :label="i.school"
              :value="`${i.school},${i.id}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="楼栋名称 :" prop="build">
          <el-select
            :disabled="dialongTitle == '编辑寝室信息'"
            clearable
            v-model="ruleForm.build"
            placeholder="请选择楼栋名称"
            @change="buildFormChange"
          >
            <el-option
              v-for="i in buildFormData"
              :key="i.id"
              :label="i.build"
              :value="`${i.build},${i.id}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="寝室号 :" prop="dormitory">
          <el-input
            clearable
            v-model.trim="ruleForm.dormitory"
            class="w-50 m-2"
            placeholder="请输入寝室号"
          />
        </el-form-item>
        <el-form-item label="寝室性别 :" prop="sex">
          <el-select
            disabled
            v-model="ruleForm.sex"
            placeholder="请选择寝室性别"
          >
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属学院 :" prop="college">
          <el-select
            @change="collegeFormChange"
            v-model="ruleForm.college"
            clearable
            multiple
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="2"
            placeholder="请选择所属学院"
          >
            <el-option
              v-for="i in collegeData"
              :key="i.id"
              :label="i.name"
              :value="`${i.name},${i.id}`"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="专业 :" prop="major">
          <el-select
            clearable
            v-model="ruleForm.major"
            placeholder="请选择专业"
          >
            <el-option
              v-for="i in majorFormData"
              :key="i.id"
              :label="i.name"
              :value="`${i.name},${i.id}`"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="床位数 :" prop="bedNumber">
          <el-input
            v-model.trim="ruleForm.bedNumber"
            placeholder="请输入床位数"
            clearable
          />
        </el-form-item>
        <el-form-item label="备注 :" prop="remark">
          <el-input
            v-model.trim="ruleForm.remark"
            placeholder="请输入备注"
            clearable
          />
        </el-form-item>
        <el-form-item class="options">
          <el-button @click="cancelAdd">取消</el-button>
          <el-button
            color="rgba(0, 97, 255, 1)"
            class="queding"
            type="primary"
            @click="submitAdd(ruleFormRef)"
          >
            确定
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 项目导入 -->
    <el-dialog
      class="projectImport"
      v-model="buildImportVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="寝室信息导入"
      align-center
      width="600"
      :before-close="cancelProjectImport"
    >
      <!-- <p class="title">当前只支持项目类型为“非装配式建筑项目”的项目导入</p> -->
      <p class="down">
        <span>寝室信息导入模板下载</span
        ><span @click="templateDown">模板下载</span>
      </p>
      <el-upload
        class="avatar-uploader"
        action="#"
        :auto-upload="false"
        :on-remove="projectImportRemove"
        :on-change="projectImportChange"
        :before-upload="beforeAvatarProImport"
        ref="buildRef"
        :limit="1"
        :on-exceed="projectImportExceed"
      >
        <template #trigger>
          <el-button class="queding" type="primary">
            &nbsp;&nbsp;导入文件&nbsp;&nbsp;
          </el-button>
        </template>
      </el-upload>
      <div class="options">
        <el-button
          color="rgba(9, 101, 98, 1)"
          class="queding"
          type="primary"
          @click="projectImportConfirm(buildRef)"
          :loading="buildImportLoading"
        >
          &nbsp;&nbsp;确认导入&nbsp;&nbsp;
        </el-button>
        <el-button @click="cancelProjectImport"
          >&nbsp;&nbsp;取消导入&nbsp;&nbsp;</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ref,
  watch,
  reactive,
  nextTick,
  onBeforeMount,
  onUnmounted,
} from "vue";
import { useRouter } from "vue-router";
import { genFileId, ElMessage, ElMessageBox } from "element-plus";
import { dayjs } from "element-plus";
import lodash from "lodash";
import { https } from "@/utils/request"; // 绝对路径

import { storeToRefs } from "pinia";
import { useCounterStore } from "@/stores/index";

const router = useRouter();
const store = useCounterStore();

// 为避免解构时失去响应性
const { name, age, isCollapse, realAge, collegeRole } = storeToRefs(store);

// 表格数据
const loading = ref(false);
const tableData = reactive({
  list: [{}],
});
const activeIndex = ref(); // 默认跳转路由
const dialongTitle = ref("新增账号"); // 弹窗标题

const searchInput = reactive({
  schoolId: null,
  buildId: null,
  dormitoryId: null,
  sex: null,
  status: null,
  retentionState: null,
  collegeId: null,
}); // 搜索按钮数据

const currentPage = ref(1); // 当前页
const pageSize = ref(10);
const total = ref(); // 当前总数
const selectIds = ref([]); // 勾选的全部数据

const addDialogVisible = ref(false); // 控制添加账号弹窗

// 表单数据
const formSize = ref("default");
const ruleFormRef = ref();
const ruleForm = reactive({
  school: "靖安校区", //校区名称
  build: "", //楼栋名称
  dormitory: "", //寝室号
  sex: "男", //寝室性别
  college: "", //所属学院
  major: "", //所属专业
  bedNumber: "", //床位数
  // "gradestr": "",              //所属年级
  remark: "", //备注
  id: "",
});
// 表单验证
const rules = reactive({
  school: [{ required: true, message: "校区名称不能为空", trigger: "blur" }],
  build: [{ required: true, message: "楼栋名称不能为空", trigger: "blur" }],
  dormitory: [{ required: true, message: "寝室号不能为空", trigger: "blur" }],
  sex: [{ required: true, message: "寝室性别不能为空", trigger: "blur" }],
  college: [{ required: true, message: "所属学院不能为空", trigger: "blur" }],
  major: [{ required: true, message: "专业不能为空", trigger: "blur" }],
  bedNumber: [{ required: true, message: "床位数不能为空", trigger: "blur" }],
});

// 导入
const buildImportVisible = ref(false);
const buildRef = ref();
const buildFile = ref();
const buildImportLoading = ref(false);

// 校区数据
const schoolData = ref([]);
// 楼栋数据
const buildData = ref([]);
const buildFormData = ref([]);
// 寝室号数据
const dormitoryData = ref([]);
// 学院
const collegeData = ref([]);
// 专业
const majorData = ref([]);
const majorFormData = ref([]);

const schoolList = async () => {
  let res = await https.get("/welcome/api/welcome-build/schoolGroup", "params");
  console.log(res, "校区数据");
  if (res.code == 200) {
    schoolData.value = res.data;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};
const buildList = async (flag) => {
  let params = {
    schoolId: flag ? flag : searchInput.schoolId,
  };
  let res = await https.get(
    "/welcome/api/welcome-build/buildGroup",
    "params",
    params
  );
  console.log(res, "楼栋数据");
  if (res.code == 200) {
    if (flag) {
      buildFormData.value = res.data;
    } else {
      buildData.value = res.data;
    }
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};
const dormitoryList = async () => {
  let params = {
    schoolId: searchInput.schoolId,
    buildId: searchInput.buildId,
    accountId: sessionStorage.getItem("accountId"),
  };
  let res = await https.get(
    "/welcome/api/welcome-dormitory/dormitoryTGroup",
    "params",
    params
  );
  console.log(res, "寝室号数据");
  if (res.code == 200) {
    dormitoryData.value = res.data;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};
// const majorList = async (flag) => {
//   let params = {
//     collegeId: flag ? flag : searchInput.collegeId,
//   };
//   let res = await https.get(
//     "/welcome/api/welcomeOrg/getMajors",
//     "params",
//     params
//   );
//   console.log(res, "专业数据");
//   if (res.code == 200) {
//     if (flag) {
//       majorFormData.value = res.data;
//     } else {
//       majorData.value = res.data;
//     }
//   } else {
//     ElMessage({
//       type: "error",
//       showClose: true,
//       message: res.message,
//       center: true,
//     });
//   }
// };
const collegeList = async () => {
  collegeData.value = collegeRole.value;
  // let res = await https.get("/welcome/api/welcomeOrg/getColleges", "params");
  // console.log(res, "学院数据");
  // if (res.code == 200) {
  //   collegeData.value = res.data;
  // } else {
  //   ElMessage({
  //     type: "error",
  //     showClose: true,
  //     message: res.message,
  //     center: true,
  //   });
  // }
};
const schoolChange = async (val) => {
  console.log(val);
  searchInput.buildId = null;
  searchInput.dormitoryId = null;
  if (!val) {
    buildData.value = null;
    dormitoryData.value = null;
    return;
  } else {
    buildData.value = null;
    dormitoryData.value = null;
  }
  buildList();
};
const buildChange = async (val) => {
  searchInput.dormitoryId = null;
  if (!val) {
    dormitoryData.value = null;
    return;
  } else {
    dormitoryData.value = null;
  }
  dormitoryList();
};
const buildFormChange = (val) => {
  console.log(val);
  // 选择楼栋时判断是性别
  if (val) {
    buildFormData.value.forEach((i) => {
      if (i.id == val.split(",")[1]) {
        ruleForm.sex = i.sex;
      }
    });
  } else {
    ruleForm.sex = null;
  }
};

const schoolFormChange = async (val) => {
  console.log(val);
  ruleForm.build = null;
  ruleForm.sex = null;
  if (!val) {
    buildFormData.value = null;
    return;
  } else {
    buildFormData.value = null;
  }
  buildList(val.split(",")[1]);
};
const collegeChange = async (val) => {
  console.log(val);
  searchInput.majorId = null;
  if (!val) {
    majorData.value = null;
    return;
  } else {
    majorData.value = null;
  }
  // majorList();
};

// 冒泡排序
function bubbleSortById(arr) {
  const n = arr.length;
  for (let i = 0; i < n - 1; i++) {
    for (let j = 0; j < n - 1 - i; j++) {
      if (arr[j].id > arr[j + 1].id) {
        // 只改这一行
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
      }
    }
  }
  return arr;
}
const collegeFormChange = async (val) => {
  console.log(val);

  console.log(ruleForm.college);

  // ruleForm.major = null;
  // if (!val) {
  //   majorFormData.value = null;
  //   return;
  // } else {
  //   majorFormData.value = null;
  // }
  // majorList(val.split(",")[1]);
};

// 获取账户列表
const getList = async () => {
  loading.value = true;
  let params = {
    accountId: sessionStorage.getItem("accountId"),
    currentPage: currentPage.value, // 当前页
    pageCount: pageSize.value, // 一页数据条数
    schoolId: searchInput.schoolId,
    buildId: searchInput.buildId,
    dormitoryId: searchInput.dormitoryId,
    sex: searchInput.sex,
    status: searchInput.status,
    retentionState: searchInput.retentionState,
    collegeId: searchInput.collegeId ? searchInput.collegeId : "",
  };

  let res = await https.get(
    "/welcome/api/welcome-dormitory/listDormitory",
    "params",
    params
  );
  console.log(res, "查询寝室");
  if (res.code == 200) {
    tableData.list = res.data.list;
    total.value = res.data.totalCount;
    loading.value = false;
  } else {
    loading.value = false;
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};

// 搜索功能
const searchBtn = lodash.debounce(async () => {
  getList();
}, 300);
const resetBtn = lodash.debounce(async () => {
  searchInput.schoolId = null;
  searchInput.buildId = null;
  searchInput.dormitoryId = null;
  searchInput.sex = null;
  searchInput.status = null;
  searchInput.retentionState = null;
  searchInput.collegeId = null;
  buildData.value = null;
  dormitoryData.value = null;
  majorData.value = null;
  getList();
}, 300);

// 添加账号
const addlist = () => {
  dialongTitle.value = "新增寝室信息";
  addDialogVisible.value = true;
  ruleForm.school = null;
  ruleForm.build = null;
  ruleForm.dormitory = null;
  ruleForm.sex = null;
  ruleForm.college = null;
  // ruleForm.major = null;
  ruleForm.bedNumber = null;
  ruleForm.remark = null;
  ruleForm.id = null;
};
// 添加账号
const updateS = (row) => {
  console.log(row);
  dialongTitle.value = "编辑寝室信息";
  addDialogVisible.value = true;
  ruleForm.school = `${row.school},${row.schoolId}`;
  buildList(row.schoolId).then(() => {
    ruleForm.build = `${row.build},${row.buildId}`;
  });
  ruleForm.dormitory = row.dormitory;
  ruleForm.sex = row.sex;
  // collegeList().then(()=>{
  let arr=[]
  row.college.split(",").forEach((i,ind) => {
    arr.push(`${i},${row.collegeId.split(',')[ind]}`)
  });
  ruleForm.college =arr;
  // })
  // majorList(row.collegeId).then(() => {
  //   ruleForm.major = `${row.major},${row.majorId}`;
  // });
  ruleForm.bedNumber = row.bedNumber;
  ruleForm.remark = row.remark;
  ruleForm.id = row.id;
  console.log(ruleForm);
};
const deleteS = async (row) => {
  ElMessageBox.confirm("是否删除此数据?", "提示!!!", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      loading.value = true;
      let data = {
        dormitoryId: row.id, // 当前页
      };
      let res = await https.get(
        "/welcome/api/welcome-dormitory/deleteDormitory",
        "params",
        data
      );
      if (res.code == 200) {
        ElMessage({
          type: "success",
          showClose: true,
          message: res.message,
          center: true,
        });
        loading.value = false;
        getList();
      } else {
        loading.value = false;
        ElMessage({
          type: "error",
          showClose: true,
          message: res.message,
          center: true,
        });
      }
    })
    .catch(() => {
      loading.value = false;
    });
};
// 保留
const retainS = async (row, flag) => {
  let data = {
    dormitoryIds: [row.id], // 当前页
    retentionState: flag, //保留状态 1:开放，2:保留
  };
  let res = await https.post(
    "/welcome/api/welcome-dormitory/batchOperation",
    "data",
    data
  );
  if (res.code == 200) {
    ElMessage({
      type: "success",
      showClose: true,
      message: res.message,
      center: true,
    });
    getList();
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};
// 保留
const batchRetainS = async (title, flag) => {
  if (selectIds.value.length == 0) {
    ElMessage({
      type: "warning",
      showClose: true,
      message: "至少选择一条数据",
      center: true,
    });
    return;
  }
  ElMessageBox.confirm(`是否${title}数据?`, "提示!!!", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let data = {
        dormitoryIds: selectIds.value, // 当前页
        retentionState: flag, //保留状态 1:开放，2:保留
      };
      let res = await https.post(
        "/welcome/api/welcome-dormitory/batchOperation",
        "data",
        data
      );
      if (res.code == 200) {
        ElMessage({
          type: "success",
          showClose: true,
          message: res.message,
          center: true,
        });
        getList();
      } else {
        ElMessage({
          type: "error",
          showClose: true,
          message: res.message,
          center: true,
        });
      }
    })
    .catch(() => {
      loading.value = false;
    });
};

// 确认添加员工
const submitAdd = lodash.debounce(async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let arr = [];
      ruleForm.college.forEach((i) => {
        if (i) {
          arr.push({
            id: Number(i.split(",")[1]),
            name: i.split(",")[0],
          });
        }
      });
      let collegeList = bubbleSortById(arr);
      let college = [];
      let collegeId = [];
      collegeList.forEach((i) => {
        college.push(i.name);
        collegeId.push(i.id);
      });
      console.log(college.join(","), collegeId.join(","));

      let data = {
        school: ruleForm.school.split(",")[0],
        schoolId: ruleForm.school.split(",")[1],
        build: ruleForm.build.split(",")[0],
        buildId: ruleForm.build.split(",")[1],
        dormitory: ruleForm.dormitory,
        sex: ruleForm.sex,
        college: college.join(","),
        collegeId: collegeId.join(","),
        // major: ruleForm.major.split(",")[0],
        // majorId: ruleForm.major.split(",")[1],
        bedNumber: ruleForm.bedNumber,
        remark: ruleForm.remark,
        grade: dayjs().year(),
      };
      console.log(data);

      if (ruleForm.id) {
        data.id = ruleForm.id;
        let res = await https.post(
          "/welcome/api/welcome-dormitory/updateDormitory",
          "data",
          data
        );
        if (res.code == 200) {
          addDialogVisible.value = false;
          getList();
          ElMessage({
            type: "success",
            showClose: true,
            message: res.message,
            center: true,
          });
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.message,
            center: true,
          });
        }
      } else {
        let res = await https.post(
          "/welcome/api/welcome-dormitory/saveDormitory",
          "data",
          data
        );
        if (res.code == 200) {
          addDialogVisible.value = false;
          getList();
          ElMessage({
            type: "success",
            showClose: true,
            message: res.message,
            center: true,
          });
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.message,
            center: true,
          });
        }
      }
    } else {
      console.log("error submit!", fields);
      loading.value = false;
    }
  });
}, 1000);

const cancelAdd = () => {
  addDialogVisible.value = false;
};

// 多选框功能
const handleSelectionChange = (val) => {
  // console.log(val);
  selectIds.value = val.map((i) => i.id);
  console.log(selectIds.value);
};

// 表格斑马纹颜色修改
const tableRowClassName = ({ row, rowIndex }) => {
  if (rowIndex % 2 === 0) {
    return "even";
  } else if (rowIndex % 2 !== 0) {
    return "odd";
  }
  return "";
};
// 每页显示条数
const handleSizeChange = (value) => {
  console.log(value, "每页显示条数");
  pageSize.value = value;
  getList();
};
// 分页
const handleCurrentChange = (value) => {
  // console.log(value);
  currentPage.value = value;
  getList();
};

// 楼栋导出
const buildExportbtn = async () => {
  let params = {
    accountId: sessionStorage.getItem("accountId"),
    schoolId: searchInput.schoolId,
    buildId: searchInput.buildId,
    dormitoryId: searchInput.dormitoryId,
    sex: searchInput.sex,
    status: searchInput.status,
    collegeId: searchInput.collegeId ? searchInput.collegeId : "",
    retentionState: searchInput.retentionState,
  };
  let res = await https.getBlob(
    "/welcome/api/welcome-dormitory/welcomeDormitoryExport",
    "params",
    params
  );
  console.log(res, "寝室导出");
  let name = `寝室信息管理`;
  var content = res;
  var datas = new Blob([content]);
  var downloadUrl = window.URL.createObjectURL(datas);
  var anchor = document.createElement("a");
  anchor.href = downloadUrl;
  anchor.download = name + ".xlsx";
  anchor.click();
  window.URL.revokeObjectURL(datas);
  ElMessage({
    type: "success",
    showClose: true,
    message: "导出成功",
    center: true,
  });
};
// 楼栋导入 (--------------------------------------------------)
const buildImportBtn = () => {
  buildImportVisible.value = true;
};
// 模板下载
const templateDown = async () => {
  let res = await https.get(
    "/welcome/api/welcome-dormitory/downloadDormitoryExcel",
    "params"
  );
  console.log(res, "模板下载");
  if (res.code == 200) {
    window.location.href = res.data;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};
// 移出照片
const projectImportRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  buildFile.value = "";
};
// 限制上传图片的大小
// const beforeAvatarProImport = (rawFile) => {
//   console.log(rawFile, 33333);
//   if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
//     ElMessage.error("图片格式必须为JPG/PNG格式!");
//     return false;
//   } else if (rawFile.size / 1024 > 150) {
//     ElMessage.error("图片的大小不能超过150kb!");
//     return false;
//   }
//   return true;
// };
// 添加照片时往fileList列表中添加图片信息
const projectImportChange = async (file, fileLists) => {
  console.log(file, "1111");
  buildFile.value = file.raw;
};
const projectImportExceed = (files) => {
  buildRef.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  buildRef.value.handleStart(file);
};
// 导入项目
const projectImportConfirm = async () => {
  buildImportLoading.value = true;
  let data = new FormData();
  data.set("file", buildFile.value);
  let res = await https.post(
    "/welcome/api/welcome-dormitory/importDormitoryExcel",
    "data",
    data
  );
  console.log(res, "导入项目");
  if (res.code == 200) {
    buildImportVisible.value = false;

    buildImportLoading.value = false;
    getList();
    ElMessage({
      type: "success",
      showClose: true,
      message: res.message,
      center: true,
    });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};
const cancelProjectImport = () => {
  buildImportVisible.value = false;
  if (buildRef.value) {
    buildRef.value.clearFiles();
    buildFile.value = null;
  }
};

onBeforeMount(() => {
  getList();
  schoolList();
  collegeList();
});
onUnmounted(() => {
  // document.removeEventListener("keyup", Enters);
});
</script>

<style scoped lang="scss">
.content-box {
  width: calc(100% - 40px);
  height: calc(100% - 105px);
  margin: 20px auto;
  background-color: #fff;
  color: #000;
  display: flex;
  flex-direction: column;

  .svg {
    width: 22px;
    height: 22px;
  }

  .left {
    width: calc(100% - 60px);
    height: 60px;
    margin: 0 auto;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #ccc;
    color: #000;
    font-size: 18px;
    font-weight: 600;
    .camera {
      margin-right: 15px;
      color: #4392f7;
    }
  }
  .scroll {
    width: calc(100% - 60px);
    height: calc(100% - 61px);
    margin: 0 auto;
    display: flex;
    flex-direction: column;

    .middle {
      width: calc(100%);
      color: #000;
      .filter {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        .search {
          margin-left: 0 !important;
          color: #fff;
        }
        .condition {
          display: flex;
          align-items: center;
          margin: 10px 30px 10px 0;
          :deep(.el-input .el-input__inner) {
            font-size: 14px;
          }
          .el-select {
            width: 220px;
          }
          span {
            margin: 0 10px 0 0;
          }
        }
      }
      .gongneng {
        margin: 10px 0;
        .el-button {
          color: #fff;
          margin-right: 15px;
        }
      }
    }
    .footer {
      width: calc(100%);
      flex: 1;
      margin: 0 auto;
      overflow: auto;

      .el-table--fit {
        height: calc(100% - 60px);
        :deep(.el-table__header-wrapper) {
          background-color: #000;
          font-size: 15px;
          color: #000;
          .cell {
            color: #000;
          }
        }
        :deep(.el-table__row) {
          height: 50px;
          font-size: 15px;
          color: #000;
        }
        :deep(.el-table__row td) {
          padding: 0;
          border: 0;
        }

        .el-button--primary {
          margin-left: 5px;
        }
        :deep(.el-table__body .even) {
          background-color: #fff;
        }
        :deep(.el-table__body .odd) {
          background-color: rgba(240, 243, 247, 1);
        }
        :deep(.options) {
          display: flex;
          justify-content: center;
          align-items: center;
          .open {
            color: #2697ff;
            cursor: pointer;
            margin: 0 15px 0 0;
          }
          .edit {
            margin: 0 15px 0 0;
            color: rgba(0, 186, 173, 1);
            cursor: pointer;
          }
          .delete {
            color: rgba(212, 48, 48, 1);
            cursor: pointer;
          }
        }
      }

      .pageSize {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin: 0 30px;
        height: 60px;

        span {
          color: #000;
        }

        .el-pagination {
          // width: 1600px;
          :deep(.el-pagination__total) {
            color: #000;
          }

          :deep(.el-pagination__goto) {
            color: #000;
          }

          :deep(.el-pagination__classifier) {
            color: #000;
          }

          :deep(.el-input__wrapper) {
            border: 1px solid rgba(0, 0, 0, 1);
            border-radius: 5px;
            box-shadow: none;
          }

          :deep(.el-pager li) {
            margin: 0 5px;
            border: 1px solid rgba(0, 0, 0, 1);
            border-radius: 5px;
            background-color: transparent;
          }

          :deep(.el-pager li.is-active) {
            // background-color: rgba(0, 97, 255, 0.8);
            border: 1px solid rgba(0, 97, 255, 1);
            color: rgba(0, 97, 255, 1);
          }

          :deep(.btn-prev) {
            margin-right: 5px;
            border: 1px solid rgba(0, 0, 0, 1);
            border-radius: 5px;
            background-color: transparent;
          }

          :deep(.btn-next) {
            margin-left: 5px;
            border: 1px solid rgba(0, 0, 0, 1);
            border-radius: 5px;
            background-color: transparent;
          }
        }
      }
    }
  }

  // 添加员工弹窗样式
  :deep(.addStaff) {
    .el-dialog__body {
      padding: 20px 20px 10px 20px;
      .el-input {
        width: 400px;
        .el-input__suffix-inner {
          color: rgba(61, 81, 232, 1);
        }
      }
      .el-select {
        width: 400px;
      }
      .el-tree {
        width: 400px;
      }
    }
  }

  // 导入
  :deep(.projectImport) {
    .el-dialog__body {
      padding: 20px 30px 0 30px;
      .title {
        color: red;
      }
      .down {
        span:nth-child(1) {
          color: rgba(127, 127, 127, 1);
        }
        span:nth-child(2) {
          margin-left: 25px;
          color: rgba(2, 167, 240, 1);
          cursor: pointer;
        }
      }
      .options {
        margin: 50px 0 30px 0;
        display: flex;
        flex-direction: row-reverse;
        .queding {
          margin-left: 20px;
          background: linear-gradient(
            90deg,
            rgba(38, 151, 255, 1) 0%,
            rgba(102, 181, 255, 1) 100%
          );
          border: none;
        }
        .quxiao {
          border: 1px solid rgba(43, 151, 252, 1);
          color: rgba(43, 151, 252, 1);
        }
      }
    }
  }
}
</style>
