<style lang="less">
.page-search {
  position: relative;
}

.input-wrap {
  display: flex;
  position: relative;
  margin: 16rpx auto 0;
  width: 686rpx;
  height: 96rpx;
  line-height: 96rpx;
  background: rgba(2, 2, 82, 0.03);
  border-radius: 16rpx;
}

.input-wrap input,
textarea {
  width: 100%;
  height: 100%;
  padding: 0 88rpx;
  box-sizing: border-box;
  background-color: transparent;
  font-size: 14px;
}

.input-wrap .icon {
  width: 48rpx;
  height: 48rpx;
  display: block;
}

.input-wrap .icon-search-wrap {
  position: absolute;
  left: 16rpx;
  top: 24rpx;
}

.input-wrap .icon-close-wrap {
  position: absolute;
  right: 32rpx;
  top: 24rpx;
}

.btn-to-meetingroom {
  font-size: 28rpx;
  line-height: 32rpx;
  text-align: right;
  color: #4d94ff;
  width: 100%;
  text-align: center;
  margin: 112rpx auto 0 auto;
}

.btn-to-meetingroom.has-history {
  position: absolute;
  top: 160rpx;
  right: 48rpx;
  text-align: right;
  margin: 0;
  font-size: 24rpx;
}

.user-space-list-wrap {
  width: 100%;
}

.user-space-list-wrap .none-wrap {
  margin-top: 112rpx;
  font-family: PingFang SC;
  font-style: normal;
  font-weight: normal;
  font-size: 14px;
  line-height: 32rpx;
  color: rgba(6, 6, 61, 0.3);
  text-align: center;
}
</style>

<template>
  <view class="page-search">
    <view class="input-wrap">
      <label for="spaceSearchInputId" class="icon-search-wrap">
        <image class="icon" src="{{h5StaticPath+ 'icon_search.svg'}}" />
      </label>
      <input
        id="spaceSearchInputId"
        value="{{inputValue}}"
        bindinput="getInputValue"
        placeholder="{{canSearchPerson?'输入人名/地点': '输入地点'}}"
        focus="{{autoFocus}}"
      />
      <label for="spaceSearchInputId" class="icon-close-wrap">
        <image
          wx:if="{{inputValue}}"
          bindtap="clearInput"
          class="icon"
          src="{{h5StaticPath+ 'icon_close.svg'}}"
        />
      </label>
    </view>
    <view
      wx:if="{{!inputValue}}"
      class="{{'btn-to-meetingroom ' + (historyList.length ? 'has-history' : '')}}"
      bindtap="goToMeetingroomList"
    >查看所有会议室</view>
    <view class="user-space-list-wrap">
      <block wx:if="{{!inputValue}}">
        <user-space-list
          wx:if="{{historyList.length}}"
          title="最近查找"
          list="{{historyList}}"
          @component-user-space-list-click="toMapPage($event)"
        ></user-space-list>
      </block>
      <block wx:else>
        <block wx:if="{{searchResultList.length}}">
          <user-space-list
            title="匹配结果"
            list="{{searchResultList}}"
            @component-user-space-list-click="toMapPage($event)"
          ></user-space-list>
        </block>
        <block wx:else>
          <view class="none-wrap">
            <label>没有匹配的结果</label>
          </view>
        </block>
      </block>
    </view>
  </view>
</template>

<script>
import wepy from '@wepy/core';
import { checkHasUserInfo } from '@/service/user';
import {
  setLastSearchedSpace,
  getHistorySearchedSpaceList,
  setHistorySearchedSpaceList
} from '../service/search';
import config from '@/config';
import {
  getMapInfoHttp,
  getUserSpaceList
} from '@/packagesEnv/api/intelligentControl';
import utils from '@/common/utils';
import { getCompanyMapData } from '@/api/home';

let h5StaticPath = config.h5StaticPath + '/page-intelligent-control/';
let combinedData = [];
let pageQuery;
let CompanyMapData;
wepy.page({
  data: {
    inputValue: '',
    historyList: [],
    searchResultList: [],
    h5StaticPath,
    canSearchPerson: true,
    autoFocus: false,
    userSpaceList: [],
    companyId: ''
  },
  onLoad(query) {
    this.canSearchPerson = query.canSearchPerson
      ? JSON.parse(query.canSearchPerson)
      : true; // 将字符串false/true 转为boolear
    pageQuery = query;
    checkHasUserInfo().then(userInfo => {
      let companyId = query.companyId || userInfo.companyId;

      this.companyId = companyId;
      getCompanyMapData(companyId).then(res => {
        CompanyMapData = JSON.parse(res.data);
        getMapInfoHttp(companyId).then(res => {
          const result = JSON.parse(res.data);
          const httpDdata = (result && result.content) || [];
          combinedData = httpDdata.reduce((acc, cur) => {
            const target = acc.find(e => e.id == cur.id);
            if (target) {
              Object.assign(target, { title: cur.localName });
              // console.log('找到了', cur, index);
            } else {
              // console.log('data有没找到', cur.id);
            }
            return acc;
          }, CompanyMapData.mapInfo);
        });
      });

      getHistorySearchedSpaceList().then(historyList => {
        this.historyList = historyList;
      });

      getUserSpaceList(this.companyId).then(res => {
        this.userSpaceList = res.data || [];
      });
    });
  },
  onReady() {
    this.autoFocus = true;
  },
  onShow() {},
  methods: {
    getInputValue(e) {
      let keyword = e.$wx.detail.value || '';
      keyword = keyword.trim();
      let searchResultList = [];
      if (keyword) {
        const regExp = utils.getSearchRegEx(keyword);
        const searchedSpaceResult = search(regExp, combinedData, 'title');
        searchResultList = searchResultList.concat(searchedSpaceResult);

        if (this.canSearchPerson) {
          let searchedUserResult = search(
            regExp,
            this.userSpaceList,
            'userName'
          );
          searchedUserResult.forEach(user => {
            combinedData.find(space => {
              if (space.id == user.spaceId) {
                user.spaceName = space.title;
                return true;
              }
              return false;
            });
          });
          searchResultList = searchResultList.concat(searchedUserResult);
        }
      }

      this.inputValue = keyword;
      this.searchResultList = searchResultList;
    },
    toMapPage(item) {
      setLastSearchedSpace(item).then(() => {
        var lastSearchedSpace = wx.getStorageSync({
          key: 'lastSearchedSpace'
        }); // 从搜索页面返回且搜索有效
        let historyList = this.historyList;
        let newHistoryList = setHistorySearchedSpaceList(historyList, item);
        this.historyList = newHistoryList;
        if (pageQuery.from == 'home') {
          wx.navigateTo({
            url: `/packagesEnv/pages/officehome/index?spaceId=${item.spaceId}`
          });
        } else if (pageQuery.from == 'officehome') {
          wx.navigateBack();
        } else {
          wx.navigateBack({
            delta: 2
          });
        }
      });
    },
    clearInput() {
      this.inputValue = '';
      this.searchResultList = [];
    },
    goToMeetingroomList() {
      if (pageQuery.from == 'home') {
        wx.navigateTo({
          url: `../meetingroomlist/meetingroomlist?from=home&companyId=${this.companyId}`
        });
      } else if (pageQuery.from == 'officehome') {
        wx.navigateTo({
          url: `../meetingroomlist/meetingroomlist?from=officehome&companyId=${this.companyId}`
        });
      } else {
        wx.navigateTo({
          url: `../meetingroomlist/meetingroomlist?companyId=${this.companyId}`
        });
      }
    }
  }
});
function search(regExp, list, key) {
  let resultList = [];
  list.forEach(item => {
    const value = item[key];
    if (value && regExp.exec(value)) {
      resultList.push({
        spaceId: item.id,
        value: value,
        key: key,
        roomFuncType: item.roomFuncType
      });
    }
  });
  return resultList;
}
</script>

<config>
{
    navigationBarTitleText: '',
    navigationBarBackgroundColor: '#FFFFFF',
    "backgroundColor": "#FFFFFF",
    usingComponents: {
     "user-space-list": "../components/user-space-list/user-space-list"
    }
}
</config>
