<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="请选择楼栋名称"
            >
              <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
              clearable
              v-model="searchInput.sex"
              placeholder="请选择楼栋性别"
            >
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </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('buildingManagementSetting1')"
            type="primary"
            color="rgba(38, 151, 255, 1)"
            @click="buildImportBtn"
            >导入</el-button
          >
          <el-button
            v-if="store.BtnRole('buildingManagementSetting2')"
            type="primary"
            style="margin-left: 0"
            color="rgba(48, 201, 191, 1)"
            @click="buildExportbtn"
            >导出</el-button
          >
          <el-button
            v-if="store.BtnRole('buildingManagementSetting3')"
            type="primary"
            style="margin-left: 0"
            color="rgba(38, 151, 255, 1)"
            @click="addlist"
            >新增</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
            width="120"
            align="center"
            label="序号"
            type="index"
            index="1"
          />
          <el-table-column align="center" prop="schoolName" label="校区名称" />
          <el-table-column
            align="center"
            prop="build"
            label="楼栋名称"
          />
          <el-table-column align="center" prop="sex" label="楼栋性别" />
          <el-table-column
            align="center"
            prop="floors"
            label="楼栋层数"
          >
            <template #default="{ row }">
              <span>{{ row.floors }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="startFloor" label="起始层数" />
          <el-table-column
            align="center"
            prop="remark"
            show-overflow-tooltip
            label="备注"
          />
          <el-table-column align="center" label="操作" fixed="right">
            <template #default="{ row }">
              <div class="options">
                <span
                  v-if="store.BtnRole('buildingManagementSetting4')"
                  class="edit"
                  @click="updateS(row)"
                  >编辑</span
                >
                <span
                  v-if="store.BtnRole('buildingManagementSetting5')"
                  class="delete"
                  @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="schoolId">
          <el-select
            clearable
            v-model="ruleForm.schoolId"
            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-input
            clearable
            v-model.trim="ruleForm.build"
            class="w-50 m-2"
            placeholder="请输入楼栋名称"
          />
        </el-form-item>
        <el-form-item label="楼栋性别 :" prop="sex">
          <el-select
            :disabled="dialongTitle == '编辑楼栋信息'"
            v-model="ruleForm.sex"
            placeholder="请选择楼栋性别"
          >
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="楼栋层数 :" prop="floors">
          <el-input
            clearable
            v-model.trim="ruleForm.floors"
            class="w-50 m-2"
            placeholder="请输入楼栋层数"
          />
        </el-form-item>
        <el-form-item label="起始层数 :" prop="startFloor">
          <el-input
            clearable
            v-model.number="ruleForm.startFloor"
            class="w-50 m-2"
            placeholder="请输入起始层数"
          />
        </el-form-item>
        <el-form-item label="备注 :" prop="">
          <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 } = storeToRefs(store);

// 表格数据
const loading = ref(false);
const tableData = reactive({
  list: [],
});
const dialongTitle = ref("新增账号"); // 弹窗标题
// 搜索按钮数据
const searchInput = reactive({
  schoolId: null,
  buildId: null,
  sex: null,
});

const currentPage = ref(1); // 当前页
const pageSize = ref(10);
const total = ref(0); // 当前总数
const selectIds = ref([]);

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

// 表单数据
const formSize = ref("default");
const ruleFormRef = ref();
const ruleForm = reactive({
  schoolId: null, //校区名称
  build: null, //楼栋名称
  sex: null, //楼栋性别
  floors: null, //楼栋层数
  startFloor: null, //起始层数
  remark: null, //备注
  id: null,
});
// 表单验证
const rules = reactive({
  schoolId: [{ required: true, message: "校区名称不能为空", trigger: "blur" }],
  build: [{ required: true, message: "楼栋名称不能为空", trigger: "blur" }],
  sex: [{ required: true, message: "楼栋性别不能为空", trigger: "blur" }],
  floors: [{ required: true, message: "楼栋层数不能为空", trigger: "blur" }],
  startFloor: [
    { required: true, message: "起始层数不能为空", trigger: "blur" },
    { type: "number", message: "请输入数字" },
  ],
});

// 校区数据
const schoolData = ref([]);

// 楼栋数据
const buildData = ref([]);

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

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 () => {
  let params = {
    schoolId: searchInput.schoolId,
  };
  let res = await https.get(
    "/welcome/api/welcome-build/buildGroup",
    "params",
    params
  );
  console.log(res, "楼栋数据");
  if (res.code == 200) {
    buildData.value = res.data;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};

const schoolChange = async (val) => {
  console.log(val);
  searchInput.buildId = null;
  if (!val) {
    buildData.value = null;
    return;
  } else {
    buildData.value = null;
  }
  buildList();
};

// 获取账户列表
const getList = async () => {
  loading.value = true;
  let params = {
    currentPage: currentPage.value, // 当前页
    pageCount: pageSize.value, // 一页数据条数
    schoolId: searchInput.schoolId,
    buildId: searchInput.buildId,
    sex: searchInput.sex,
  };
  console.log(params);

  let res = await https.get(
    "/welcome/api/welcome-build/listBuild",
    "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;
  buildData.value = null;
  searchInput.sex = null;
  getList();
}, 300);

// 添加账号
const addlist = () => {
  dialongTitle.value = "新增楼栋信息";
  addDialogVisible.value = true;
  ruleForm.schoolId = null;
  ruleForm.build = null;
  ruleForm.sex = null;
  ruleForm.floors = null;
  ruleForm.startFloor = null;
  ruleForm.remark = null;
  ruleForm.id = null;
};
// 添加账号
const updateS = (row) => {
  dialongTitle.value = "编辑楼栋信息";
  addDialogVisible.value = true;
  ruleForm.schoolId = `${row.schoolName},${row.schoolId}`;
  ruleForm.build = row.build;
  ruleForm.sex = row.sex;
  ruleForm.floors = row.floors;
  ruleForm.startFloor = row.startFloor;
  ruleForm.remark = row.remark;
  ruleForm.id = row.id;
};
const deleteS = async (row) => {
  ElMessageBox.confirm("是否删除此数据?", "提示!!!", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      loading.value = true;
      let data = {
        buildId: row.id, // 当前页
      };
      let res = await https.get(
        "/welcome/api/welcome-build/deleteBuild",
        "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 submitAdd = lodash.debounce(async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let data = {
        school: ruleForm.schoolId.split(",")[0],
        schoolId: ruleForm.schoolId.split(",")[1],
        build: ruleForm.build,
        sex: ruleForm.sex,
        floors: ruleForm.floors,
        startFloor: ruleForm.startFloor,
        remark: ruleForm.remark,
      };
      if (ruleForm.id) {
        data.id = ruleForm.id;
        let res = await https.post(
          "/welcome/api/welcome-build/updateBuild",
          "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-build/saveBuild",
          "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 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 = {
    schoolId: searchInput.schoolId,
    buildId: searchInput.buildId,
    sex: searchInput.sex,
  };
  let res = await https.getBlob(
    "/welcome/api/welcome-build/welcomeBuildExport",
    "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-build/downloadBuildExcel",
    "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-build/importBuildExcel",
    "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();
});
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;
          .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>
