<template>
  <bxs-bottom-sheets
    v-model="isShow"
    title="选择地区"
    @close="close"
    :height="375"
    :prevent-scroll-through="true"
    :use-b-scroll="false"
    @domReady="domReady"
    >
    <div
      class="bx-area-header"
      slot="header"
      >
      <div class="bx-area-title">
        <div
          class="bx-area-cancel"
          @click="close"
          >
          取消
        </div>
        <div>{{ title }}</div>
        <div
          class="bx-area-confirm"
          @click="confirm"
          :class="{'bx-area-confirm--primary': isSelectionDone}"
          >
          确定
        </div>
      </div>
      <div class="bx-area-tabs bx-hairline--bottom">
        <div
          @click="switchTab('provinceItem')"
          class="bx-area-tab"
          :class="{'bx-area-active': tabActive === 'provinceItem'}"
          >
          {{ provinceName || '请选择' }}
        </div>
        <div
          @click="switchTab('cityItem')"
          class="bx-area-tab"
          :class="{'bx-area-active': tabActive === 'cityItem'}"
          v-if="provinceName"
          >
          {{ cityName || '请选择' }}
        </div>
        <div
          @click="switchTab('countyItem')"
          class="bx-area-tab"
          :class="{'bx-area-active': tabActive === 'countyItem'}"
          v-if="cityName && showDistrict && !finish"
          >
          {{ countyName || '请选择' }}
        </div>
      </div>
    </div>
    <div
      class="bx-area-container"
      ref="areaContainer"
      >
      <ul
        class="bx-area-items"
        v-if="tabActive === 'provinceItem'"
        >
        <li
          class="bx-area-item"
          v-for="item in provinceList"
          :key="item[keyName]"
          @click="selectProvince(item[keyName], item[valueName])"
          :class="{'bx-area-active': item[keyName] === provinceCode}"
          ref="areaItem"
          >
          {{ item[valueName] }}
        </li>
      </ul>
      <ul
        class="bx-area-items"
        v-if="tabActive === 'cityItem'"
        >
        <li
          class="bx-area-item"
          v-for="item in cityList"
          :key="item[keyName]"
          @click="selectCity(item[keyName], item[valueName])"
          :class="{'bx-area-active': item[keyName] === cityCode}"
          ref="areaItem"
          >
          {{ item[valueName] }}
        </li>
      </ul>
      <ul
        class="bx-area-items"
        v-if="tabActive === 'countyItem' && showDistrict && !finish"
        >
        <li
          class="bx-area-item"
          v-for="item in countyList"
          :key="item[keyName]"
          @click="selectCounty(item[keyName], item[valueName])"
          :class="{'bx-area-active': item[keyName] === countyCode}"
          ref="areaItem"
          >
          {{ item[valueName] }}
        </li>
      </ul>
    </div>
  </bxs-bottom-sheets>
</template>
<script>
import { create } from '../utils'
import BottomSheets from '../bottom-sheets'

export default create({
  name: 'area',
  props: {
    showDistrict: {
      type: Boolean,
      default: true,
    },
    keyName: {
      type: String,
      default: 'code',
    },
    valueName: {
      type: String,
      default: 'name',
    },
    areaData: {
      type: Object,
      default: () => ({}),
    },
    areaSelect: {
      type: [String, Number],
      default: '',
    },
    title: {
      type: String,
      default: '选择地区',
    },
    value: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      tabActive: 'provinceItem',
      provinceCode: '',
      provinceName: '',
      cityCode: '',
      cityName: '',
      countyCode: '',
      countyName: '',
      provinceList: [],
      cityList: [],
      countyList: [],
      $content: null,
      finish: false,
    }
  },
  computed: {
    isSelectionDone() {
      return (
        this.provinceCode &&
        this.cityCode &&
        (this.countyCode || !this.showDistrict || this.finish)
      )
    },
    isShow: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      },
    },
  },
  watch: {
    isShow(val) {
      if (val) {
        this.init()
      }
    },
  },
  methods: {
    close() {
      this.isShow = false
    },
    init() {
      this.provinceList = this.areaData.provinceList || []
      this.setValues()
    },
    setValues() {
      const proCode = this.areaSelect.toString().slice(0, 2)
      const cityCode = this.areaSelect.toString().slice(0, 4)
      const vm = this
      if (proCode && Array.isArray(this.areaData.provinceList)) {
        const [proFilter] = this.areaData.provinceList.filter(
          item =>
            parseInt(item[vm.keyName], 10) === parseInt(`${proCode}0000`, 10),
        )
        const [cityFilter] = this.areaData.cityList.filter(
          item =>
            parseInt(item[vm.keyName], 10) === parseInt(`${cityCode}00`, 10),
        )
        const [countyFilter] = this.areaData.countyList.filter(
          item =>
            parseInt(item[vm.keyName], 10) === parseInt(vm.areaSelect, 10),
        )
        if (!proFilter || !cityFilter) {
          this.reset()
          return
        }
        vm.selectProvince(proFilter[vm.keyName], proFilter[vm.valueName])
        if (this.areaSelect.toString().slice(2, 6) !== '0000' && cityCode) {
          vm.selectCity(cityFilter[vm.keyName], cityFilter[vm.valueName])
          vm.switchTab('cityItem')
          if (
            this.areaSelect.toString().slice(4, 6) !== '00' &&
            vm.showDistrict
          ) {
            if (countyFilter) {
              vm.selectCounty(
                countyFilter[vm.keyName],
                countyFilter[vm.valueName],
              )
              vm.switchTab('countyItem')
            } else {
              this.reset()
            }
          }
        }
      } else {
        this.reset()
      }
    },
    reset() {
      this.tabActive = 'provinceItem'
      this.provinceCode = ''
      this.provinceName = ''
      this.cityCode = ''
      this.cityName = ''
      this.countyCode = ''
      this.countyName = ''
    },
    switchTab(activeTab) {
      this.tabActive = activeTab
      let indexItem = 0
      if (activeTab === 'provinceItem') {
        if (this.provinceCode) {
          indexItem = this.provinceList
            .map(item => item[this.keyName])
            .indexOf(this.provinceCode)
        }
      } else if (activeTab === 'cityItem') {
        if (this.cityCode) {
          indexItem = this.cityList
            .map(item => item[this.keyName])
            .indexOf(this.cityCode)
        }
      } else if (activeTab === 'countyItem') {
        if (this.countyCode) {
          indexItem = this.countyList
            .map(item => item[this.keyName])
            .indexOf(this.countyCode)
        }
      }
      this.$nextTick(() => {
        if (indexItem) {
          if (this.$refs.areaItem && this.$refs.areaItem.length) {
            const areaItem =
              this.$refs.areaItem && this.$refs.areaItem[0].offsetHeight
            this.resetTop((indexItem - 2) * areaItem)
          }
        } else {
          this.resetTop()
        }
      })
    },
    domReady(dom) {
      this.$content = dom.content
    },
    resetTop(y = 0) {
      this.$nextTick(() => {
        if (this.$content) {
          this.$content.scrollTop = y
        }
      })
    },
    selectProvince(provinceCode, provinceName) {
      if (this.provinceCode !== provinceCode) {
        this.provinceCode = provinceCode
        this.provinceName = provinceName
        this.cityCode = ''
        this.cityName = ''
        this.countyCode = ''
        this.countyName = ''
      }

      this.tabActive = 'cityItem'
      this.cityList = []

      this.areaData.cityList.forEach(city => {
        if (city.parentId === provinceCode) {
          this.cityList.push(city)
        }
      })
      this.resetTop()
    },
    selectCity(cityCode, cityName) {
      if (this.cityCode !== cityCode) {
        this.cityCode = cityCode
        this.cityName = cityName
        this.countyCode = ''
        this.countyName = ''
      }

      if (this.showDistrict) {
        this.countyList = []
        this.areaData.countyList.forEach(county => {
          if (county.parentId === cityCode) {
            this.countyList.push(county)
          }
        })
        if (this.countyList.length) {
          this.tabActive = 'countyItem'
          this.resetTop()
          this.finish = false
        } else {
          this.finish = true
        }
      }
    },
    selectCounty(countyCode, countyName) {
      this.countyCode = countyCode
      this.countyName = countyName
    },
    confirm() {
      if (!this.isSelectionDone) {
        return
      }
      this.$emit('confirm', {
        provinceCode: this.provinceCode,
        provinceName: this.provinceName,
        cityCode: this.cityCode,
        cityName: this.cityName,
        countyCode: this.countyCode,
        countyName: this.countyName,
      })
      this.isShow = false
    },
  },
  components: {
    [BottomSheets.name]: BottomSheets,
  },
})
</script>
<style>
@import './index.css';
</style>
