<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">
            <el-input
              clearable
              v-model.trim="searchInput.name"
              class="w-50 m-2"
              placeholder="请输入关键字"
              style="width: 180px"
              @clear="searchBtn"
            />
          </div>

          <el-button
            style="margin-left: 20px"
            color="rgba(0, 97, 255, 1)"
            type="primary"
            class="search"
            @click="searchBtn"
            ><el-icon><Search /></el-icon> <span>查询</span></el-button
          >
        </div>
        <!-- 按钮列表 -->
        <div class="gongneng">
          <el-button type="primary" v-if="flagBtn.tianjia==1" color="rgba(0, 97, 255, 1)" @click="addlist"
            ><img
              src="@/assets/add.png"
              style="width: 14px; height: 14px; margin-right: 4px"
              alt=""
            /><span>新增楼栋单元</span></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 align="center" type="selection" width="80" /> -->
          <el-table-column
            width="120"
            align="center"
            label="序号"
            type="index"
            index="1"
          />
          <el-table-column align="center" prop="building" label="楼栋" />
          <el-table-column align="center" prop="element" label="单元">
          </el-table-column>
          <el-table-column align="center" prop="createTime" label="创建时间"/>

          <el-table-column align="center" label="操作" width="180">
            <template #default="scope">
              <div class="options">
                <div v-if="flagBtn.bianji==1" class="look" @click="edit(scope.row)">编辑</div>
                <el-popconfirm
                  v-if="flagBtn.shanchu==1"
                  width="220"
                  confirm-button-text="确认"
                  cancel-button-text="取消"
                  :icon="InfoFilled"
                  icon-color="#f89626"
                  title="是否删除此楼栋单元?"
                  @confirm="del(scope.row)"
                  @cancel="cancelEvent"
                >
                  <template #reference>
                    <div class="del">删除</div>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div class="pageSize">
          <span></span>
          <el-pagination
            background
            :current-page="currentPage"
            :page-size="pageSize"
            layout="total, prev, pager, next, jumper, slot"
            :total="total"
            @update:current-page="handleCurrentChange"
          />
        </div>
        <!-- 添加账号弹窗 -->
        <el-dialog
          class="addStaff"
          v-model="addDialogVisible"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          :title="dialongTitle"
          align-center
          width="520"
          :before-close="cancelAdd"
        >
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="100px"
            class="demo-ruleForm"
            :size="formSize"
            label-position="left"
            status-icon
          >
            <el-form-item label="楼栋 :" prop="build">
              <el-input
                v-model.trim="ruleForm.build"
                placeholder="请输入楼栋"
                clearable
              />
            </el-form-item>
            <el-form-item label="单元 :" prop="unit">
              <el-input
                v-model.trim="ruleForm.unit"
                placeholder="请输入单元"
                clearable
              />
            </el-form-item>

            <el-form-item class="options">
              <el-button
                color="rgba(0, 97, 255, 1)"
                class="queding"
                type="primary"
                @click="submitAdd(ruleFormRef)"
              >
                确定
              </el-button>
              <el-button @click="cancelAdd(ruleFormRef)">取消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  watch,
  reactive,
  nextTick,
  onBeforeMount,
  onUnmounted,
} from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Calendar } from "@element-plus/icons-vue";
import { dayjs } from "element-plus";
import lodash, { reduce } from "lodash";
import axios from "axios";
import { useStore } from "vuex";
const store = useStore();
const router = useRouter();
// 表格数据
const loading = ref(false);
const tableData = reactive({
  list: [],
});
const activeIndex = ref(); // 默认跳转路由
const dialongTitle = ref("新增楼栋单元"); // 弹窗标题

const searchInput = reactive({
  status: "",
  name: "",
  createTime: "",
}); // 搜索按钮数据
const flagBtn = ref(); // 按钮权限

watch(
  () => searchInput.createTime,
  (newVal, oldVal) => {
    console.log("监听时间:", newVal);
    if (newVal == null) {
      getList();
    }
  }
);

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

const api = ref("");
const schoolCardList = ref();
const schoolCardSearch = ref(); // 微信卡号下拉框搜索词
const schoolCardPage = ref(1);
const schoolCardSize = ref(20);
const schoolCardTotalPage = ref();
const addDialogVisible = ref(false); // 控制添加账号弹窗
const editMemberTree = ref(); // 角色ref
const roleData = ref(); // 角色列表

const defaultProps = ref({
  children: "children",
  label: "name",
});
// 表单数据
const formSize = ref("default");
const ruleFormRef = ref();
const ruleForm = reactive({
  build: "",
  unit: "",
  id: "",
});
var buildNum = (rule, value, callback) => {
  // if (!value) {
  //   return callback(new Error("请输入楼栋）"));
  // }
  var reg = /^\\d$/;
  if (!reg.test(value)) {
    callback(new Error("输入值必须为纯数字！"));
  } else {
    callback();
  }
};
// 表单验证
const rules = reactive({
  build: [
    { required: true, message: "楼栋不能为空", trigger: "blur" },
    // { validator: buildNum, trigger: "blur" },
  ],
  unit: [
    { required: true, message: "单元不能为空", trigger: "blur" },
    // { validator: buildNum, trigger: "blur" },
  ],

  // desc: [{ required: true, message: "Please input activity form", trigger: "blur" }],
});

// 获取账户列表
const getList = async () => {
  loading.value = true;
  let data = {
    page: currentPage.value, // 当前页
    size: pageSize.value, // 一页数据条数
    // permissionSettingId: sessionStorage.getItem("permissionSettingId"),
    keyWord: searchInput.name,
  };
  // if (searchInput.createTime) {
  //   data.startTime = searchInput.createTime[0];
  //   data.endTime = searchInput.createTime[1];
  // }
  let res = await axios({
    method: "get",
    url: api.value + "/building/list",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("user_head"),
    },
    params: data,
  });
  console.log(res, "楼栋管理");
  if (res.data.code == 200) {
    tableData.list = res.data.data.records;
    total.value = res.data.data.total;
    loading.value = false;
    // ElMessage({
    //   type: "success",
    //   showClose: true,
    //   message: res.data.message,
    //   center: true,
    // });
  } else {
    loading.value = false;
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};

// 搜索功能
const searchBtn = lodash.debounce(async () => {
  getList();
}, 300);

// 添加账号
const addlist = () => {
  dialongTitle.value = "新增楼栋单元";
  addDialogVisible.value = true;
  ruleForm.build = "";
  ruleForm.unit = "";
  ruleForm.id = "";
};

// 取消添加员工
const cancelAdd = () => {
  addDialogVisible.value = false;
  ruleFormRef.value.resetFields();
};
//编辑按钮
const edit = (row) => {
  console.log(row);
  dialongTitle.value = "编辑楼栋单元";
  addDialogVisible.value = true;
  ruleForm.build = row.building;
  ruleForm.unit = row.element;
  ruleForm.id = row.id;
};
// 确认添加员工
const submitAdd = lodash.debounce(async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (ruleForm.id) {
         let data = {
          id:ruleForm.id,
        	"building": ruleForm.build,
        	"element": ruleForm.unit
        };
        let res = await axios({
          method: "post",
          url: api.value + "/building/update",
          headers: {
            token: sessionStorage.getItem("token"),
            user_head: sessionStorage.getItem("user_head"),
          },
          data: data,
        });
        console.log(res, "编辑楼栋管理");
        if (res.data.code == 200) {
          getList();
          ElMessage({
            type: "success",
            showClose: true,
            message: res.data.message,
            center: true,
          });
          addDialogVisible.value = false;
          ruleFormRef.value.resetFields();
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      } else {
        let data = {
        	"building": ruleForm.build,
        	"element": ruleForm.unit
        }
        let res = await axios({
          method: "post",
          url: api.value + "/building/save",
          headers: {
            token: sessionStorage.getItem("token"),
            user_head: sessionStorage.getItem("user_head"),
          },
          data: data,
        });
        console.log(res, "添加楼栋");
        if (res.data.code == 200) {
          getList();
          ElMessage({
            type: "success",
            showClose: true,
            message: res.data.message,
            center: true,
          });
          addDialogVisible.value = false;
          ruleFormRef.value.resetFields();
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      }
    } else {
      console.log("error submit!", fields);
    }
  });
}, 1000);

//删除按钮
const del = async (row) => {
  // console.log(row);
  let data = {
    buildingId: row.id,
    // permissionSettingId: sessionStorage.getItem("permissionSettingId"),
  };
  let res = await axios({
    method: "get",
    url: api.value + "/building/delete",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("user_head"),
    },
    params: data,
  });
  if (res.data.code == 200) {
    if (tableData.list.length == 1 && currentPage.value != 1) {
      currentPage.value = currentPage.value - 1;
    }
    getList();
    ElMessage({
      type: "success",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
  // console.log(res);
};
// 取消删除
const cancelEvent = () => {
  ElMessage({
    type: "info",
    showClose: true,
    message: "取消删除",
    center: true,
  });
};

// 多选框功能
// const handleSelectionChange = (val) => {
//   console.log(val);
//   selectData.list = val;
// };

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

onBeforeMount(() => {
  api.value = store.state.user.api;
  const btnflag = JSON.parse(sessionStorage.getItem("btnflag"));
  flagBtn.value = btnflag.account;
  console.log(flagBtn.value, "按钮权限");

  getList();
});
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: #fff;
  display: flex;
  flex-direction: column;
  box-shadow: 0px 3px 10px rgba(0, 97, 255, 0.2);

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

    color: #000;
    // border-bottom: 1px solid rgb(231, 231, 231);
    .filter {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
        // margin: 10px 0 0 0;
      .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;
        }
        span {
          margin: 0 10px 0 0;
        }
      }
    }
    .gongneng {
      margin: 10px 0;
      .el-button {
        color: #fff;
        margin-right: 15px;
      }
    }
    :deep(.cont) {
      width: 60%;
      margin: 20px auto;
    }
    :deep(.download) {
      display: flex;
      align-items: center;
      margin: 10px;
    }
    :deep(.download span) {
      font-size: 16px;
      margin-left: 20px;
    }
    :deep(.cont .el-button) {
      margin-left: 60px;
      margin-bottom: 30px;
    }

    :deep(.cont .accomplish) {
      width: 100%;
      display: flex;
      justify-content: center;
    }
    :deep(.cont .accomplish .el-button) {
      width: 50%;
      margin: 0;
    }
  }
  .footer {
    width: calc(100% - 60px);
    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;
        .reset {
          color: rgba(9, 101, 98, 1);
          cursor: pointer;
        }
        .look {
          margin: 0 15px;
          color: rgba(30, 125, 251, 1);
          cursor: pointer;
        }
        .del {
          color: rgba(212, 48, 48, 1);
          cursor: pointer;
        }
      }
    }

    // 添加员工弹窗样式
    :deep(.addStaff) {
      //   height: 420px;
      border-radius: 11px;
      .el-dialog__header {
        border-radius: 11px 11px 0 0;
        background: rgba(237, 241, 245, 1);
        font-weight: 600;
        margin: 0;
        .el-dialog__headerbtn {
          outline: none;
        }
      }
      .el-dialog__body {
        padding: 20px 20px 10px 20px;
        .el-input {
          width: 200px;
          .el-input__suffix-inner {
            color: rgba(61, 81, 232, 1);
          }
        }

        .options {
          margin: 40px 20px 20px 0;
          width: 100%;
          .el-form-item__content {
            display: flex;
            flex-direction: row-reverse;
          }
          .queding {
            color: #fff;
            margin-left: 15px;
          }
        }
      }
    }
  }

  .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;
      }
    }
  }
}
.el-input {
  width: 192px;
}
</style>
<style lang="scss">
//添加成员 联系人下拉框样式
.more-tag-data {
  // border: 1px solid red;
  .el-select-dropdown__wrap {
    height: 200px;
  }
}
.el-popper {
  .addStudentMore {
    text-align: center;
  }
}
</style>
