<template>
  <div class="address-picker-wrap">
    <div
      :class="[
        'address-picker-wrap-txt',
        { placeholder: !pickerValShow && placeholder === '省市区县、乡镇等' }
      ]"
      @click="openPopup"
    >
      {{ pickerValShow || placeholder }}
    </div>
    <cr-popup
      v-model="show"
      position="bottom"
      closeable
      :close-on-click-overlay="false"
      class="popup-head"
    >
      <div class="popup-title">请选择所在地区</div>
      <cr-tabs
        ref="tabs"
        v-model="active"
        class="popup-tab"
        :ellipsis="true"
        color="#ee4155"
        @click="handleTabClick"
      >
        <cr-tab :title="provinceName">
          <ul class="area-panel">
            <li
              v-for="(it, idx) in areaData[0]"
              :key="idx"
              :class="['area-panel__item', { active: provinceTag.addrId === it.addrId }]"
              @click.self="handleItemSelect(0, it)"
            >
              {{ it.addrName }}
            </li>
          </ul>
        </cr-tab>
        <cr-tab :title="cityName">
          <ul class="area-panel">
            <li
              v-for="(it, idx) in areaData[1]"
              :key="idx"
              :class="['area-panel__item', { active: cityTag.addrId === it.addrId }]"
              @click.self="handleItemSelect(1, it)"
            >
              {{ it.addrName }}
            </li>
          </ul>
        </cr-tab>
        <cr-tab :title="distName">
          <ul class="area-panel">
            <li
              v-for="(it, idx) in areaData[2]"
              :key="idx"
              :class="['area-panel__item', { active: distTag.addrId === it.addrId }]"
              @click.self="handleItemSelect(2, it)"
            >
              {{ it.addrName }}
            </li>
          </ul>
        </cr-tab>
        <cr-tab :title="townName">
          <ul class="area-panel">
            <li
              v-for="(it, idx) in areaData[3]"
              :key="idx"
              :class="['area-panel__item', { active: townTag.addrId === it.addrId }]"
              @click.self="handleItemSelect(3, it)"
            >
              {{ it.addrName }}
            </li>
          </ul>
        </cr-tab>
      </cr-tabs>
    </cr-popup>
  </div>
</template>

<script>
import address from '@/api/address.api';
const areaDefault = ['请选择', '请选择', '请选择', '请选择'];
const tagMap = ['provinceTag', 'cityTag', 'distTag', 'townTag'];
export default {
  name: 'PopupAreaTabPicker',
  props: {
    value: null,
    placeholder: [String, Array]
    // placeholder: {
    //   type: String,
    //   default: '请选择'
    // }
  },
  data() {
    return {
      show: false,
      active: 1, // 定位cur下标
      selectData: [],
      cityTag: {},
      provinceTag: {},
      distTag: {},
      townTag: {},
      areaData: [[], [], [], []], // 缓存四个tab数据列表
      pickerValShow: '',
      addressValue: []
    };
  },
  computed: {
    provinceName() {
      return this.areaData[0].length > 0 ? this.provinceTag.addrName : '';
    },
    cityName() {
      return this.areaData[1].length > 0 ? this.cityTag.addrName : '';
    },
    distName() {
      return this.areaData[2].length > 0 ? this.distTag.addrName : '';
    },
    townName() {
      return this.areaData[3].length > 0 ? this.townTag.addrName : '';
    }
  },
  watch: {
    show: {
      immediate: true,
      handler(val) {
        this.$emit('popup', val);
      }
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    handleTabClick(name) {
      // 清空当前选中tab之后的选中文字
      for (let i = name + 1; i < 4; i++) {
        this[tagMap[i]] = {
          addrId: '',
          addrLevel: i,
          addrName: areaDefault[i]
        };
      }
    },
    handleItemSelect(index, it) {
      const selectData = JSON.parse(JSON.stringify(this.selectData));
      const active = index + 1;
      selectData[index] = it;
      this[tagMap[index]] = it;
      for (let i = index + 1; i < 4; i++) {
        this[tagMap[i]] = {
          addrId: '',
          addrLevel: i,
          addrName: areaDefault[i]
        };
        selectData[i] = {
          addrId: '',
          addrName: '',
          addrLevel: i
        };
        this.areaData[i] = [];
      }
      this.getAddrList(it.addrId, active);
      this.$set(this, 'selectData', selectData);
      if (index === 3) {
        this.show = false;
        this.submit();
      }
    },
    // 获取地址列表
    async getAddrList(addrId = '', index = 0) {
      const areaData = JSON.parse(JSON.stringify(this.areaData)); // 浅拷贝
      const res = await address.zoneList(addrId); // 获取地址列表默认取一级
      const addrList = res[0].addrList || [];
      areaData[index] = addrList;
      if (addrList && addrList.length) {
        // 点击最后一级别addrId 所得addrList数据为空
        this.active = index;
      } else {
        this.show = false; // 隐藏底部弹出层
        this.submit(); // 提交选中数据
      }
      this.$set(this, 'areaData', areaData);
    },
    submit() {
      const address = this.selectData.filter(item => item.addrId);
      const addressName = address.map(item => item.addrName);
      const addressValue = address.map(item => item.addrId);
      this.pickerValShow = addressName.join(',');
      this.$emit('input', addressValue);
      this.$emit('finish', {
        id: addressValue,
        items: this.selectData
      });
    },
    init() {
      this.selectData = [];
      this.areaData = [[], [], [], []];
      this.pickerValShow = '';
      this.selectData[0] = {
        addrId: '',
        addrName: '',
        addrLevel: '1'
      };
      for (let i = 0; i < 4; i++) {
        this[tagMap[i]] = {
          addrId: '',
          addrLevel: i + 1,
          addrName: areaDefault[i]
        };
      }
      this.getAddrList();
    },
    openPopup() {
      this.show = true;
      this.$refs.tabs.setLine();
      if (this.value) {
        this.active = this.addressValue.length - 1;
      } else {
        this.active = 0;
      }
    },
    reset() {
      this.init();
    }
  }
};
</script>
<style lang="less" scoped>
// 弹出框头部
.popup-head {
  border-radius: 6px 6px 0 0;
  .popup-title {
    .text-16();
    font-weight: @font-weight-bold;
    color: @black;
    text-align: center;
    padding: 10px 0;
  }
  .popup-tab {
    @{deep} .cr-tabs__item {
      color: #000;
    }
    @{deep} .cr-tabs__item--active {
      color: #ec1500;
    }
  }
}
.address-picker-wrap {
  width: 100%;
  &-txt {
    width: 100%;
    font-size: 15px;
    color: #333333;
    &.placeholder {
      color: #b2b2b2;
      opacity: 0.7;
    }
  }
  @{deep} .cr-popup--close-top-right {
    position: absolute !important;
  }
  @{deep} .cr-popup--close {
    z-index: 999;
    color: #333;
    font-size: 18px;
    padding: 10px;
    top: 4px;
    right: 4px;
  }
  .cr-tabs {
    &__wrap {
      border-bottom: 1px solid #eeeeee;
    }
    &__item {
      flex: none;
      width: 70px;
      height: 40px;
      font-size: 13px;
      text-align: center;
      line-height: 40px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      line-clamp: 1;
      -webkit-box-orient: vertical;
    }
  }
}
.area-panel {
  height: 300px;
  overflow-x: scroll;
  overflow-y: scroll;
  &__item {
    padding: 10px 15px;
    font-size: 14px;
    color: #333;
    &.active {
      color: #ee4155;
    }
  }
}
</style>
