<template>
  <div>
    <a-cascader
      v-if="type === 'cascader'"
      :options="tagData.divisionsForTree"
      :placeholder="placeholder"
      style="width: 100%;"
      :size="size"
    />
    <a-select
      ref="select"
      :size="size"
      v-model="valueView"
      style="width: 100%;"
      :dropdownMatchSelectWidth="false"
      :dropdownStyle="dropdownStyle"
      :placeholder="placeholder"
      @blur="selectBlurHandle"
      allow-clear
      :getPopupContainer=" triggerNode => { return triggerNode.parentNode } "
      :open="selectOpen"
      @focus="handleFocus"
      :style="inputStyle">
      <div slot="dropdownRender">
        <a-tabs
          v-model="activeKey"
          :size="size"
          @mousedown="handleTabMousedown"
        >
          <a-tab-pane
            :tab="view.key"
            v-for="(view,index) in viewArr"
            :key="view.key"
            v-if="contexts > index"
            :disabled="tagData[view.value].length === 0">
            <a-input
              v-model="searchKeyword[index]"
              placeholder="搜索"
              class="search-input"
              style="margin-bottom: 10px; width: 100%;"
            />
            <a-checkable-tag
              :style="tagStyle"
              v-for="item of filteredTags(view.value, index)"
              :key="item.code"
              @change="tagClick(view.key, item)"
            >
              <a-tooltip
                placement="top"
                :mouseEnterDelay="0.5"
                :title="item.name"
                :getPopupContainer=" triggerNode => { return triggerNode.parentElement } "
              >
                {{ item?.name?.length > 8 ? `${item.name.slice(0, 8)}...` : item.name }}
              </a-tooltip>
            </a-checkable-tag>
            <a-empty v-if="tagData[view.value].length === 0" :img="Empty.PRESENTED_IMAGE_SIMPLE"></a-empty>
          </a-tab-pane>
          <a-button slot="tabBarExtraContent" @click="back">
            收起
          </a-button>
        </a-tabs>
      </div>
    </a-select>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { runLogic } from '@vue2-client/services/api/common'
import { handleTree } from '@vue2-client/utils/util'
import { Empty } from 'ant-design-vue'

const viewArr = [
  {
    key: '省/直辖市',
    value: 'divisionsForTree',
  }, {
    key: '市',
    value: 'cityData',
  }, {
    key: '区',
    value: 'areaData',
  }, {
    key: '街道',
    value: 'streetData',
  }, {
    key: '小区',
    value: 'communityData',
  }
]
export default {
  name: 'CitySelect',
  data () {
    return {
      Empty,
      open: false,
      tagData: {
        divisionsForTree: [],
        // 市
        cityData: [],
        // 区
        areaData: [],
        // 街道
        streetData: [],
        // 小区
        communityData: [],
      },
      // model: {
      //   provinceModel: { name: '', code: '' },
      //   cityModel: { name: '', code: '' },
      //   areaModel: { name: '', code: '' },
      //   streetModel: { name: '', code: '' }
      // },
      model: [
        { name: '', code: '' },
        { name: '', code: '' },
        { name: '', code: '' },
        { name: '', code: '' },
        { name: '', code: '' }
      ],
      // 控制标签
      activeKey: '省/直辖市',
      // 遍历以渲染页面
      viewArr,
      // 框内显示值 valueView
      valueView: undefined,
      // 搜索关键字
      searchKeyword: ['', '', '', '', ''],
      selectOpen: false,
    }
  },
  async mounted () {
    runLogic('getOperatingAreas', {
      orgId: this.currUser.orgid
    }, 'af-revenue').then(res => {
      this.tagData.divisionsForTree = handleTree(res, 'code', 'parentcode')
      if (this.value) {
        this.setValue(this.value, res)
      }
    })
  },
  model: {
    prop: 'value',
    event: 'onChange'
  },
  computed: {
    ...mapState('account', { currUser: 'user' })
  },
  props: {
    // 页面渲染内容  默认 省市区街道 四个 所以是4  5 是到小区
    contexts: {
      type: Number,
      default: 4
    },
    placeholder: {
      type: String,
      default: '请选择省市区'
    },
    // small lage 输入框大小
    size: {
      type: String,
      default: undefined
    },
    // 类型 simple / undefined
    // simple 就是用的 cascader  不穿就是用的 自己封装的
    type: {
      type: String,
      default: undefined
    },
    // 框的样式
    inputStyle: {
      type: Object,
      default: () => {
      }
    },
    // 下拉框的样式
    dropdownStyle: {
      type: Object,
      default: () => {
        return {
          width: '35rem',
          padding: '1%'
        }
      }
    },
    // 标签的样式
    tagStyle: {
      type: Object,
      default: () => {
        return {
          fontSize: '0.88rem',
          width: '23%',
          textAlign: 'left',
          margin: '0.5%',
          cursor: 'pointer'
        }
      }
    },
    // 用于v-model 绑定
    value: {
      type: String,
      default: undefined
    },
    // 用于仅用于展示
    defaultValue: {
      type: String,
      default: undefined
    },
    // 用于v-model 绑定 code :最后一级的code  address: 所有级拼接的地址
    valueType: {
      type: String,
      default: 'code'
    }
  },
  watch: {
    value () {
      if (!this.value && this.valueView) {
        /// 兼容外层重置方法
        this.model = [
          { name: '', code: '' },
          { name: '', code: '' },
          { name: '', code: '' },
          { name: '', code: '' },
          { name: '', code: '' }
        ]
        this.getResultText(this.contexts)
      }
    }
  },
  methods: {
    handleTabMousedown (e) {
      console.log('aaaaa', e)
      const isInput = e.target.closest('.search-input')
      if (!isInput) {
        e.preventDefault()
      }
    },
    handleFocus () {
      this.selectOpen = true
    },
    // 根据搜索关键字过滤标签
    filteredTags (key, index) {
      if (!this.searchKeyword[index]) {
        return this.tagData[key] || []
      }
      return (this.tagData[key] || []).filter(item =>
        item.name.toLowerCase().includes(this.searchKeyword[index].toLowerCase())
      )
    },
    setValue (code, tree) {
      const findNode = (code, tree) => {
        for (let i = 0; i < tree.length; i++) {
          if (tree[i].code === code) {
            return tree[i]
          } else if (tree[i].children && tree[i].children.length > 0) {
            const node = findNode(code, tree[i].children)
            if (node) {
              return node
            }
          }
        }
      }

      const findParent = (code, tree, parent = null) => {
        for (let i = 0; i < tree.length; i++) {
          if (tree[i].code === code) {
            return parent
          } else if (tree[i].children && tree[i].children.length > 0) {
            const node = findParent(code, tree[i].children, tree[i])
            if (node) {
              return node
            }
          }
        }
      }

      const node = findNode(code, tree)
      if (node) {
        this.model[this.contexts - 1].name = node.name
        this.model[this.contexts - 1].code = node.code
        let parent = findParent(code, tree)
        for (let i = this.contexts - 2; i >= 0; i--) {
          this.model[i].name = parent ? parent.name : null
          this.model[i].code = parent ? parent.code : null
          if (i < this.contexts - 1 && parent) {
            parent = findParent(parent.code, tree)
          }
        }
        this.getResultText(this.contexts)
      }
    },
    tagClick (e, item) {
      if (e === '省/直辖市') {
        // 如果是同一个标签
        if (this.model[0].name !== item.name) {
          this.tagData.cityData = item.children
          this.tagData.areaData = []
          this.tagData.streetData = []
          this.model[0].name = item.name
          this.model[0].code = item.code
          this.model[1] = { name: '', code: '' }
          this.model[2] = { name: '', code: '' }
          this.model[3] = { name: '', code: '' }
        }
        if (this.contexts !== 1) {
          this.activeKey = '市'
        }
        this.getResultText(1)
      } else if (e === '市') {
        if (this.model[1].name !== item.name) {
          this.tagData.areaData = item.children
          this.tagData.streetData = []
          this.model[1].name = item.name
          this.model[1].code = item.code
          this.model[2] = { name: '', code: '' }
          this.model[3] = { name: '', code: '' }
        }
        if (this.contexts !== 2) {
          this.activeKey = '区'
        }
        this.getResultText(2)
      } else if (e === '区') {
        if (this.model[2].name !== item.name) {
          this.tagData.streetData = item.children || []
          this.model[2].name = item.name
          this.model[2].code = item.code
          this.model[3] = { name: '', code: '' }
        }
        if (this.contexts !== 3) {
          this.activeKey = '街道'
        }
        this.getResultText(3)
      } else if (e === '街道') {
        if (this.model[3].name !== item.name) {
          this.tagData.communityData = item.children || []
          this.model[3].name = item.name
          this.model[3].code = item.code

          this.model[4] = { name: '', code: '' }
        }
        if (this.contexts !== 4) {
          this.activeKey = '小区'
        }
        this.getResultText(4)
      } else if (e === '小区') {
        if (this.model[4].name !== item.name) {
          this.model[4].name = item.name
          this.model[4].code = item.code
        }
        this.getResultText(5)
      }
    },
    getResultText (tag) {
      const address = []
      let code = ''
      for (let i = 0; i < this.contexts; i++) {
        if (this.model[i].name && this.model[i].name !== '') {
          address.push(this.model[i].name)
        }
        code = this.model[i].code ?? ''
      }
      this.valueView = address.length === 0 ? undefined : address.join('')
      if (tag === this.contexts) {
        this.selectOpen = false
        this.$refs.select.blur()
        // this.$emit('onChange', this.valueType === 'address' ? address.join('') : code)
        this.$emit('onChange', code)
      }
    },
    // 失去焦点回调
    selectBlurHandle () {
      if (!this.model[this.contexts - 1].code || this.model[this.contexts - 1].code === '') {
        this.valueView = undefined
      }
    },
    // 退出下拉菜单
    back () {
      this.selectOpen = false
      this.selectBlurHandle()
    }
  }
}
</script>
