<template>
  <div class="main_box">
    <div class="body-box">
      <div class="banner-box">
        <div class="search-input">
          <div class="date-box" @click="handleChooseDate">统计日期：{{ searchForm.dt }}</div>
          <van-search
            type="text"
            placeholder="请选择业务指标"
            v-model="itemIdxNm"
            @clear="onClear"
            left-icon=""
            class="special-search"
            readonly
            @click="showIndcPicker = true"
            right-icon="arrow-down"
          />
          <van-search
            type="text"
            v-model="searchForm.branchName"
            placeholder="请输入归属支行"
            @search="onSearch"
            @clear="onClear"
            left-icon=""
            class="special-search"
          />
        </div>
        <div class="search-input special-search-box">
          <van-search
            type="text"
            v-model="searchForm.outletName"
            placeholder="请输入归属网点"
            @search="onSearch"
            @clear="onClear"
            left-icon=""
            class="special-search special-search-outlet"
          />
          <van-search
            type="text"
            v-model="searchForm.nickName"
            placeholder="请输入归属客户经理"
            @search="onSearch"
            @clear="onClear"
            left-icon=""
            class="special-search"
          />
          <div class="search_btn" @click="onSearch">
            <van-icon name="search" class="icon"></van-icon>
          </div>
          <div class="search_btn reset" @click="resetForm">
            <van-icon name="cross" class="icon"></van-icon>
          </div>
        </div>
      </div>
      <div class="echart-box">
        <van-button
          size="small"
          class="back-btn"
          v-if="level == '2' && !isOutletAdmin && !isCommonManager"
          @click="backTo"
        >
          返回上一级
        </van-button>
        <div class="echart" ref="echart"></div>
      </div>
      <van-popup v-model="showIndcPicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="indcTypeList"
          value-key="label"
          @cancel="showIndcPicker = false"
          @confirm="onConfirmIndc"
        />
      </van-popup>
      <van-popup v-model="showDialog" position="bottom">
        <div class="info-box">
          <div class="dialog-title">
            <span>业绩指标信息</span>
          </div>
          <div class="child-main">
            <div v-if="level == 1">
              <div class="my-title">总行行政网格：{{ layerInfo.name }}</div>
              <div class="my-title">归属支行：{{ allBranch }}</div>
              <div class="my-title">
                整体{{ layerInfo.itemName }}：{{ layerInfo.value }}%
              </div>
              <div
                v-for="(item, index) in otherInfo"
                :key="index"
                class="branch-box"
              >
                <div class="bank-title">
                  (支行) {{ item.name }}{{ layerInfo.itemName }}：{{
                    item.itemVal
                  }}%
                </div>
                <div class="org-box">
                  <div v-for="(i, k) in item.managerList" :key="k">
                    <span class="custom-line"
                      >{{ i.nickName
                      }}<span class="value-line"
                        >{{ layerInfo.itemName }}：{{ i.itemVal }}%</span
                      ></span
                    >
                  </div>
                </div>
                <div
                  v-for="(i, k) in item.children"
                  :key="k"
                  class="outlet-box"
                >
                  <div class="bank-title">
                    (网点) {{ i.name }}{{ layerInfo.itemName }}：{{
                      i.itemVal
                    }}%
                  </div>
                  <div class="org-box">
                    <div v-for="(j, s) in i.managerList" :key="s">
                      <span
                        >{{ j.nickName }}
                        <span class="value-line">
                          {{ layerInfo.itemName }}：{{ j.itemVal }}%
                        </span>
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div v-if="level == 2">
              <div class="my-title">支行行政网格：{{ layerInfo.name }}</div>
              <div class="my-title">归属支行：{{ allBranch }}</div>
              <div class="my-title">归属网点：{{ allOutlet }}</div>
              <div class="my-title">归属客户经理：{{ allManager }}</div>
              <div class="my-title">
                整体{{ layerInfo.itemName }}：{{ layerInfo.value }}%
              </div>
            </div>
          </div>
          <div class="info-footer">
            <van-button
              class="btn"
              @click="showDialog = false"
              :class="level == '2' ? 'level2-class' : ''"
              >关闭</van-button
            >
            <van-button
              v-if="level == '1'"
              class="btn"
              type="primary"
              @click="gotoNext"
              >下钻查看村/社区</van-button
            >
          </div>
        </div>
      </van-popup>
      <van-popup v-model="showDatePicker" position="bottom">
        <van-datetime-picker
          v-model="searchDate"
          type="date"
          title="选择统计日期"
          :max-date="maxDate"
          @cancel="showDatePicker = false"
          @confirm="handleConfirmChooseDate"
        />
      </van-popup>
    </div>
  </div>
</template>
<script>
import * as echarts from "echarts";
import WKT from "terraformer-wkt-parser";
import {
  getPerIndcList,
  searchEchartTownData,
  searchEchartVillageData,
  getHotMapInfo,
} from "@/service/api/dataCenter.js";
import {
  Tab,
  Tabs,
  Icon,
  Button,
  Search,
  RadioGroup,
  Radio,
  List,
  PullRefresh,
  Dialog,
  Toast,
  Popup,
  Picker,
  DatetimePicker,
} from "vant";
export default {
  props: {
    activeBtn: String,
  },
  watch: {
    activeBtn(newValue) {
      this.activeBtn = newValue;
      this.queryIndcList({ opsDept: newValue });
    },
  },
  data() {
    return {
      searchForm: {
        itemIdx: "",
        branchName: "",
        outletName: "",
        nickName: "",
        dt: "",
      },
      searchDate: "",
      maxDate: "",
      itemIdxNm: "",
      showIndcPicker: false,
      showDatePicker: false,
      indcTypeList: [],
      date: "2025-01-22",
      isOutletAdmin: false,
      isCommonManager: false,
      level: "1",
      myChart: null,
      mapData: {
        type: "FeatureCollection",
        features: [],
      },
      perData: [],
      code: "",
      min: 0,
      max: 100,
      layerInfo: {},
      otherInfo: [],
      allBranch: "",
      allOutlet: "",
      allManager: "",
      code1: "",
      code2: "",
      showDialog: false,
    };
  },
  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,
  },

  created() {
    const date = new Date();
    date.setDate(date.getDate() - 1);
    this.searchDate = date;
    this.maxDate = date;
    this.searchForm.dt = this.getPreviousDate();
    this.queryIndcList({ opsDept: this.activeBtn });
    const str = sessionStorage.getItem("userInfo") || "{}";
    const userInfo = JSON.parse(str);
    if (userInfo.roles.includes("commonManager")) {
      this.isCommonManager = true;
    } else if (userInfo.roles.includes("outletAdmin")) {
      this.isOutletAdmin = true;
    }
    if (this.isOutletAdmin || this.isCommonManager) {
      this.level = "2";
    }
  },
  mounted() {
    this.myChart = echarts.init(this.$refs.echart);
  },
  methods: {
    getPreviousDate() {
      const date = new Date();
      date.setDate(date.getDate() - 1);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    handleChooseDate() {
      this.showDatePicker = true;
    },
    handleConfirmChooseDate(val) {
      const year = val.getFullYear();
      const month = String(val.getMonth() + 1).padStart(2, "0");
      const day = String(val.getDate()).padStart(2, "0");
      this.searchForm.dt = `${year}-${month}-${day}`;
      this.showDatePicker = false;
      this.getPerEchartsData()
    },
    scrollToTop() {
      window.scrollTo({
        top: 0,
        behavior: "smooth",
      });
    },
    // 获取业务指标
    async queryIndcList(params) {
      const res = await getPerIndcList(params);
      if (res.code == 200) {
        this.indcTypeList = res.data.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue,
          };
        });
        if (this.indcTypeList.length > 0) {
          this.searchForm.itemIdx = this.indcTypeList[0].value;
          this.itemIdxNm = this.indcTypeList[0].label;
          this.getPerEchartsData();
        }
      }
    },
    onConfirmIndc(item) {
      this.searchForm.itemIdx = item.value;
      this.itemIdxNm = item.label;
      this.showIndcPicker = false;
      this.getPerEchartsData();
    },

    onSearch() {
      this.getPerEchartsData();
    },
    resetForm() {
      this.searchForm = {
        branchName: "",
        outletName: "",
        nickName: "",
        dt: this.getPreviousDate(),
      };
      this.searchForm.itemIdx = this.indcTypeList[0]?.value;
      this.itemIdxNm = this.indcTypeList[0]?.label;
      this.getPerEchartsData();
    },
    onClear() {
      this.getPerEchartsData();
    },
    async getPerEchartsData() {
      const Api =
        this.level == "1" ? searchEchartTownData : searchEchartVillageData;
      const params = {
        ...this.searchForm,
        opsDept: this.activeBtn,
      };
      if (this.level == "2") {
        params.code = this.code1;
      }
      const res = await Api(params);
      if (res.code == 200) {
        const arr = res.data || [];
        if (!arr.length) {
          this.mapData.features = [];
          this.perData = [];
          this.renderMap();
          Toast("暂无数据");
          return;
        }
        this.date = arr[0].createTime;
        this.mapData.features = [];
        this.perData = [];
        arr.map((item, index) => {
          let value = item.itemVal;
          this.perData.push({
            name: item.regionName || "",
            value: Number(value),
            relateGrids: item.relateGrids || "",
            relateDepts: item.relateDepts || "",
            relateUsers: item.relateUsers || "",
            itemName: item.itemName || "",
            code: item.code || "",
            evoFlag: item.evoFlag,
          });
          this.mapData.features.push({
            type: "Feature",
            properties: {
              name: item.regionName || "",
            },
            geometry: {
              type: WKT.parse(item.wkt).type,
              coordinates: WKT.parse(item.wkt).coordinates,
            },
          });
        });
        let values = this.perData.map((item) => item.value);
        let minValue = Math.min(...values);
        let maxValue = Math.max(...values);
        this.min = Math.floor(minValue);
        this.max = Math.ceil(maxValue);
        this.renderMap();
      }
    },
    renderMap() {
      echarts.registerMap("hotMap", this.mapData);
      const option = {
        // 地图偏移位置
        layoutCenter: ["60%", "50%"],
        layoutSize: "170%",
        visualMap: {
          show: true,
          min: this.min,
          max: this.max,
          text: ["高", "低"],
          realtime: false,
          calculable: true,
          inRange: {
            color: [
              "#caf0f8",
              "#ade8f4",
              "#90e0ef",
              "#48cae4",
              "#00b4d8",
              "#0096c7",
              "#0077b6",
              "#023e8a",
              "#03045e",
            ],
          },
          bottom: 60,
        },
        series: [
          {
            name: "图层名称",
            type: "map",
            map: "hotMap",
            selectedMode: false,
            roam: true,
            itemStyle: {},
            // 高亮
            emphasis: {
              disabled: true,
              itemStyle: {
                // areaColor:'skyblue',
                borderWidth: 2,
                shadowOffsetX: 2,
                shadowOffsetY: 2,
                shadowColor: "rgba(250,250,250,0.5)",
              },
            },
            label: {
              show: true,
              textStyle: {
                // fontSize:14,
                // color:'#526b63',
              },
              formatter: function (params) {
                // console.log(params,'222')
                const value =
                  params?.data?.evoFlag != "true"
                    ? "0.00"
                    : params?.value?.toFixed(2);
                return (
                  "{num|" +
                  params.name +
                  "}" +
                  "\r\n" +
                  "{num|" +
                  value +
                  "%" +
                  "}"
                );
              },
              rich: {
                num: {
                  color: "#fff",
                  fontSize: 12,
                  // fontWeight:'bold',
                  padding: [5, 2, 0, 0],
                },
              },
              // emphasis:{
              //     show:true,
              //     color:'#fff',
              //     fontSize:20
              // },
            },
            data: this.perData,
          },
        ],
      };
      option.series[0].data.forEach((item) => {
        // console.log(item,item.itemStyle)
        // 设置颜色区间
        if (item.evoFlag != "true") {
          item.itemStyle = {
            color: "#ddd",
            borderColor: "#222",
            borderWidth: 1,
          };
          item.emphasis = {
            disabled: true,
          };
        } else {
          item.itemStyle = {};
          item.emphasis = {
            disabled: true,
            itemStyle: {
              borderWidth: 2,
              shadowOffsetX: 2,
              shadowOffsetY: 2,
              shadowColor: "rgba(250,250,250,0.5)",
            },
          };
        }
      });
      this.myChart.setOption(option, true);

      // 单击某个区域
      this.myChart.on("click", (params) => {
        console.log("click", params);
        if (params.data.evoFlag != "true") {
          return;
        }
        if (this.level == "1") {
          this.code1 = params.data.code;
        }
        if (this.level == "2") {
          this.code2 = params.data.code;
        }
        this.layerInfo = params.data;
        this.getModalInfo();
      });
    },
    gotoNext() {
      this.level = "2";
      this.code1 = this.layerInfo.code;
      this.showDialog = false;
      this.searchForm.branchName = "";
      this.searchForm.outletName = "";
      this.searchForm.nickName = "";
      this.getPerEchartsData();
    },
    //返回
    backTo() {
      this.level = "1";
      this.searchForm.branchName = "";
      this.searchForm.outletName = "";
      this.searchForm.nickName = "";
      this.getPerEchartsData();
    },
    async getModalInfo() {
      const res = await getHotMapInfo({
        opsDept: this.activeBtn,
        itemIdx: this.searchForm.itemIdx,
        code: this.level == "1" ? this.code1 : this.code2,
      });
      if (res.code == 200) {
        const data = (res.data && res.data[0]) || {};
        if (!res?.data?.length) {
          Toast("暂无数据");
        }
        this.otherInfo = data.children || [];
        this.allBranch = this.otherInfo.map((item) => item.name).join(",");
        let outlet = [];
        this.otherInfo.map((item) => {
          item.children.map((i) => {
            outlet.push(i.name);
          });
        });
        this.allOutlet = outlet.join(",");
        let manager = [];
        data.managerList.map((item) => {
          manager.push(item.nickName);
        });
        this.otherInfo.map((item) => {
          item.managerList.map((i) => {
            manager.push(i.nickName);
          });
          item.children.map((i) => {
            i.managerList.map((n) => {
              manager.push(n.nickName);
            });
          });
        });
        this.allManager = manager.join(",");
        this.showDialog = true;
      }
    },
  },
};
</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;
    }
  }
}
.wrapper_top {
  background-color: #fff;
  padding: 15px 20px;
}

.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;
}

.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;
  .back-btn {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 500;
    border-radius: 4px;
  }
  .echart {
    width: 100%;
    height: 666px;
    // border: 1px solid #ddd;
  }
}
.info-box {
  .dialog-title {
    text-align: center;
    font-size: 18px;
    margin: 16px 0;
    font-weight: 600;
  }
  .child-main {
    max-height: 600px;
    overflow-y: auto;
    padding: 0 16px;
    .bank-title {
      font-size: 14px;
      color: #595959;
      font-weight: 600;
    }
  }
  .branch-box {
    border-radius: 5px;
    margin-bottom: 5px;
    padding: 5px 5px;
    background: #f9f9fa;
  }
  .org-box {
    padding: 5px 0px 5px 15px;
    font-weight: 400;
    font-size: 14px;
    color: #595959;
    .value-line {
      margin-left: 10px;
    }
  }
  .my-title {
    font-weight: 400;
    font-size: 14px;
    color: #262626;
    line-height: 30px;
  }
  ::v-deep .el-dialog__body {
    padding-top: 10px;
  }
  ::v-deep .el-dialog:not(.is-fullscreen) {
    margin-top: 20vh !important;
  }
  .outlet-box {
    // margin-left: 10px;
  }
  .info-footer {
    display: flex;
    justify-content: space-around;
    margin: 20px 0;
    .btn {
      width: 40%;
      border-radius: 4px;
    }
    .level2-class {
      width: 90%;
    }
  }
}
</style>
