<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
              @change="collegeChange"
              v-model="searchInput.college"
              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
              @change="majorChange"
              v-model="searchInput.major"
              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.eduLevel"
              placeholder="请选择层次"
            >
              <el-option label="本科" value="本科" />
              <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('dormitoryMoneySetting1')"
            type="primary"
            color="rgba(38, 151, 255, 1)"
            @click="buildImportBtn"
            >导入</el-button
          >
          <el-button
            v-if="store.BtnRole('dormitoryMoneySetting2')"
            type="primary"
            style="margin-left: 0"
            color="rgba(48, 201, 191, 1)"
            @click="buildExportbtn"
            >导出</el-button
          >
          <el-button
            v-if="store.BtnRole('dormitoryMoneySetting3')"
            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="collegeName" label="学院" />
          <el-table-column align="center" prop="majorName" label="专业名称" />
          <el-table-column align="center" prop="eduLevel" label="层次" />
          <el-table-column align="center" prop="floors" label="学制">
            <template #default="{ row }">
              <span>{{ row.eduSystem }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="payAmount" label="金额" />
          <el-table-column align="center" label="操作" fixed="right">
            <template #default="{ row }">
              <div class="options">
                <span
                  v-if="store.BtnRole('dormitoryMoneySetting4')"
                  class="edit"
                  @click="updateS(row)"
                  >编辑</span
                >
                <span
                  v-if="store.BtnRole('dormitoryMoneySetting5')"
                  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="college">
          <el-select
            @change="collegeFormChange"
            v-model="ruleForm.college"
            placeholder="请选择院系"
            clearable
          >
            <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
            @change="majorFormChange"
            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="eduLevel">
          <el-select
            clearable
            v-model="ruleForm.eduLevel"
            placeholder="请选择层次"
          >
            <el-option label="本科" value="本科" />
            <el-option label="专升本" value="专升本" />
            <el-option label="专科" value="专科" />
          </el-select>
        </el-form-item>
        <el-form-item label="学制 :" prop="eduSystem">
          <el-input
            clearable
            v-model.trim="ruleForm.eduSystem"
            class="w-50 m-2"
            placeholder="请输入学制"
          />
        </el-form-item>
        <el-form-item label="金额 :" prop="payAmount">
          <el-input
            clearable
            v-model="ruleForm.payAmount"
            class="w-50 m-2"
            placeholder="请输入金额"
          />
        </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 dialongTitle = ref("新增账号"); // 弹窗标题
// 搜索按钮数据
const searchInput = reactive({
  college: null,
  major: null,
  eduLevel: null,
});

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

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

// 表单数据
const formSize = ref("default");
const ruleFormRef = ref();
const ruleForm = reactive({
  college: null, //
  major: null, //
  eduLevel: null, //
  eduSystem: null, //
  payAmount: null, //
  id: null,
});
var checkFullName = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("金额不能为空"));
  }

  var reg = /^(0|([1-9]\d*)(\.\d{1,2})?)$/;
  if (!reg.test(value)) {
    callback(new Error("金额输入有误，请重新输入"));
  } else {
    callback();
  }
};
// 表单验证
const rules = reactive({
  college: [{ required: true, message: "学院不能为空", trigger: "blur" }],
  major: [{ required: true, message: "专业名称不能为空", trigger: "blur" }],
  eduLevel: [{ required: true, message: "层次不能为空", trigger: "blur" }],
  eduSystem: [{ required: true, message: "学制不能为空", trigger: "blur" }],
  payAmount: [
    { required: true, message: "金额不能为空", trigger: "blur" },
    {
        pattern: /^(0|([1-9]\d*)(\.\d{1,2})?)$|^(0\.\d{1,2})$/,
        message: "金额输入有误，请重新输入",
        trigger: "blur",
    },
  ],
});

// 学院
const collegeData = ref([]);
// 专业
const majorData = ref([]);
const majorFormData = ref([]);

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

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 majorList = async (flag) => {
  let params = {
    collegeId: flag ? flag : searchInput.college,
  };
  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 collegeChange = async (val) => {
  console.log(val);
  searchInput.major = null;
  if (!val) {
    majorData.value = null;
    return;
  } else {
    majorData.value = null;
  }
  majorList();
};
const collegeFormChange = async (val) => {
  console.log(val);
  ruleForm.major = null;
  if (!val) {
    majorFormData.value = null;
    return;
  } else {
    majorFormData.value = null;
  }
  majorList(ruleForm.college.split(",")[1]);
};
// 获取账户列表
const getList = async () => {
  loading.value = true;
  let params = {
    currentPage: currentPage.value, // 当前页
    pageCount: pageSize.value, // 一页数据条数
    collegeId: searchInput.college,
    majorId: searchInput.major,
    eduLevel: searchInput.eduLevel,
  };
  console.log(params);

  let res = await https.get(
    "/welcome/api/paySetting/getPageDatas",
    "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.college = null;
  searchInput.major = null;
  majorData.value = null;
  searchInput.eduLevel = null;
  getList();
}, 300);

// 添加账号
const addlist = () => {
  dialongTitle.value = "新增宿舍金额设置";
  addDialogVisible.value = true;
  ruleForm.college = null;
  ruleForm.major = null;
  ruleForm.eduLevel = null;
  ruleForm.eduSystem = null;
  ruleForm.payAmount = null;
  ruleForm.id = null;
};
// 添加账号
const updateS = (row) => {
  dialongTitle.value = "编辑宿舍金额设置";
  addDialogVisible.value = true;
  ruleForm.college = `${row.collegeName},${row.collegeId}`;
  if (row.collegeId) {
    majorList(row.collegeId).then(() => {
      ruleForm.major = `${row.majorName},${row.majorId}`;
    });
  }
  ruleForm.eduLevel = row.eduLevel;
  ruleForm.eduSystem = row.eduSystem;
  ruleForm.payAmount = row.payAmount;
  ruleForm.id = row.id;
};
const deleteS = async (row) => {
  ElMessageBox.confirm("是否删除此数据?", "提示!!!", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      loading.value = true;
      let data = {
        id: row.id, // 当前页
      };
      let res = await https.get(
        "/welcome/api/paySetting/deletePaySetting",
        "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 = {
        collegeId: ruleForm.college.split(',')[1],
        collegeName: ruleForm.college.split(',')[0],
        majorId: ruleForm.major.split(',')[1],
        majorName: ruleForm.major.split(',')[0],
        eduLevel:ruleForm.eduLevel,
        eduSystem: ruleForm.eduSystem,
        payAmount: ruleForm.payAmount,
      };
      if (ruleForm.id) {
        data.id = ruleForm.id;
        let res = await https.post(
          "/welcome/api/paySetting/updatePaySetting",
          "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/paySetting/insertPaySetting",
          "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 = {
    collegeId: searchInput.college,
    majorId: searchInput.major,
    eduLevel: searchInput.eduLevel,
  };
  let res = await https.getBlob(
    "/welcome/api/paySetting/paySettingExport",
    "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/paySetting/downloadPaySettingExcel",
    "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/paySetting/importPaySettingExcel",
    "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();
  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;
          .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>
