<template>
  <div class="main_box">
    <van-loading class="loading" v-if="mapLoading"
      >数据加载中,请稍后...</van-loading
    >
    <div class="body-box">
      <div class="banner-box">
        <div class="search-input">
          <van-search
            type="text"
            placeholder="请选择汇总维度"
            v-model="timeIntervalNm"
            left-icon=""
            class="special-search"
            readonly
            @click="showIntervalPicker = true"
            right-icon="arrow-down"
          />
          <van-search
            type="text"
            placeholder="请选择日期"
            v-model="searchForm.date"
            left-icon=""
            class="special-search"
            readonly
            @click="showDatePicker = true"
            right-icon="arrow-down"
            :style="{ visibility: showDate ? 'visible' : 'hidden' }"
          />
        </div>
        <div class="search-input special-search-box" v-if="!isCommonManager">
          <van-search
            type="text"
            placeholder="请选择归属机构"
            v-model="node.text"
            left-icon=""
            class="special-search"
            readonly
            @click="showOrgPicker = true"
            right-icon=""
          >
            <template #right-icon>
              <van-icon name="arrow-down" size="16" v-if="!node.text" />
              <van-icon name="clear" size="16" v-else @click.stop="clearOrg" />
            </template>
          </van-search>
          <van-search
            type="text"
            placeholder="请选择客户经理"
            v-model="userName"
            left-icon=""
            class="special-search"
            readonly
            @click="showUserPicker = true"
            right-icon="arrow-down"
          >
            <template #right-icon>
              <van-icon name="arrow-down" size="16" v-if="!userName" />
              <van-icon name="clear" size="16" v-else @click.stop="clearUser" />
            </template>
          </van-search>
        </div>
      </div>
      <div class="map-grid" ref="mapContainer"></div>
      <van-popup v-model="showIntervalPicker" position="bottom">
        <van-picker
          v-model="timeIntervalNm"
          :default-index="defaultIndex"
          show-toolbar
          :columns="rangeList"
          value-key="value"
          @cancel="showIntervalPicker = false"
          @confirm="onConfirmInterval"
        />
      </van-popup>
      <van-popup v-model="showDatePicker" position="bottom">
        <van-datetime-picker
          v-model="currentDate"
          type="date"
          show-toolbar
          :max-date="maxDate"
          @cancel="showDatePicker = false"
          @confirm="onConfirmDate"
        />
      </van-popup>
      <van-popup v-model="showOrgPicker" position="bottom" class="popOrg">
        <van-picker
          show-toolbar
          :columns="deptOptions"
          @cancel="showOrgPicker = false"
          @confirm="onConfirmOrg"
        />
      </van-popup>
      <van-popup v-model="showUserPicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="managerOptions"
          value-key="label"
          @cancel="showUserPicker = false"
          @confirm="onConfirmUser"
        >
          <template #columns-top>
            <van-search
              type="text"
              placeholder="请输入柜员号或姓名"
              v-model="customNm"
              left-icon=""
              class="special-search"
              right-icon="search"
              @search="searchCustom"
              @clear="clearCustom"
            />
          </template> 
          </van-picker>
      </van-popup>
    </div>
  </div>
</template>
<script>
import WKT from "terraformer-wkt-parser";
import moment from "moment";
import {
  getDeptTree,
  getPointInfo1,
  getPointInfo2,
  getUserListByDeptIds,
} from "@/service/api/dataCenter.js";
import {
  Tab,
  Tabs,
  Icon,
  Button,
  Search,
  RadioGroup,
  Radio,
  List,
  PullRefresh,
  Dialog,
  Toast,
  Popup,
  Picker,
  DatetimePicker,
  TreeSelect,
} from "vant";
export default {
  props: {},
  watch: {},
  data() {
    return {
      searchForm: {
        timeInterval: "30",
        date: undefined,
        deptId: undefined,
        userName: "",
      },
      userName: "",
      timeIntervalNm: "近30天",
      showIntervalPicker: false,
      indcTypeList: [],
      showDialog: false,
      isCommonManager: false,
      rangeList: [
        { key: "", value: "按天" },
        { key: "30", value: "近30天" },
        { key: "90", value: "近90天" },
        { key: "180", value: "近180天" },
        { key: "365", value: "近365天" },
      ],
      defaultDate: undefined,
      defaultDateStr: "",
      currentDate: undefined,
      showDatePicker: false,
      showDate: false,
      node: {},
      showOrgPicker: false,
      deptOptions: [],
      managerOptions: [],
      managerOptionsDef: [],
      activeId: "",
      activeIndex: 0,
      mapLoading: false,
      showUserPicker: false,
      maxDate: undefined,
      defaultIndex: 1,
      customNm: "",
    };
  },
  components: {
    VanTab: Tab,
    VanTabs: Tabs,
    VanIcon: Icon,
    VanButton: Button,
    VanSearch: Search,
    VanRadioGroup: RadioGroup,
    VanRadio: Radio,
    VanList: List,
    VanPullRefresh: PullRefresh,
    VanToast: Toast,
    [Dialog.Component.name]: Dialog.Component,
    VanPopup: Popup,
    VanPicker: Picker,
    VanDatetimePicker: DatetimePicker,
    VanTreeSelect: TreeSelect,
  },

  created() {
    const today = new Date();
    const preDay = new Date(today.getTime() - 24 * 3600 * 1000);
    this.maxDate = preDay;
    this.defaultDate = preDay;
    this.defaultDateStr = moment(preDay).format("YYYY-MM-DD");
    const str = sessionStorage.getItem("userInfo") || "{}";
    const userInfo = JSON.parse(str);
    if (userInfo.roles.includes("commonManager")) {
      this.isCommonManager = true;
      this.searchForm.userName = this.userName;
    }
    this.getDeptTreeList();
  },
  mounted() {
    this.initMap();
  },
  methods: {
    clearCustom(){
      this.managerOptions = [...this.managerOptionsDef];
    },
    searchCustom(){
      this.managerOptions=this.managerOptionsDef.filter(item=>item.label.includes(this.customNm))
    },
    loopArr(arr) {
      return arr.map((item) => {
        if (item?.children?.length) {
          return {
            ...item,
            text: item.label,
            children: this.loopArr([
              {
                label: "请选择",
                id: "",
                level: "branch",
                children: [],
              },
              ...item.children,
            ]),
          };
        }
        if (item.level == "branch") {
          return {
            ...item,
            text: item.label,
            children: [
              {
                label: "请选择",
                text: "请选择",
                id: "",
              },
            ],
          };
        } else {
          return {
            ...item,
            text: item.label,
          };
        }
      });
    },
    // 获取机构
    async getDeptTreeList() {
      const res = await getDeptTree();
      if (res.code == 200) {
        this.deptOptions = this.loopArr(res.data);
        console.log(this.deptOptions);
      }
    },
    // 获取客户经理列表
    async getUserNameOption(deptid) {
      const res = await getUserListByDeptIds(deptid);
      if (res.code == 200) {
        this.managerOptions = res.data.map((item) => {
          return {
            label: `${item.nickName}-${item.userName}`,
            value: item.userName,
          };
        });
        this.managerOptionsDef = [...this.managerOptions];
      }
    },
    // 点击归属机构选项
    onConfirmOrg(item, value) {
      console.log(item, value);
      const newArr = item.filter((item) => item !== "请选择");
      this.node = this.findBelongBranchId(
        this.deptOptions,
        newArr[newArr.length - 1]
      );
      this.searchForm.userName = "";
      this.userName = "";
      this.getUserNameOption(this.node.id);
      this.showOrgPicker = false;
      this.getPoint();
    },
    findBelongBranchId(tree, text) {
      for (const node of tree) {
        if (node.text === text) {
          return node;
        }
        if (node.children && node.children.length) {
          const found = this.findBelongBranchId(node.children, text);
          if (found) return found;
        }
      }
      return null;
    },
    clearOrg() {
      this.node = {};
      this.searchForm.userName = "";
      this.userName = "";
      this.managerOptions = [];
      this.data = [];
      this.map.clearOverlays();
    },
    clearUser() {
      this.searchForm.userName = "";
      this.userName = "";
      this.getPoint();
    },
    onConfirmUser(item) {
      console.log(item);
      this.searchForm.userName = item.value;
      this.userName = item.label;
      this.showUserPicker = false;
      this.managerOptions=[...this.managerOptionsDef];
      this.customNm = '';
      this.getPoint();
    },
    // 维度
    onConfirmInterval(item) {
      this.searchForm.timeInterval = item.key;
      this.timeIntervalNm = item.value;
      if (item.key == "") {
        this.showDate = true;
        this.searchForm.date = this.defaultDateStr;
        this.currentDate = this.defaultDate;
      } else {
        this.showDate = false;
        this.searchForm.date = undefined;
      }
      this.showIntervalPicker = false;
      if (this.isCommonManager || this.node.id) {
        this.getPoint();
      }
    },

    onConfirmDate(item) {
      console.log(item);
      this.searchForm.date = moment(item).format("YYYY-MM-DD");
      this.currentDate = item;
      if (this.isCommonManager || this.node.id) {
        this.getPoint();
      }
    },

    // 初始化地图
    initMap() {
      this.mapLoading = true;
      this.map = new BMapGL.Map(this.$refs.mapContainer);
      // const localCity = new BMapGL.LocalCity();
      this.map.centerAndZoom("浙江省", 8);
      this.map.enableScrollWheelZoom();
      if (this.isCommonManager) {
        this.getPoint();
      } else {
        this.mapLoading = false;
      }
    },

    getPoint() {
      this.map.centerAndZoom("浙江省", 8);
      const { timeInterval, date, deptId, userName } = this.searchForm;
      // console.log(deptId, userName,this.node);
      let params = {
        headId: "",
        branchId: "",
        outletId: "",
      };
      if (timeInterval == "") {
        params.date = (date && moment(date).format("YYYY-MM-DD")) || "";
      } else {
        params.timeInterval = timeInterval;
      }
      if (this.node.level == "head") {
        params.headId = this.node.id;
      } else if (this.node.level == "branch") {
        params.branchId = this.node.id;
      } else if (this.node.level == "outlet") {
        params.outletId = this.node.id;
      }
      params.userName = userName;
      console.log(params);
      this.mapLoading = true;
      const Api = timeInterval ? getPointInfo1 : getPointInfo2;
      setTimeout(() => {
        Api(params).then((res) => {
          console.log(res, "ressssss");
          if (res.code == 200) {
            this.data = res.data;
            this.map.clearOverlays();
            if (this.data.length) {
              this.max = this.data.reduce((prev, current) =>
                Number(prev.count) > Number(current.count) ? prev : current
              ).count;
              this.drawHeatMap();
            } else {
              this.mapLoading = false;
            }
          }
        });
      }, 300);
    },

    drawHeatMap() {
      let heatmapOverlay = new BMapLib.HeatmapOverlay({
        radius: 20,
        visible: true,
        // opacity:70
      });
      this.map.addOverlay(heatmapOverlay);
      // heatmapOverlay.setOptions({
      //   gradient:{
      //     0:'blue',
      //     0.1:'rgb(0,255,255)',
      //     0.2:'rgb(0,255,0)',
      //     0.4:'yellow',
      //     0.6:'red',
      //     1:'maroon',
      //   }
      // })
      const data = {
        max: this.max,
        data: this.data,
      };
      // console.log(heatmapOverlay)
      heatmapOverlay.setDataSet(data);
      // this.map.setViewport();
      this.mapLoading = false;
    },
  },
};
</script>
<style lang="less" scoped>
.main_box {
  position: relative;
  .backTop {
    position: fixed;
    bottom: 150px;
    right: 15px;
    width: 64px;
    height: 64px;
    border-radius: 50%;
    background: #4682ff;
    box-shadow: 0px -2px 6px 0px rgba(70, 130, 255, 1);
    color: #fff;
    transform: rotate(180deg);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    font-size: 20px;
    .heng {
      display: block;
      width: 15px;
      border: 1px solid #fff;
    }
  }
  .banner-box {
    position: absolute;
    width: 100%;
    z-index: 100;
  }
  .loading {
    position: absolute;
    width: 100%;
    height: calc(100vh);
    z-index: 800;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(255, 255, 255, 0.8);
  }
  .map-grid {
    position: relative;
    width: 100%;
    height: calc(100vh - 80px);
    margin: 0;
    padding: 0;
    .loading {
      position: absolute;
      width: 100%;
      height: 100%;
    }
  }
}
.wrapper_top {
  background-color: #fff;
  padding: 15px 20px;
}
.org-container {
  padding: 16px;
  .top-btn {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    margin-bottom: 15px;
    .cancel {
      color: #969799;
    }
    .ok {
      color: #576b95;
    }
  }
  .content {
    display: flex;
    .headText {
      padding: 14px 12px;
    }
  }
}

.search-input {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 3px;
  background: #fff;
  padding: 0 10px;
  .special-search {
    padding-right: 0 !important;
    ::v-deep .van-search__content {
      padding-left: 4px !important;
    }
    ::v-deep .van-cell {
      padding-right: 0 !important;
    }
    ::v-deep .van-field__control::-webkit-input-placeholder {
      font-size: 12px;
    }
  }
  .special-search-outlet {
    padding-left: 0 !important;
  }
  .date-box {
    background: #f7f8fa;
    height: 34px;
    line-height: 34px;
    color: #888;
    padding: 0 5px;
    font-size: 12px;
    border-radius: 4px;
    width: 440px;
  }
}
.special-search-box {
  margin-top: 0px;
  ::v-deep .van-field__control {
    font-size: 12px;
  }
}

.search_btn {
  background-color: rgb(24, 144, 255);
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 40px;
  height: 40px;
  color: #fff;
  font-size: 20px;
  .icon {
    display: inline-block;
    width: 40px;
    text-align: center;
  }
}
.reset {
  background: #f7f8fa;
  color: rgba(0, 0, 0, 0.45);
  margin-left: 3px;
}

/deep/ .van-search {
  width: 100%;
  padding: 5px 8px;
}

.radio_box {
  display: flex;
  align-items: center;
  margin: 15px 0 15px 15px;
}

.btn_box {
  padding: 8px 16px;
  background-color: #fff;
}

.isChecked {
  background-color: rgb(35, 114, 235);
  color: #fff;
  border-radius: 4px;
}
.grid_item {
  margin-top: 8px;
  padding: 10px 15px;
  background-color: #fff;
}
.grid_item_top {
  display: flex;
  align-items: center;
}
.icon_box {
  background-color: rgb(35, 114, 235);
  border-radius: 4px;
  width: 25px;
  height: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.grid_item_top_icon {
  font-size: 16px;
  color: #fff;
}
.grid_item_top_title {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
}
.grid_item_middle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: rgb(249, 249, 251);
  padding: 10px 15px;
  margin-top: 10px;
}
.grid_item_middle_item {
  width: 30%;
  text-align: center;
}
.middle_num {
  margin-top: 10px;
  font-weight: 600;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.middle_title {
  font-size: 12px;
}
.line {
  width: 1px;
  height: 30px;
  background-color: rgb(255, 255, 255);
  border: 1px solid rgb(218, 220, 224);
}
.grid_item_bottom {
  margin-top: 8px;
  font-size: 12px;
}
.grid_item_bottom_item {
  display: flex;
  align-items: center;
  margin-top: 5px;
  .branch-detail {
    color: #4886f8;
    margin-left: 5px;
  }
  .bottom_item_right {
    display: inline-block;
    max-width: calc(100% - 90px);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .custom-btn {
    height: 24px;
  }
}
.item-date {
  justify-content: space-between;
  margin-top: 1px;
}
.bottom_item_left {
  color: rgb(140, 140, 140);
}

.echart-box {
  position: relative;
  background: #fff;
  margin-top: 3px;
  .echart {
    width: 100%;
    height: 666px;
    // border: 1px solid #ddd;
  }
}
.popOrg {
  ::v-deep .van-ellipsis {
    white-space: pre-wrap;
    font-size: 12px;
  }
}
</style>