<template>
  <div class="choice-space">
    <div class="search">
      <div class="search-floor" @click="showPounp">
        <span class="title">位置:</span>
        <span class="title"
          >{{ checkPositon.buildingName }}{{ checkPositon.floorName }}</span
        >
        <van-icon class="arrow-down" name="arrow-down" />
      </div>
      <div class="search-space">
        <div class="com-select">
          <div class="com-text" @click="showSpaceTypePounp">
            <span>{{ spaceType.name }}</span>
            <van-icon class="arrow-down" name="arrow-down" />
          </div>
        </div>
        <van-search
          class="search-box"
          v-model="searchSpaceName"
          @update:model-value="searchSpace"
          placeholder="请输入搜索关键词"
        />
        <div class="search-icon">
          <img :src="parseImgUrl('search-icon', 'search-icon.svg')" alt="" />
        </div>
      </div>
    </div>
    <div class="space-content">
      <template v-if="showSpace">
        <div
          class="space-box"
          :id="'space' + index"
          v-for="(item, index) in spaceData"
          :key="'space' + index"
        >
          <div class="space-item">
            <span class="item-text">
              {{ item.spaceName }}
            </span>
            <van-checkbox
              class="item-check"
              v-model="item.checked"
              @click="updateWorkSpace(item)"
              shape="square"
            ></van-checkbox>
          </div>
        </div>
      </template>
      <template v-else>
        <div class="no-data" height="100%" width="100%">
          <img :src="parseImgUrl('page-officehome', 'empty.png')" alt="" />
          <span>暂无数据</span>
        </div>
      </template>
    </div>
    <div class="next-btn-box" v-if="spaceData && spaceData.length">
      <button @click="goNext">下一步</button>
    </div>
    <!--弹出模块-->
    <van-popup v-model:show="show" position="bottom">
      <van-tree-select
        @click-nav="checkBuilding"
        @click-item="checkFloor"
        v-model:active-id="checkPositon.floorId"
        v-model:main-active-index="activeIndex"
        :items="positionArr"
      />
    </van-popup>
    <van-popup v-model:show="showSpaceType" position="bottom">
      <div class="space-type">
        <span
          v-for="(item, index) in spaceTypeArr"
          @click="checkSpaceType(item)"
          :class="spaceType.type === item.type ? 'active-type' : ''"
          :key="'space-type-id' + index"
        >
          {{ item.name }}
        </span>
      </div>
    </van-popup>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  getCurrentInstance,
  nextTick,
  onMounted,
  reactive,
  toRefs,
} from "vue";
import { useRoute, useRouter, onBeforeRouteUpdate } from "vue-router";
import { Search, TreeSelect, Popup, Checkbox, Toast } from "vant";
import {
  getUserInfo,
  parseImgUrl,
  setLocalProjectId,
  setQueryConfig,
} from "@/utils";
import { store } from "@/store";
import { UserMutationTypes } from "@/store/modules/user/mutation-types";
import {
  checkWorkSpace,
  deleteWorkSpace,
  getBuildingList,
  getDefaultLocation,
  getFloorList,
  getPadSpaceList,
  insertWorkSpace,
  queryWorkSpace,
  saveWorkSpace,
} from "@/apis/envmonitor";
import { clear } from "console";

export default defineComponent({
  components: {
    vanSearch: Search,
    VanPopup: Popup,
    VanTreeSelect: TreeSelect,
    VanCheckbox: Checkbox,
  },
  setup() {
    const proxyGlobal: any = getCurrentInstance();
    const route: any = useRoute();
    const router: any = useRouter();
    const userInfo: any = getUserInfo();
    const option1 = [
      { text: "全部商ddddd品", value: 0 },
      { text: "新款商ddd品", value: 1 },
      { text: "活动商ddd品", value: 2 },
    ];
    const option2 = [
      { text: "默认排序", value: "a" },
      { text: "好评排ddd序", value: "b" },
      { text: "销量排序", value: "c" },
    ];
    let positionArr: any = [];
    let checkPositon: any = {
      buildingName:''
    };
    const defaultSpaceData: any = {};
    const buildingData: any = [];
    const buildingItem: any = {};
    const floorData: any = [];
    const spaceTypeArr: any = [
      {
        type: "",
        name: "全部空间",
      },
      {
        type: 0,
        name: "个人办公室",
      },
      {
        type: 1,
        name: "开放办公区",
      },
      {
        type: 2,
        name: "会议室",
      },
      {
        type: 99,
        name: "其它",
      },
    ];
    const spaceType: any = {
      type: "",
      name: "全部空间",
    };
    const spaceData: any = [];
    const copySpaceData: any = [];
    const proxyData = reactive({
      parseImgUrl: parseImgUrl,
      showSpace: true,
      userInfo: userInfo,
      activeIndex: 0,
      spaceType: spaceType,
      searchSpaceName: "",
      checked: false,
      positionArr: positionArr,
      checkPositon: checkPositon,
      route: route,
      option1: option1,
      option2: option2,
      value1: 0,
      value2: "a",
      transitionName: "slide-right",
      showHeader: false,
      showSpaceType: false,
      show: false, // 是否展示选择建筑的页面
      spaceTypeArr: spaceTypeArr,
      showPounp() {
        proxyData.show = !proxyData.show;
      },
      showSpaceTypePounp() {
        proxyData.showSpaceType = !proxyData.showSpaceType;
      },
      // 选择空间
      checkSpaceType(item: any) {
        proxyData.spaceType = item;
        proxyData.showSpaceType = false;
        // 获取空间列表
        proxyData.searchSpace();
      },
      buildingData: buildingData,
      buildingItem: buildingItem,
      // 获取建筑列表
      getBuildingList() {
        let params: any = {
          criteria: {
            projectId: proxyData.userInfo.projectId, //类型：String  必有字段  备注：项目id
          },
        };
        getBuildingList(params).then((res) => {
          let resData: any = res;
          if (resData.result === "success") {
            let content: any = resData?.content ?? [];
            proxyData.buildingData = content;
            proxyData.setBbuildingName();
            proxyData.getFloorList();
          } else {
            proxyData.buildingData = [];
          }
        });
      },
      //  设置建筑名称
      setBbuildingName() {
        proxyData.buildingData.map((item: any, index: any) => {
          if (item.id === proxyData.checkPositon.buildingId) {
            proxyData.checkPositon.buildingName = item.localName;
            proxyData.activeIndex = index;
          }
        });
      },
      // 格式化建筑数据
      formateBuildingData() {
        // debugger
        proxyData.positionArr = [];
        for (let i = 0; i < proxyData.buildingData.length; i++) {
          let obj = {
            text: proxyData.buildingData[i].localName,
            id: proxyData.buildingData[i].id,
            children: [],
          };
          if (
            proxyData.buildingData[i].id === proxyData.checkPositon.buildingId
          ) {
            proxyData.activeIndex = i;
            proxyData.floorData.map((item: any) => {
              item.text = item.localName;
              if (item.id === proxyData.checkPositon.floorId) {
                proxyData.checkPositon.floorName = item.localName;
              }
            });
            proxyData.checkPositon.buildingName =
              proxyData.buildingData[i].localName;
            obj.children = proxyData.floorData;
          }
          // debugger
          console.log(proxyData.floorData);
          proxyData.positionArr.push(obj);
        }
        console.log(proxyData.positionArr);
      },
      floorData: floorData,
      /**
       * 查询楼层信息
       */
      getFloorList() {
        if (proxyData.checkPositon.buildingId) {
          let params: any = {
            criteria: {
              projectId: proxyData.userInfo.projectId,
              buildingId: proxyData.checkPositon.buildingId,
            },
            orders: [
              {
                asc: true,
                column: "localId",
              },
            ],
          };
          getFloorList(params)
            .then((res) => {
              let resData: any = res;
              if (res.result === "success") {
                proxyData.floorData = resData?.content ?? [];
              } else {
                proxyData.floorData = [];
              }
              proxyData.formateBuildingData();
              proxyData.getPadSpaceList();
              // console.log(proxyData.floorData);
            })
            .catch(() => {});
        }
      },
      // 平板默认 空间
      defaultSpaceData: defaultSpaceData,
      // 查询当前平板的默认空间await与wait的区别
      getDefaultLocation() {
        let params: any = {
          macAddress: proxyData.userInfo.mac,
          spaceId: proxyData.spaceId,
          // projectId: store.state.user.projectId,
        };
        let paramsStr: any = setQueryConfig(params);
        getDefaultLocation(paramsStr).then((res) => {
          let resData: any = res;
          proxyData.defaultSpaceData = resData?.data ?? {};
          proxyData.checkPositon.buildingId =proxyData.defaultSpaceData.buildingId;
          proxyData.setCheckPersiton();
          proxyData.getBuildingList();
        });
      },
      // 设置选中的位置
      setCheckPersiton() {
        proxyData.checkPositon.buildingId =
          proxyData.defaultSpaceData.buildingId;
        proxyData.checkPositon.floorId = proxyData.defaultSpaceData.floorId;
      },
      // 格式工作办公数据
      formataWorkData() {
        let data: any = proxyData.spaceData.filter((item: any) => {
          return item.checked;
        });
        proxyData.copySpaceData.map((item: any) => {
          for (let i = 0; i < data.length; i++) {
            if (item.spaceId === data[i].spaceId) {
              item.checked = data[i].checked;
            }
          }
        });
        let paramsArr: any = proxyData.copySpaceData.filter((item: any) => {
          return item.checked;
        });
        return paramsArr;
      },
      // 设置主空间
      goNext() {
        proxyGlobal.proxy.$loadingStart(0);
        proxyData.querySpaceList();
      },
      updateWorkSpace(item: any) {
        if (item.checked) {
          proxyData.insertWorkSpace(item);
        } else {
          proxyData.deleteWorkSpace(item);
        }
      },
      insertWorkSpace(item: any, isMajorSpace: any = 0) {
        let params: any = {
          spaceId: item.spaceId, //类型：String  必有字段  备注：工作空间列表
          isMajorSpace: isMajorSpace, //类型：Number  必有字段  备注：是否主空间 0-否 1-是
          macAddress: proxyData.userInfo.mac, //类型：String  必有字段  备注：平板地址
        };
        insertWorkSpace(params).then((res: any) => {});
      },
      deleteWorkSpace(item: any) {
        let params: any = {
          spaceId: item.spaceId, //类型：String  必有字段  备注：工作空间列表
          macAddress: proxyData.userInfo.mac, //类型：String  必有字段  备注：平板地址
        };
        deleteWorkSpace(params).then((res: any) => {});
      },
      // 保存空间
      // saveWorkSpace(params: any) {
      //   proxyGlobal.proxy.$loadingStart(0);
      //   saveWorkSpace(params).then((res) => {
      //     proxyData.querySpaceList();
      //     // router.push({ name: "setMainSpace" });
      //   });
      // },
      querySpaceList() {
        let params: any = {
          criteria: {
            projectId: proxyData.userInfo.projectId,
            //类型：Object  必有字段  备注：无
            macAddress: proxyData.userInfo.mac, //类型：String  必有字段  备注：mac地址
          },
        };
        checkWorkSpace(params)
          .then((res) => {
            let resData: any = res;
            let data: any = [];
            if (resData.result === "success") {
              data = resData?.content ?? [];
            } else {
              data = [];
            }
            if (data.length > 1) {
              // router.push({ name: "setMainSpace" });
              setTimeout(() => {
                proxyGlobal.proxy.$loadinngEnd();
                router.push({ name: "setMainSpace" });
              }, 1000);
            } else if (data.length === 1) {
              proxyData.insertWorkSpace(data[0], 1);
              proxyGlobal.proxy.$loadinngEnd();
              router.push({
                name: "envmonitor",
                query: { spaceId: data[0].spaceId },
              });
            } else {
              Toast("请选择办公空间!");
            }
          })
          .catch(() => {
            proxyGlobal.proxy.$loadinngEnd();
          });
      },
      // 选择建筑
      checkBuilding(index: any) {
        proxyData.checkPositon.buildingId = proxyData.positionArr[index].id;
        proxyData.checkPositon.buildingName = proxyData.positionArr[index].text;
        proxyData.getFloorList();
      },
      // 选择楼层
      checkFloor(item: any) {
        proxyData.checkPositon.floorId = item.id;
        proxyData.checkPositon.floorName = item.localName;
        proxyData.show = false;
        nextTick(() => {
          proxyData.setPageScroolTop();
        });
        proxyData.clearSearchName();
        proxyData.getPadSpaceList();
      },
      // 清除搜索条件
      clearSearchName() {
        proxyData.searchSpaceName = "";
        proxyData.spaceType = spaceType;
        // 清除默认样式
        let spaceContetEl: any = document.querySelector(".choice-space");
        spaceContetEl.scrollTop = 0;
      },
      spaceData: spaceData,
      copySpaceData: copySpaceData,
      nowPerstionIndex: 0,
      // 空间列表
      getPadSpaceList(query: any = "") {
        // debugger;
        let params: any = query
          ? query
          : {
              floorId: proxyData.checkPositon.floorId,
              buildingId: proxyData.checkPositon.buildingId,
              macAddress: proxyData.userInfo.mac,
            };
        let str: any = setQueryConfig(params);
        getPadSpaceList(str).then((res) => {
          let resData: any = res;
          if (resData.result === "success") {
            proxyData.spaceData = resData?.data ?? [];
            proxyData.spaceData.map((item: any, index: any) => {
              if (item.isWorkSpace) {
                item.checked = true;
              } else {
                item.checked = false;
              }
              if (item.spaceId === proxyData.spaceId) {
                item.checked = true;
              }
            });
            // 不搜索的时候数据备份一下
            if (!query) {
              proxyData.copySpaceData = JSON.parse(
                JSON.stringify(proxyData.spaceData)
              );
            }
          } else {
            proxyData.spaceData = [];
          }
          if (proxyData && proxyData.spaceData.length) {
            proxyData.showSpace = true;
          } else {
            proxyData.showSpace = false;
          }
          // 设置页面默认的位置
          nextTick(() => {
            proxyData.setPageScroolTop();
          });
        });
      },
      // 设置当前页面选中的位置
      setPageScroolTop() {
        let idIndex: any = 0;
        // debugger;
        for (let i = 0; i < proxyData.spaceData.length; i++) {
          if (proxyData.spaceData[i].checked) {
            idIndex = i;
            break;
          }
        }
        let spaceEl: any = document.querySelector("#" + "space" + idIndex);
        let spaceContetEl: any = document.querySelector(".choice-space");
        // spaceContetEl.scrollTop = 0;
        let top: any = spaceEl ? spaceEl.offsetTop : 0;
        if (top > 120) {
          top = top - 120;
        } else {
          top = 0;
        }
        if (spaceContetEl) {
          spaceContetEl.scrollTop = top;
        } else {
          spaceContetEl.scrollTop = 0;
        }
      },
      searchSpace() {
        let query: any = {
          floorId: proxyData.checkPositon.floorId,
          buildingId: proxyData.checkPositon.buildingId,
          funcType: proxyData.spaceType.type,
          spaceName: proxyData.searchSpaceName,
          macAddress: proxyData.userInfo.mac,
        };
        proxyData.getPadSpaceList(query);
      },
      spaceId: "",
      init() {
        let spaceId: any = route.query.spaceId;
        proxyData.spaceId = spaceId;
        let projectId: any = route.query.id;
        store.commit(UserMutationTypes.SET_PROJECT_ID, projectId);
        proxyData.getDefaultLocation();
        if (spaceId) {
          let item: any = {
            spaceId: spaceId, //类型：String  必有字段  备注：工作空间列表
          };
          proxyData.insertWorkSpace(item, 0);
        }
      },
    });
    onMounted(() => {
      proxyData.init();
    });
    return {
      ...toRefs(proxyData),
    };
  },
});
</script>
<style lang="scss" scoped>
// @import "~@/styles/comMedia.scss";
.choice-space {
  width: 100%;
  height: 100%;
  overflow: scroll;
  // padding-bottom: 70px;
  .search {
    position: fixed;
    background: rgb(245, 245, 245);
    width: 100%;
    top: 48px;
    left: 0;
    display: flex;
    padding: 0 20px;
    z-index: 333;
    .arrow-down {
      position: absolute;
      font-size: 16px;
      right: 16px;
      top: 50%;
      transform: translateY(-50%);
      color: #8d9399;
    }
    .search-floor {
      position: relative;
      width: 380px;
      height: 44px;
      line-height: 42px;
      background: #ffffff;
      border-radius: 22px;
      padding-left: 10px;
      .title {
        display: inline-block;
        vertical-align: middle;
        padding-left: 10px;
        font-style: normal;
        font-weight: 400;
        font-size: 16px;
        line-height: 26px;
        color: #1f2429;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        &:nth-child(2) {
          width: 285px;
        }
      }
    }
    .search-space {
      display: flex;
      flex: 1;
      margin-left: 20px;
      .com-select {
        position: relative;
        width: 170px;
        height: 44px;
        // line-height: 44px;
        border-radius: 22px 0 0 22px;
        background: #fff;
        .com-text {
          height: 44px;
          font-size: 16px;
          line-height: 44px;
          padding-left: 30px;
        }
      }
      .search-box {
        flex: 1;
        height: 44px;
      }
      .search-icon {
        display: inline-block;
        background: #fff;
        // height: 44px;
        // line-height: 44px;
        // width: 42px;
        padding-right: 20px;
        border-radius: 0 22px 22px 0;
        img {
          width: 24px;
          height: 24px;
          margin-top: 10px;
        }
        // height: 22px;
      }
    }
  }
  .space-content {
    display: block;
    width: 100%;
    // height: 100%;
    padding-top: $headerHeightPading;
    padding-right: 20px;
    padding-left: 4px;
    padding-bottom: 70px;
    // justify-content: space-between;
    // overflow: scroll;
    .space-box {
      // display: i;
      display: inline-block;
      width: 33.33%;
      height: 100px;
      // background: #fff;
      padding-left: 20px;
      margin-bottom: 20px;
      .space-item {
        display: flex;
        position: relative;
        width: 100%;
        height: 100%;
        // line-height: 100px;
        // line-height: 1;
        background: #ffffff;
        /* divider/down */
        box-shadow: inset 0px -1px 0px #e4e6e7;
        border-radius: 25px;
        background: #fff;
        .item-text {
          display: inline-block;
          font-size: 16px;
          line-height: 20px;
          width: calc(100% - 60px);
          padding-left: 20px;
          position: absolute;
          left: 0px;
          top: 50%;
          transform: translateY(-50%);
        }
        .item-check {
          position: absolute;
          right: 28px;
          top: 50%;
          width: 24px;
          height: 24px;
          transform: translateY(-50%);
        }
      }
    }
  }
  .space-type {
    padding: 20px;
    span {
      display: block;
      font-size: 16px;
      padding: 10px 0;
    }
    .active-type {
      color: $elActiveColor;
    }
  }

  .next-btn-box {
    position: fixed;
    width: 100%;
    height: 60px;
    left: 0;
    bottom: 0%;
    background: #ffffff;
    box-shadow: 0px 0px 2px rgba(0, 0, 0, 0.05),
      0px 4px 15px rgba(0, 0, 0, 0.05);
    text-align: center;
    button {
      width: 46%;
      height: 40px;
      font-family: "PingFang SC";
      font-style: normal;
      font-weight: 500;
      font-size: 20px;
      line-height: 24px;
      color: $elActiveText;
      margin-top: 10px;
      background: $elActiveColor;
      // opacity: 0.8;
      border-radius: 16px;
      border: none;
      &:hover {
        //  opacity: 0.1;
        background: $elActiveColor;
      }
    }
  }
}
</style>
<style lang="scss">
.choice-space {
  .search-box {
    .van-search__content {
      background: transparent;
      border-left: 1px solid #d9d9d9;
    }
    .van-field__left-icon {
      display: none;
    }
  }
  .van-checkbox__icon--checked .van-icon {
    background-color: $elActiveColor !important;
    border-color: $elActiveColor !important;
  }
  .van-tree-select__item--active {
    color: $elActiveColor;
  }
  .van-sidebar-item--select:before {
    background-color: $elActiveColor;
  }
}
</style>

