<!-- 选择 城市
  <SelectCity v-model="val" @selected="selectHandle" />
-->
<template>
  <div>
    <template v-if="print">
      <div>{{ cityName }}</div>
    </template>
    <template v-else>
      <div class="wrap">
        <Input
          ref="cityIpt"
          v-model="cityName"
          :value="cityName"
          :placeholder="placeholder"
          :disabled="disabled"
          @click.native="inputFocus()"
          @on-blur="inputBlur()"
          @input="valueChange"
        />
        <transition name="slide-fade">
          <div
            v-show="isShow"
            ref="popper"
            v-transfer-dom
            class="h-ems-place"
            :data-transfer="transfer"
            style="z-index: 999996;"
          >
            <div class="h-ems-title">
              <span>拼音支持首字母输入</span>
              <span v-if="multiple" style="color:red;font-size:12px">(可以选择多个目的地)</span>
              <i
                class="ivu-icon ivu-icon-ios-close"
                @click="closePlace()"
              ></i>
            </div>
            <div
              v-show="isContent"
              class="h-ems-content"
            >
              <ul class="h-ems-pinyin">
                <li
                  :class="{ active: index==0 }"
                  val="rm"
                  @click="liclick('rm',0)"
                >
                  热门
                </li>
                <li
                  :class="{ active: index==1 }"
                  val="A-E"
                  @click="liclick('A-E',1)"
                >
                  A-E
                </li>
                <li
                  :class="{ active: index==2 }"
                  val="F-J"
                  @click="liclick('F-J',2)"
                >
                  F-J
                </li>
                <li
                  :class="{ active: index==3 }"
                  val="K-O"
                  @click="liclick('K-O',3)"
                >
                  K-O
                </li>
                <li
                  :class="{ active: index==4 }"
                  val="P-T"
                  @click="liclick('P-T',4)"
                >
                  P-T
                </li>
                <li
                  :class="{ active: index==5 }"
                  val="U-Z"
                  @click="liclick('U-Z',5)"
                >
                  U-Z
                </li>
              </ul>
              <div class="h-ems-place-name">
                <template v-if="!areaConfig.length || areaConfig.includes('1')">
                  <span
                    v-for="place in places"
                    :key="place.id"
                    @click="placeClick(place)"
                  >{{ place.cityName }}</span>
                </template>
                <template v-show="index == 0">
                  <div v-if="!areaConfig.length || areaConfig.includes('2')">
                    <template v-for="item in hk_hw">
                      <span
                        v-if="!areaConfig.length || areaConfig.includes(item.areaType)"
                        :key="item.id"
                        style="font-weight: bold;"
                        @click="placeClick(item)"
                      >{{ item.cityName }}</span>
                    </template>
                  </div>
                </template>
              </div>
            </div>
            <div
              v-show="isPlaceList"
              class="h-ems-placeList"
            >
              <ul>
                <li
                  v-for="place in placeLis"
                  :key="place.id"
                  @click="placeClick(place)"
                >
                  {{ place.cityName }}
                </li>
              </ul>
            </div>
            <div
              v-show="multiple"
              class="multiple-wrp"
            >
              <span
                v-for="(item, i) in selectVals"
                :key="item.id"
                class="multiple-item"
              >{{ item.cityName }}
                <Icon
                  type="ios-close"
                  @click="closeSelectVal(i)"
                />
              </span>
              <div
                class="btns"
                style="margin-top: 10px;"
              >
                <Button
                  size="small"
                  style="margin-right: 4px"
                  @click="closePlace()"
                >
                  取消
                </Button>
                <Button
                  type="primary"
                  size="small"
                  @click="placeOK()"
                >
                  确定
                </Button>
              </div>
            </div>
          </div>
        </transition>
      </div>
    </template>
  </div>
</template>
<script>
import TransferDom from "../../util/transfer-dom.js";
import axios from '../axios.js';

const Popper = require("popper.js/dist/umd/popper.js"); // eslint-disable-line

export default {
  name: "SelectCity",
  directives: { TransferDom },
  model: {
    prop: "value",
    event: "input"
  },
  props: {
    value: {
      type: String,
      default: ""
    },
    url: {
      type: String,
      default: "",
      required: true
    },
    print: {
      type: Boolean,
      default: false
    },
    transfer: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: "请选择"
    },
    area: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      index: 0,
      isShow: false,
      isContent: true,
      isPlaceList: false,
      siteTop: 0,
      siteLeft: 0,
      pys: {},
      cityName: "",
      cityId: this.value,
      areaConfig: [],
      areaType: "",
      places: [],
      hk_hw: [], // 存储香港和海外
      syObjs: [],
      placeLis: [],
      popper: null,
      popperStatus: false,
      selectVals: [],
      boldNameList: ["海外", "澳门", "台湾", "香港"]
    };
  },
  watch: {
    value(newName, oldName) {
      this.cityId = newName;
      if (!newName) this.cityName = "";
      this.findCityById(this.syObjs);
    },
    area(val) {
      this.setErea(val);
    }
  },
  created() {
    this.setErea(this.area);
    this.GetCityList();
  },
  mounted() {
    // popper
    if (this.transfer) {
      this.update();
    }
  },
  beforeDestroy: function() {
    if (this.popper) {
      this.popper.destroy();
    }
  },
  methods: {
    setErea(area) {
      // 不传 全量展示
      if (area) {
        const areaType = {
          1: ['1'], // 展示国内
          2: ['1', '2'], // 展示国内 + 港澳台
          3: ['1', '2', '3'] // 全量展示(国内 + 海外 + 港澳台)
        };
        this.areaConfig = areaType[this.area];
      } else {
        this.areaConfig = [];
      }
    },
    GetCityList() {
      const cityList = JSON.parse(sessionStorage.getItem("cityList"));
      if (!cityList) {
        axios.post(this.url, []).then((response) => {
          const data = response.data;
          sessionStorage.setItem("cityList", JSON.stringify(data));
          this.initCityList(data);
        }).catch(error => {
          this.$Message.error(error || '网络错误！');
        });
      } else {
        this.initCityList(cityList);
      }
    },
    initCityList(data) {
      const pys = {
        rm: [],
        "A-E": [],
        "F-J": [],
        "K-O": [],
        "P-T": [],
        "U-Z": []
      };
      const rmObjs = data.hotCityList;
      pys.rm = rmObjs;
      const syObjs = data.allCityList;
      this.findCityById(syObjs); // 根据cityId查找cityName用于反显
      for (let i = 0; i < syObjs.length; i++) {
        const sy = syObjs[i];
        if ("ABCDE".indexOf(sy.cityFirstName) >= 0) {
          pys["A-E"].push(sy);
        } else if ("FGHIJ".indexOf(sy.cityFirstName) >= 0) {
          pys["F-J"].push(sy);
        } else if ("KLMNO".indexOf(sy.cityFirstName) >= 0) {
          pys["K-O"].push(sy);
        } else if ("PQRST".indexOf(sy.cityFirstName) >= 0) {
          pys["P-T"].push(sy);
        } else if ("UVWXYZ".indexOf(sy.cityFirstName) >= 0) {
          pys["U-Z"].push(sy);
        }
      }
      // 香港和海外 单独拿出来渲染
      const abroad = pys.rm.find(item => item.cityName === '海外');
      if (abroad) {
        abroad.areaType = '3';
      }
      this.hk_hw = [];
      this.places = [];
      this.hk_hw = pys.rm.filter(item => this.boldNameList.includes(item.cityName));
      this.places = pys.rm.filter(item => !this.boldNameList.includes(item.cityName));
      this.pys = pys;
      this.syObjs = syObjs;
    },
    findCityById(allCityList) {
      if (!this.multiple) {
        if (this.cityId) {
          const self = this;
          // let has = false;
          for (let i = 0; i < allCityList.length; i++) {
            const item = allCityList[i];
            if (item.cityId == self.cityId) {
              self.cityName = item.cityName;
              // self.$emit("input", self.cityId + "");
              // self.$emit("selected", self.cityId);
              // self.$emit("selectedAreaValue", item.areaType);
              // has = true;
            }
          }
          // if (!has) {
          //   this.$emit("input", "");
          //   this.$emit("selected", null);
          //   this.$emit("selectedAreaValue", null);
          // }
        }
      } else {
        this.selectVals = [];
        if (this.cityId) {
          const cityIds = this.cityId.split(",");
          const names = [];
          for (let i = 0; i < cityIds.length; i++) {
            const cityId = cityIds[i];
            for (let j = 0; j < allCityList.length; j++) {
              if (allCityList[j].cityId == cityId) {
                names.push(allCityList[j].cityName);
                this.selectVals.push(allCityList[j]);
                this.areaType = allCityList[j].areaType;
                break;
              }
            }
          }
          this.cityName = names.toString();
          // this.$emit("input", this.cityId);
          // this.$emit("selected", this.cityId);
          // this.$emit("selectedAreaValue", this.areaType);
          // if (names.length <= 0) {
          //   this.$emit("selected", null);
          //   this.$emit("selectedAreaValue", null);
          // }
        }
      }
    },
    valueChange: function(val) {
      // this.cityName = val;
      const selval = [];
      const valLow = val.toLowerCase();
      for (let i = 0; i < this.syObjs.length; i++) {
        const syo = this.syObjs[i];
        if (
          syo.fullCityName.toLowerCase().indexOf(valLow) == 0 ||
          syo.cityName.indexOf(val) >= 0 ||
          syo.cityAbbreviation.toLowerCase().indexOf(valLow) == 0
        ) {
          selval.push(syo);
        }
      }
      this.placeLis = selval;
      if (val == "") {
        this.isPlaceList = false;
        this.isContent = true;
      } else {
        this.isPlaceList = true;
        this.isContent = false;
      }
    },
    inputFocus: function() {
      if (this.disabled) {
        return false;
      }
      if (this.transfer) {
        this.update();
      }
      this.isShow = true;
    },
    inputBlur: function() {
      // this.isShow = false;
      // this.closePlace();
    },
    liclick: function(val, index) {
      this.index = index;
      if (val == "rm") {
        this.hk_hw = [];
        this.places = [];
        this.hk_hw = this.pys[val].filter(item => this.boldNameList.includes(item.cityName));
        this.places = this.pys[val].filter(item => !this.boldNameList.includes(item.cityName));
      } else {
        this.places = this.pys[val];
        this.hk_hw = [];
      }
    },
    placeOK: function() {
      var names = [];
      var ids = [];
      var cityType = "";
      for (var i = 0; i < this.selectVals.length; i++) {
        var p2 = this.selectVals[i];
        names.push(p2.cityName);
        ids.push(p2.cityId);
        if (cityType == "" || parseInt(cityType) < parseInt(p2.cityType)) {
          cityType = p2.cityType;
        }
      }
      this.cityName = names.toString();
      this.cityId = ids.toString();
      this.isShow = false;
      this.$emit("input", ids.toString());
      this.$emit("selected", {
        ids: ids.toString(),
        cityName: this.cityName,
        areaType: this.areaType,
        cityType: cityType,
      });
      // this.$emit("selectedName", this.cityName);
      // this.$emit("selectedAreaValue", this.areaType);
      // this.$emit("selectedCityType", cityType);
      this.$refs["cityIpt"].focus();
      this.closePlace();
    },
    closeSelectVal: function(index) {
      this.selectVals.splice(index, 1);
    },
    placeClick: function(place) {
      if (!this.multiple) {
        this.cityName = place.cityName;
        this.cityId = place.cityId;
        this.isShow = false;
        // console.log(place);
        this.$emit("input", this.cityId + "");
        this.$emit("selected", this.cityId + "");
        this.$emit("selectedAreaValue", this.areaType);
        this.$refs.cityIpt.focus();
        this.closePlace();
      } else {
        if (this.selectVals.length <= 0) this.areaType = "";
        if (this.areaType && this.areaType != place.areaType) {
          this.$Message.error("请选择相同的地区类型地址!");
          return;
        } else {
          this.areaType = place.areaType;
        }
        this.isPlaceList = false;
        this.isContent = true;
        let ifcz = false;
        for (let i = 0; i < this.selectVals.length; i++) {
          const p2 = this.selectVals[i];
          if (place.cityId == p2.cityId) {
            ifcz = true;
            break;
          }
        }
        if (!ifcz) this.selectVals.push(place);
      }
    },
    closePlace: function() {
      this.isShow = false;

      if (this.isPlaceList) {
        // 检查手动输入是否有效，无效清除
        const cityName = this.cityName;
        const placeLis = this.placeLis;
        let has = false;
        for (let i = 0; i < placeLis.length; i++) {
          const item = placeLis[i];
          if (item.cityName === cityName) {
            this.cityName = cityName;
            this.$emit("input", item.cityId + "");
            this.$emit("selected", item.cityId + "");
            this.$emit("selectedAreaValue", item.areaType);
            this.$refs.cityIpt.focus();
            has = true;
          }
        }
        if (!has) {
          this.cityName = "";
          this.isPlaceList = false;
          this.isContent = true;
          this.$emit("input", "");
          this.$emit("selected", null);
          this.$emit("selectedAreaValue", null);
        }
      }
      if (!this.cityId) {
        this.cityName = "";
        this.isPlaceList = false;
        this.isContent = true;
        this.$emit("input", "");
        this.$emit("selected", null);
        this.$emit("selectedAreaValue", null);
      }
    },
    transferFix() {
      const $cityIpt = this.$refs.cityIpt.$el.getBoundingClientRect();
      // console.log($cityIpt);

      this.$refs.popper.style.top = $cityIpt.top + $cityIpt.height + "px";
      this.$refs.popper.style.left = $cityIpt.left + "px";
    },
    update() {
      if (this.popper) {
        this.$nextTick(() => {
          this.popper.update();
          this.popperStatus = true;
        });
      } else if (!this.print) {
        this.$nextTick(() => {
          this.popper = new Popper(this.$refs.cityIpt.$el, this.$refs.popper, {
            placement: "bottom-start",
            modifiers: {
              computeStyle: {
                gpuAcceleration: false
              },
              preventOverflow: {
                boundariesElement: "window"
              }
            },
            onCreate: () => {
              this.resetTransformOrigin();
              this.$nextTick(this.popper.update());
            },
            onUpdate: () => {
              this.resetTransformOrigin();
            }
          });
        });
      }
    },
    destroy() {
      if (this.popper) {
        setTimeout(() => {
          if (this.popper && !this.popperStatus) {
            this.popper.destroy();
            this.popper = null;
          }
          this.popperStatus = false;
        }, 300);
      }
    },
    resetTransformOrigin() {
      if (!this.popper) return;

      const xPlacement = this.popper.popper.getAttribute("x-placement");
      const placementStart = xPlacement.split("-")[0];
      const placementEnd = xPlacement.split("-")[1];
      const leftOrRight = xPlacement === "left" || xPlacement === "right";
      if (!leftOrRight) {
        this.popper.popper.style.transformOrigin =
          placementStart === "bottom" || (placementStart !== "top" && placementEnd === "start")
            ? "center top"
            : "center bottom";
      }
    }
  }
};
</script>

<style lang="less" scoped>
.wrap {
  position: relative;
}
.h-ems-place {
  width: 300px;
  border-radius: 4px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.2);
  position: absolute;
  top: 32px;
  left: 0;
  z-index: 9997;
  .multiple-wrp {
    background: #FFF;
    padding: 5px;
    .multiple-item {
      padding: 0 2px;
      border: 1px solid #ccc;
      border-radius: 5px;
      position: relative;
      margin-right: 4px;
      margin-bottom: 4px;
      display: inline-block;
      cursor: pointer;
      &:hover {
        border-color: #fbae49
      }
      .ivu-icon-ios-close {
        right: -3px;
        top: -4px;
        height: 10px;
        width: 10px;
        font-size: 11px;
        background: red;
        padding: 0px;
        color: #fff;
        text-align: center;
        border-radius: 10px;
        font-weight: bold;
      }
    }
  }
}
.h-ems-place .h-ems-title {
  padding-left: 5px;
  background: #fbae49;
  color: #fff;
  height: 30px;
  line-height: 30px;
}
.h-ems-place .h-ems-content {
  background: #fff;
}
.h-ems-place .h-ems-content .h-ems-pinyin {
  padding: 5px;
  height: 23px;
  display: block;
  position: relative;
  z-index: 2;
}
.h-ems-place .h-ems-content .h-ems-pinyin {
  padding: 5px;
  height: 23px;
  display: block;
  position: relative;
  z-index: 2;
}
.h-ems-place .h-ems-content .h-ems-pinyin li {
  float: left;
  padding: 1px 10px;
  cursor: pointer;
  list-style: none;
}
.h-ems-place .h-ems-content .h-ems-pinyin li.active {
  border: 1px solid #ccc;
  border-bottom: #fff;
  background: #fff;
}
.h-ems-place .h-ems-content .h-ems-place-name {
  width: 100%;
  display: block;
  border-top: 1px solid #ccc;
  height: 200px;
  overflow-y: auto;
  position: relative;
  top: -2px;
  z-index: 1;
}

.h-ems-place .h-ems-content .h-ems-place-name {
  width: 100%;
  display: block;
  border-top: 1px solid #ccc;
  height: 200px;
  overflow-y: auto;
  position: relative;
  top: -2px;
  z-index: 1;
  padding: 10px;
}
.h-ems-place .h-ems-content .h-ems-place-name span {
  padding: 1px 10px;
  display: inline-block;
}
.h-ems-place .h-ems-content .h-ems-place-name span:hover {
  background-color: #fdf0d1;
  cursor: pointer;
}
.h-ems-place .h-ems-placeList {
  display: block;
  background: #fff;
  height: 200px;
  overflow: auto;
}
.h-ems-place .h-ems-placeList li {
  padding: 5px 10px;
  border-bottom: 1px solid #ccc;
}
.h-ems-place .h-ems-placeList li:hover {
  background-color: #fdf0d1;
  cursor: pointer;
}
.h-ems-place .ivu-icon-ios-close {
  font-size: 30px;
  position: absolute;
  top: 2px;
  right: 10px;
  cursor: pointer;
}
.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all 0.3s ease;
}
.slide-fade-enter,
.slide-fade-leave-to {
  transform: translateY(-10px);
  opacity: 0;
}
</style>
