<template>
  <view class="mapAddress-container">
    <u-form :model="form" class="form" ref="uForm" label-width="100">
      <u-form-item
        label="所在省市区"
        prop="administrativeRegion"
        required
        @click="showMPCityPicker"
      >
        <u-input
          disabled
          disabledColor="#fff"
          class="form-input city-input"
          v-model="form.administrativeRegion"
          placeholder="请选择省市区"
          border="none"
        />
        <u-icon
          slot="right"
          style="display: inline-block; margin-left: 8rpx"
          name="arrow-right"
          size="12"
          color="#aaaaaa"
        ></u-icon>
      </u-form-item>
      <u-form-item label="搜索地址" prop="name" required>
        <u-input
          class="form-input"
          v-model="form.searchAddress"
          placeholder="搜索地址，更快填写"
          @input="handerSearchAddress"
        />
      </u-form-item>
    </u-form>
    <view class="tips" v-if="searchAddressList.length > 0">单击地址确定</view>
    <scroll-view
      v-if="form.searchAddress.length > 0"
      class="uni-swiper-list"
      scroll-y
      scroll-with-animation="true"
      :scroll-top="0"
    >
      <view class="search-address-list" v-if="searchAddressList.length > 0">
        <view
          class="search-address-item"
          v-for="(item, index) of searchAddressList"
          :key="index"
        >
          <view
            class="search-address-item-left"
            @click="handerSetAddress(item)"
          >
            <view class="item-left-name" v-html="item.searchName"></view>
            <view class="item-left-address">
              {{ item.detailedInformation }}
            </view>
          </view>
        </view>
      </view>
      <u-loading-icon mode="circle" v-else-if="isLoading">
        加载中...
      </u-loading-icon>
      <view v-if="searchAddressList.length == 0 && !isLoading">
        暂无该地址，换取个地址
      </view>
    </scroll-view>
    <view class="btn-content">
      <u-button class="btn-confirm" @click="handleConfirm">确定</u-button>
    </view>
    <mpvueCityPicker
      :themeColor="themeColor"
      ref="mpvueCityPicker"
      :pickerValueDefault="cityPickerValueDefault"
      @onCancel="onCancel"
      @onConfirm="onConfirm"
    ></mpvueCityPicker>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
import mpvueCityPicker from "./mpvueCityPicker.vue";
import { GetBaiduSuggestion } from "../../api/audit";
export default {
  name: "mapAddress",
  components: {
    mpvueCityPicker,
  },
  data() {
    return {
      form: {
        administrativeRegion: "",
        searchAddress: "",
        longitude: "",
        latitude: "",
      },
      cityPickerValueDefault: [0, 0, 0],
      themeColor: "#007AFF",
      searchAddressList: [],
      time: 0,
      citys: [],
      selectAddress: "",
      isLoading: false,
      isSelctAddrss: false,
      locationItem: {
        administrativeRegion: {},
        selectAddress: {},
      },
    };
  },
  onHide() {
    this.searchAddressList = [];
  },
  methods: {
    handerSearchAddress(value) {
      if (this.isSelctAddrss) return;

      this.isLoading = true;
      this.searchAddressList = [];
      if (this.citys.length == 0) {
        this.$refs.uToast.show({
          message: "请选择所在地区",
          type: "error",
          duration: 1000,
        });

        setTimeout(() => {
          this.form.searchAddress = "";
        }, 0);

        return;
      }

      if (!this.form.administrativeRegion || !value) {
        console.log(value);
        return;
      }

      let params = {
        query: value,
        region: this.citys[0],
        city_limit: true,
        ret_coordtype: "gcj02ll",
      };

      if (this.time !== null) {
        clearTimeout(this.time);
      }

      // 使用代理服务器解决CORS 具体 请看目录vue.config.js
      this.time = setTimeout(async () => {
        let res = await GetBaiduSuggestion(params);
        if (res && res.status == 0) {
          this.searchAddressList = res.result
            .filter((item) => "location" in item)
            .map((item) => {
              let obj = {
                ...item,
                name: item.name,
                detailedInformation: item.address
                  ? item.address.replace(/-/g, "")
                  : item.name,
              };
              return obj;
            });

          this.searchAddressList.forEach((item) => {
            if (item.name.indexOf(value) >= 0) {
              item.searchName = item.name.replace(
                new RegExp(value, "g"),
                "<font style='color:#ee852f;padding:0 4px'>" + value + "</font>"
              );
              console.log("item.searchName", item.searchName);
            } else {
              item.searchName = item.name;
            }
          });
        }
        this.isLoading = false;
      }, 600);
    },
    onCancel() {},
    onConfirm(e) {
      if (e) {
        this.citys[0] = e.label[1];
        this.citys[1] = e.value[1];
        this.locationItem.administrativeRegion = e;
        this.form.administrativeRegion = e.label.join("");
        console.log(this.form.administrativeRegion);
      }
    },
    showMPCityPicker() {
      this.$refs["mpvueCityPicker"].show();
    },
    handerSetAddress(item) {
      this.isSelctAddrss = true;
      this.form.searchAddress = item.name;
      this.locationItem.selectAddress = item;
      setTimeout(() => {
        this.isSelctAddrss = false;
      }, 600);
    },
    handleConfirm() {
      if (
        !this.locationItem.selectAddress ||
        !this.locationItem.administrativeRegion
      ) {
        return;
      }

      if (this.locationItem) {
        uni.setStorageSync("locationItem", this.locationItem);
      }

      uni.navigateBack();
    },
  },
};
</script>

<style lang="scss">
@import "@/styles/variables.scss";
.mapAddress-container {
  padding: 0 36rpx;
  overflow: hidden;

  .tips {
    margin: 20rpx 0;
    font-size: 26rpx;
    color: #7f7f7f;
  }

  .uni-swiper-list {
    height: calc(100vh - 280px);
  }

  .search-address-list {
    margin: 40rpx 0;

    .search-address-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 40rpx 0;
      border-bottom: 2rpx solid #f0f0f0;

      .search-address-item-left {
        width: 80%;
      }

      .search-address-item-right {
        color: #d7d7d7;
        width: 20%;
        text-align: right;
      }

      rich-text {
        // max-width: 90%;
        max-height: 27px;
        overflow: hidden;
        word-break: break-all; /* break-all(允许在单词内换行。) */
        text-overflow: ellipsis; /* 超出部分省略号 */
        display: -webkit-box; /** 对象作为伸缩盒子模型显示 **/
        -webkit-box-orient: vertical; /** 设置或检索伸缩盒对象的子元素的排列方式 **/
        -webkit-line-clamp: 2; /** 显示的行数 **/
      }

      // .item-left-name rich-text {
      //   white-space: nowrap; /* 确保文本在一行内显示 */
      //   overflow: hidden; /* 隐藏超出容器的文本 */
      //   text-overflow: ellipsis; /* 使用省略符号表示文本超出 */
      //   -webkit-box-orient: vertical;
      //   max-width: 90%;
      //   display: -webkit-box;
      //   box-sizing: border-box;
      // }

      .item-left-name {
        margin-bottom: 20rpx;
      }

      .item-left-address {
        font-size: 24rpx;
        color: #848484;
        white-space: nowrap; /* 确保文本在一行内显示 */
        overflow: hidden; /* 隐藏超出容器的文本 */
        text-overflow: ellipsis; /* 使用省略符号表示文本超出 */
        max-width: 90%;
      }
    }
  }

  .btn-content {
    position: fixed;
    bottom: 24rpx;
    width: 84%;
    padding: 48rpx 24rpx;
  }

  .btn-confirm {
    border-radius: 16rpx;
    background: $base-color;
    color: #fff;
  }

  .city-input {
    pointer-events: none;
  }
}
</style>
