<template>
  <view>
    <view class="xd-address" v-show="isShowAddress">
      <view class="xd-address__close" @click="close">
        <xd-font-icon
          size="36"
          icon="iconguanbi2"
          color="#999"
          :width="40"
          :height="40"
        ></xd-font-icon>
      </view>
      <view class="xd-address__title">添加收货地址</view>
      <view class="xd-address__body">
        <view class="xd-address__body-item">
          <view class="xd-address__body-item-label">收货人</view>
          <view class="xd-address__body-item-input">
            <input
              class="xd-address__body-item-input-el"
              placeholder-class="xd-address__body-item-input-placeholder"
              @confirm="doneInput"
              placeholder="收货人"
              :adjust-position="false"
              maxlength="20"
              v-model="receipt_username"/>
          </view>
          <view class="xd-address__body-item-line" :style="{borderColor: styleMainColor}"></view>
        </view>
        <view class="xd-address__body-item">
          <view class="xd-address__body-item-label">手机号码</view>
          <view class="xd-address__body-item-input">
            <input
              class="xd-address__body-item-input-el"
              placeholder-class="xd-address__body-item-input-placeholder"
              @confirm="doneInput"
              placeholder="手机号码"
              :adjust-position="false"
              v-model="receipt_phone"/>
          </view>
          <view class="xd-address__body-item-line" :style="{borderColor: styleMainColor}"></view>
        </view>
        <view class="xd-address__body-item">
          <view class="xd-address__body-item-label">所在地区</view>
          <view class="xd-address__body-item-input" @click="handleRegion">
            <view style="color:#bbb" v-if="!receipt_region_name">所在地区</view>
            <view v-else class="xd-address__body-content">{{receipt_region_name}}</view>
          </view>
          <view @click="toLocation">
            <xd-font-icon size="30" icon="iconshouhuodizhi" color="#999"></xd-font-icon>
          </view>
          <view class="xd-address__body-item-line" :style="{borderColor: styleMainColor, width: '95%'}"></view>
        </view>
        <view class="xd-address__body-item">
          <view class="xd-address__body-item-label">详细地址</view>
          <view class="xd-address__body-item-input">
            <textarea
              class="xd-address__body-item-input-textarea"
              placeholder-class="xd-address__body-item-input-placeholder"
              @confirm="doneInput"
              placeholder="如道路、门牌号、小区、楼栋号、单元室等"
              :adjust-position="false"
              :focus="focus"
              auto-height
              maxlength="100"
              :selection-start="focusNumber"
              v-model="receipt_address"></textarea>
            <div class="xd-address__body-item-input-tips" v-if="showTips">记得完善门牌号</div>
          </view>
          <view class="xd-address__body-item-line" :style="{borderColor: styleMainColor}"></view>
        </view>
      </view>
      <view class="xd-address__set">
        <view>设为默认地址</view>
        <view>
          <xd-switch v-model="receipt_default" :checked="receipt_default" size="small"></xd-switch>
        </view>
      </view>
      <view class="xd-address__btn">
        <xd-button btn-type="primary" @click="save">保存</xd-button>
      </view>
    </view>
    <view class="xd-select" v-show="!isShowAddress">
      <view class="xd-address__close" @click="isShowAddress=!isShowAddress">
        <xd-font-icon
          size="36"
          icon="iconguanbi2"
          color="#999"
          :width="40"
          :height="40"
        ></xd-font-icon>
      </view>
      <view class="xd-select__title">请选择所在区域</view>
      <view class="xd-select__body">
        <view class="xd-select__body-warper">
          <view
            class="xd-select__body-item"
            v-for="(item,index) in city_title"
            :key="index"
          >
            <view
              class="xd-select__body-item-text"
              @click="reSelectCity(index)"
            >{{city_name[index]||item}}
            </view>
            <view
              class="xd-select__body-item-icon"
              :style="{
                borderColor : styleMainColor,
                background: (level < index? '#fff': styleMainColor)
              }"
            ></view>
          </view>
        </view>
        <view class="xd-select__body-line" :style="{background:styleMainColor}"></view>
      </view>
      <view class="xd-select__list" v-if="cityList.length > 0">
        <view
          class="xd-select__list-item"
          v-for="(item,index) in cityList"
          :key="index"
        >
          <text @click="selectCity(item)">{{item.label}}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import XdSwitch from "@/components/XdSwitch/XdSwitch";
  import XdButton from "@/components/XdButton/XdButton";
  import XdFontIcon from "@/components/XdFontIcon/XdFontIcon";
  import {
    getParentsStyle, //获取页面风格单个键值值
  } from '@/utils/xd.base';

  export default {
    name: "XdAddress",
    components: {
      XdSwitch,
      XdButton,
      XdFontIcon
    },
    props: {
      citySeparator: {
        type: String,
        default: ' '
      },

      defaultValue: {
        type: Object | null,
        default: null
      }
    },
    data() {
      return {
        id: null,

        //添加地址
        receipt_username: '', //收货人
        receipt_phone: '', //手机号码
        receipt_address: '', //详情地址
        receipt_region: {}, //所在地址
        receipt_region_name: '',//城市地址
        receipt_default: false, //是否默认

        //切换添加收货地址与切换城市UI
        isShowAddress: true, //是否显示添加地址

        //选择城市
        level: -1, //-1 表示未选择任何城市 备注：0=>省份/区域  1=>城市  2=> 区/县   3=>街道
        maxLevel: 4, //最大4级城市
        maxStatus: false, //是否已到最大级别
        cityList: [],
        city_name: [], //城市名称
        city_code: [], //城市代码
        city_selected_data: [],  //选择城市详情信息
        city_title: ['省份/区域', '城市', '区/县', '街道'],

        location: null, //用户定位信息
        showTips: false, //是否显示提示
        focus: false,
        focusNumber: -1,
        latitude: null,
        longitude: null,
        
        //使用全局主样式
        styleMainColor: '',
      }
    },
    computed: {

      getAddress() {
        return {
          id: this.id,
          receipt_username: this.receipt_username,
          receipt_phone: this.receipt_phone,
          receipt_address: this.receipt_address,
          receipt_default: this.receipt_default,
          receipt_region: this.city_selected_data,
          receipt_city_name: this.city_name,
          receipt_city_code: this.city_code,
          region_name: this.receipt_region_name,
          latitude: this.latitude,
          longitude: this.longitude
        }
      },
    },
  
    async created() {
      this.styleMainColor = await getParentsStyle(this.$parent, '$mainColor')
      
      this.setValue();
      
      /**监听用户定位成功事件**/
      this.$bus.$on('onUserLocation', (location) => {
        console.log('onUserLocation', location)
        this.location = location;
        this.latitude = location['latitude'];
        this.longitude = location['longitude'];
        this.receipt_address = location['sourceData']['title'];

        this.handleParse(location);
        this.showTips = true;
        setTimeout(() => {
          this.focus = true;
          this.focusNumber = 200
        }, 100)

        setTimeout(() => {
          this.showTips = false
        }, 3000)
      });


      if (this.level === -1) {
        this.getCity(0);
      }
    },

    watch: {
      defaultValue() {
        this.setValue();
      }
    },

    methods: {
      handleRegion() {
        if (!this.location) {
          this.toLocation();
        } else {
          this.isShowAddress = !this.isShowAddress
        }
      },

      handleParse(location) {
        this.$emit('onAddressToCode', location, (res) => {
          this.city_name = res['city_name'] || [];
          this.city_code = res['city_code'] || [];
          this.city_selected_data = res['city_selected_data'] || [];
          this.receipt_region_name = res['receipt_region_name'] || '';
        })
      },


      setValue() {
        if (this.$xdUniHelper.checkVarType(this.defaultValue) === 'object') {
          if (this.defaultValue['latitude']
            && this.defaultValue['longitude']
            && this.defaultValue['receipt_address']
          ) {
            this.location = {
              latitude: this.defaultValue['latitude'],
              longitude: this.defaultValue['longitude'],
              address: this.defaultValue['receipt_address']
            }
          }

          Object.keys(this.defaultValue).map((key) => {
            this[key] = this.defaultValue[key];
          })
        }
      },

      doneInput() {
        uni.hideKeyboard()
      },

      setReceiptRegionName() {
        this.receipt_region_name = this.city_name.join(this.citySeparator);
      },

      /**
       * @description 点击定位打开定位页面
       */
      toLocation() {
        this.$emit('onToLocation');
      },

      /**
       * @description 重新选择城市
       */
      reSelectCity(level) {
        //选择隔空城市不操作
        if (level - this.level > 1) {
          return;
        }
        this.city_code = this.city_code.splice(0, level);
        this.city_name = this.city_name.splice(0, level);
        this.city_selected_data = this.city_selected_data.splice(0, level);
        this.level = level - 1;

        //获取城市信息
        if (this.level === -1) {
          this.getCity(0);
        } else {
          this.getCity(this.city_code[this.level]);
        }
      },

      selectCity(item) {
        if (this.level < (this.maxLevel - 1)) {
          this.level++;
        }


        //保存信息
        this.$set(this.city_name, this.level, item.label)
        this.$set(this.city_code, this.level, item.value)
        this.$set(this.city_selected_data, this.level, item)
        // this.city_name[this.level] = item.label;
        // this.city_code[this.level] = item.value;
        // this.city_selected_data[this.level] = item;

        //是否启动获取城市列表
        if (this.level < (this.maxLevel - 1)) {
          this.getCity(item.value);
        }
        //选择完成操作
        else {
          this.isShowAddress = true;
          this.setReceiptRegionName()
        }
      },

      /**
       * @description 获取城市数据接口
       * @param parentId
       * @example 城市数据格式 [{label: '北京市'，value: 1},{label: '广东省'，value: 2}]
       */
      getCity(parentId) {
        this.cityList = [];
        this.$emit('getCity', {parentId, level: this.level + 1}, (cityList) => {
          if (!this.$xdUniHelper.isEmpty(cityList)) {
            if (!cityList[0]['label'] || !cityList[0]['value']) {
              this.cityList = [];
              throw new Error(`
                1、当前数据格式错误，
                2、正确格式需包含(label,value)字段。
                例如: [{label: \'北京市\'，value: 1},{label: \'广东省\'，value: 2}]`
              );
            } else {
              this.cityList = this.$xdUniHelper.cloneDeep(cityList);
            }
          } else {
            //选择完成操作
            this.isShowAddress = true;
            this.setReceiptRegionName();
            this.cityList = [];
          }
        })
      },

      /**
       * @description 保存事件
       */
      save() {
        this.$emit('save', this.getAddress);
      },

      close() {
        this.$emit('close');
      }
    }
  }
</script>

<style scoped lang="less">

  .xd-address__body-content {
    line-height: unit(36, rpx) !important;

    & * {
      line-height: unit(36, rpx) !important;
    }

  }

  .xd-address {
    padding: unit(40, rpx);
    font-size: @xd-font-size-base + 1;
    position: relative;

    &__close {
      width: unit(44, rpx);
      height: unit(44, rpx);
      position: absolute;
      top: unit(10, rpx);
      right: unit(10, rpx);
      z-index: 2;

      /deep/ .xd-iconfont {
        display: flex;
        justify-content: center;
        align-items: center;
      }

    }


    &__title {
      text-align: center;
      line-height: unit(64, rpx);
    }

    &__body {
      &-item {
        height: unit(102, rpx);
        line-height: unit(102, rpx);
        position: relative;
        display: flex;
        justify-content: flex-start;
        align-items: center;

        &-label {
          width: unit(120, rpx);
          padding-right: unit(20, rpx);
        }

        &-input {
          flex: 1;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          position: relative;

          &-tips {
            background: #333;
            color: #fff;
            font-size: unit(22, rpx);
            border-radius: unit(8, rpx);
            position: absolute;
            bottom: unit(-80, rpx);
            line-height: unit(36, rpx);
            padding: unit(10, rpx) unit(10, rpx);
            left: 0;
            opacity: .8;
            z-index: 300;
          }

          &-textarea {
            font-size: @xd-font-size-base + 1;
            width: 100%;
            height: unit(40, rpx);
            line-height: unit(40, rpx);
          }

          &-el {
            font-size: @xd-font-size-base + 1;
            width: 100%;
          }

          /deep/ &-placeholder {
            font-size: @xd-font-size-base + 1;
            color: #ccc;
            line-height: unit(40, rpx);
          }
        }

        &-line {
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          border-bottom-width: 1px;
          border-bottom-style: solid;
          opacity: 0.2;
        }
      }
    }

    &__set {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: @xd-font-size-base + 1;
      height: unit(102, rpx);
      line-height: unit(102, rpx);
    }
  }

  .xd-select {
    padding: unit(40, rpx);
    font-size: @xd-font-size-base + 1;
    position: relative;

    &__close {
      width: unit(44, rpx);
      height: unit(44, rpx);
      position: absolute;
      top: unit(10, rpx);
      right: unit(10, rpx);
      z-index: 2;

      /deep/ .xd-iconfont {
        display: flex;
        justify-content: center;
        align-items: center;
      }

    }

    &__title {
      text-align: center;
      line-height: unit(64, rpx);
      margin-bottom: unit(30, rpx);
    }

    &__body {
      position: relative;
      height: unit(60, rpx);

      &-warper {
        height: unit(60, rpx);
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      &-item {
        height: 100%;
        width: 25%;
        flex: 1;
        text-align: center;
        position: relative;

        &-text {
          height: 100%;
          line-height: unit(60, rpx);
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
          word-break: break-all;
        }

        &-icon {
          position: absolute;
          bottom: unit(-10, rpx);
          left: 50%;
          transform: translateX(-50%);
          height: unit(16, rpx);
          width: unit(16, rpx);
          box-sizing: border-box;
          border-width: 1px;
          border-style: solid;
          border-radius: 50%;
          background: #fff;
        }
      }

      &-line {
        height: 2px;
      }
    }

    &__list {
      margin: unit(20, rpx) 0;
      height: 40vh;
      overflow-y: auto;

      &-item {
        line-height: unit(60, rpx);
        height: unit(60, rpx);
      }
    }
  }
</style>
