<template>
  <div class="dof-city" ref="city" :style="cityExtendStyle">
    <dof-searchbar ref="dof-searchbar"
                   v-bind="mergeInputConfig"
                   @dofSearchbarInputOnInput="onInput"
                   @dofSearchbarInputReturned="onSubmit"
                   @dofSearchbarCancelClicked="onCancel"></dof-searchbar>

    <dof-tab ref="dof-tab"
             v-if="showTab"
             @dofTabSwitch="onTabSwitch"></dof-tab>

    <dof-indexlist :normal-list="normalList"
                   :hot-list-config="hotListConfig"
                   :nav-style="{ top: '24px'}"
                   :height="listHeight"
                   :show-index="showIndex"
                   :only-show-list="!showNavHeader || onlyShowList"
                   :city-location-config="currentCityLocationConfig"
                   @dofIndexlistItemClicked="onItemClick"></dof-indexlist>

    <dof-result type="noGoods"
                :wrap-style="{top:'84px'}"
                :show="true"
                :customSet="result"
                v-if="showError"></dof-result>
  </div>
</template>

<script>
  import defaultSourceData from './default-data';
  import * as Util from './util';
  import Utils from '../utils';
  import dofTab from './tab.vue';
  import DofSearchbar from '../dof-searchbar';
  import DofResult from '../dof-result';
  import DofIndexlist from '../dof-indexlist';

  export default {
    components: { dofTab, DofSearchbar, DofResult, DofIndexlist },
    props: {
      animationType: {
        type: String,
        default: 'push'
      },
      inputConfig: {
        type: Object,
        default: () => ({})
      },
      sourceData: {
        type: Object,
        default: () => defaultSourceData
      },
      cityStyleType: {
        type: String,
        default: 'list'
      },
      currentLocation: String,
      cityHeight: {
        type: Number,
        default: 0
      },
      showTab: {
        type: Boolean,
        default: false
      },
      showIndex: {
        type: Boolean,
        default: true
      },
      showNavHeader: {
        type: Boolean,
        default: true
      }
    },
    data: () => ({
      tId: null,
      saveDefaultSourceData: {},
      cityData: {},
      onlyShowList: false,
      result: {
        noGoods: {
          pic: 'https://img.alicdn.com/tfs/TB1SpPHkf2H8KJjy0FcXXaDlFXa-200-200.png',
          button: '',
          content: '搜索无结果'
        }
      }
    }),
    created () {
      this.cityData = this.sourceData;
      this.saveDefaultSourceData = this.sourceData;
    },
    computed: {
      cityExtendStyle () {
        return Utils.uiStyle.pageTransitionAnimationStyle(this.animationType);
      },
      currentCityLocationConfig () {
        if (this.currentLocation) {
          return {
            type: this.cityStyleType,
            title: '定位',
            list: [
              { name: this.currentLocation, isLocation: true }
            ]
          };
        } else {
          return {};
        }
      },
      normalList () {
        return Util.getCities(this.cityData.cities);
      },
      hotListConfig () {
        return {
          type: this.cityStyleType,
          title: '热门',
          list: Util.getCities((this.cityData.hotCity))
        };
      },
      showError () {
        const { normalList, hotListConfig } = this;
        return (normalList && normalList.length < 1) && (hotListConfig && hotListConfig.list && hotListConfig.list.length < 1);
      },
      listHeight () {
        // 兼容去头逻辑
        let pageHeight = Utils.env.getPageHeight();

        const { cityHeight } = this;
        if (cityHeight && !isNaN(cityHeight) && cityHeight > 0) {
          pageHeight = cityHeight;
        }
        // searchInput 84
        const tabHeight = this.showTab ? 90 : 0;
        return pageHeight - 84 - tabHeight;
      },
      mergeInputConfig () {
        return {
          autofocus: false,
          alwaysShowCancel: true,
          placeholder: '中文/拼音/首字母',
          ...this.inputConfig
        };
      }
    },
    methods: {
      onTabSwitch (e) {
        this.$emit('dofTabSwitch', e);
      },
      switchTab (i = 0) {
        setTimeout(() => {
          this.$refs['dof-tab'].switchTab(i);
        }, 100);
      },
      onItemClick (e) {
        this.$refs['dof-searchbar'].autoBlur();
        this.show(false);
        this.$emit('dofCityItemSelected', { item: e.item });
      },
      onInput (e) {
        clearTimeout(this.tId);
        const { cities } = this.cityData;
        const { value } = e;
        if (value !== '' && cities && cities.length > 0) {
          const queryData = Util.query(cities, String(value).trim());
          this.cityData = {
            cities: queryData,
            hotCity: []
          };
          this.onlyShowList = true;
        } else {
          this.cityData = this.saveDefaultSourceData;
          this.onlyShowList = false;
        }
        this.tId = setTimeout(() => {
          this.$emit('dofCityOnInput', {
            value: e.value
          });
        }, 300);
      },
      onCancel () {
        this.autoBlur();
        this.show(false);
        this.$emit('dofCityCanceled', {});
      },
      onSubmit (e) {
        this.autoBlur();
        this.$emit('dofCityOnKeyUpEnter', { value: e.value });
      },
      autoBlur () {
        const inputRef = this.$refs['dof-searchbar'];
        inputRef && inputRef.autoBlur();
      },
      show (status = true, callback = null) {
        const ref = this.$refs.city;
        if (this.animationType === 'push') {
          Utils.animation.pageTransitionAnimation(ref, `translateX(${status ? -750 : 750}px)`, status, callback);
        } else if (this.animationType === 'model') {
          Utils.animation.pageTransitionAnimation(ref, `translateY(${status ? -Utils.env.getScreenHeight() : Utils.env.getScreenHeight()}px)`, status, callback);
        }
      }
    }
  };
</script>

<style scoped>
  .dof-city {
    position: fixed;
    width: 750px;
    background-color: #F2F3F4;
  }
</style>
