<template>
  <a-cascader
    :options="options"
    :load-data="loadData"
    placeholder="请选择所在区域"
    :change-on-select="false"
    :default-value="defaultValueCascader"
    :fieldNames="fieldNames"
    v-model="defaultValueCascader"
    @change="onChange"
  />
</template>

<script>
import { axios } from '@/utils/request'
import pick from 'lodash.pick'

/**
 * 不支持defaultValue  支持initialValue   支持value
 */
export default {
  name: 'CityCascader',
  props: {
    placeholder: { // 按钮显示文本
      type: String,
      default: ''
    },
    changeOnSelect: {
      type: Boolean,
      default: false
    },
    // 被选择的对象，修改的时候需要传参
    // regionCode: {
    //   type: String,
    //   default: '0'
    // },
    // eslint-disable-next-line vue/require-default-prop
    defaultValue: [String, Number],
    // eslint-disable-next-line vue/require-default-prop
    value: [String, Number],
    // 是否加载树形结构，修改的时候需要传擦
    showParent: {
      type: Boolean,
      default: true
    },
    // 最大层级 从0开始
    maxLevel: {
      type: Number,
      default: 3
    },
    fieldNames: {
      type: Object,
      default: () => ({
        label: 'name',
        value: 'regionCode',
        fullName: 'fullName',
        children: 'children',
        level: 'level'
      })
    }
  },
  data () {
    return {
      defaultValueCascader: [],
      regionCode: '0',
      options: [],
      isInit: true

    }
  },
  watch: {
    regionCode: function (val, oldVal) {
      this.reloadData(val, true)
    },
    value: function (val, oldVal) {
      this.regionCode = this.BaseTool.Object.isNotBlank(val) ? val : (this.defaultValue | '0')
    }
  },
  created () {
    if (this.BaseTool.Object.isNotBlank(this.value)) {
      this.reloadData(this.value, false)
    } else {
      this.reloadData(this.regionCode, false)
    }
  },
  methods: {
    async reloadData (val, isWitch) {
      if (isWitch) {
        this.isInit = false
      }
      if (!isWitch && !this.isInit) {
        return
      }
      if (this.showParent) {
        if (this.BaseTool.String.isNotBlank(val) && val !== '0') {
          if (val.length >= 12) {
            this.defaultValueCascader = [val.substr(0, 2), val.substr(0, 4), val.substr(0, 6), val.substr(0, 9), val.substr(0, 12)]
          } else if (val.length >= 9) {
            this.defaultValueCascader = [val.substr(0, 2), val.substr(0, 4), val.substr(0, 6), val.substr(0, 9)]
          } else if (val.length >= 6) {
            this.defaultValueCascader = [val.substr(0, 2), val.substr(0, 4), val.substr(0, 6)]
          } else if (val.length >= 4) {
            this.defaultValueCascader = [val.substr(0, 2), val.substr(0, 4)]
          } else if (val.length >= 2) {
            this.defaultValueCascader = [val.substr(0, 2)]
          } else {
            this.defaultValueCascader = []
          }
        } else {
          this.defaultValueCascader = []
        }
      }
      if (this.showParent && val !== '0') {
        const d = await this.treeBaseVOCityInfo({ regionCode: val })
        if (!isWitch && !this.isInit) {

        } else {
          this.options = this.treeDataToOptions(d.data.children)
        }
      } else {
        const d = await this.baseVOCityInfo({ parentId: val })
        if (!isWitch && !this.isInit) {

        } else {
          this.options = this.dataToOptions(d.data.children)
        }
      }
    },
    loadData: function (selectedOptions) {
      const parentVO = selectedOptions[selectedOptions.length - 1]
      parentVO.loading = true
      // 获取主键
      const regionCode = parentVO[this.fieldNames.value]
      this.baseVOCityInfo({ parentId: regionCode }).then((res) => {
        parentVO.loading = false
        parentVO.children = this.dataToOptions(res.data.children)
        this.options = [...this.options]
      })
    },
    treeDataToOptions: function (data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].isSelect) {
          data[i] = this.dataToData(data[i])
        } else {
          data[i] = Object.assign(pick(data[i], [
            this.fieldNames.value,
            this.fieldNames.fullName,
            this.fieldNames.label,
            this.fieldNames.level
          ]))
        }
        data[i].isLeaf = data[i][this.fieldNames.level] >= this.maxLevel
      }
      return data
    },
    dataToData (data) {
      const isLeaf = data[this.fieldNames.level] >= this.maxLevel
      if (isLeaf) {
        return Object.assign(pick(data, [
          this.fieldNames.value,
          this.fieldNames.fullName,
          this.fieldNames.label,
          this.fieldNames.level
        ]))
      }
      const d = Object.assign(pick(data, [
        this.fieldNames.value,
        this.fieldNames.fullName,
        this.fieldNames.label,
        this.fieldNames.level
      ]))
      if (data.isSelect) {
        d.children = []
        for (let i = 0; i < data.children.length; i++) {
          d.children.push(this.dataToData(data.children[i]))
        }
      } else {
        d.isLeaf = d[this.fieldNames.level] >= this.maxLevel
      }

      return d
    },
    dataToOptions: function (data) {
      for (let i = 0; i < data.length; i++) {
        data[i] = Object.assign(pick(data[i], [
          this.fieldNames.value,
          this.fieldNames.fullName,
          this.fieldNames.label,
          this.fieldNames.level
        ]))
        data[i].isLeaf = data[i][this.fieldNames.level] >= this.maxLevel
      }
      return data
    },
    onChange (value, selectedOptions) {
      if (this.BaseTool.Object.isBlank(selectedOptions) || !selectedOptions.length) {
        this.defaultValueCascader = null
        this.$emit('change', null, {})
        return
      }
      const v = selectedOptions[selectedOptions.length - 1]
      this.$emit('change', v[this.fieldNames.value], v)
    },
    baseVOCityInfo: function (parameter) {
      return axios({
        url: `/city/infos/base/${parameter.parentId}`,
        method: 'get',
        headers: {
          'Content-Type': 'application/json;charset=UTF-8'
        }
      })
    },
    treeBaseVOCityInfo: function (parameter) {
      return axios({
        url: `/city/infos/base/tree/${parameter.regionCode}`,
        method: 'get',
        headers: {
          'Content-Type': 'application/json;charset=UTF-8'
        }
      })
    }
  },
  updated: function () {

  }
}
</script>

<style scoped>

</style>
