<template>
  <view v-if="isFromReadonly" class="ml-cascader-picker is-readonly">
    <view class="ml-cascader-picker-readonly-content">{{ selectLabel }}</view>
  </view>
  <view v-else class="ml-cascader-picker" :class="[className || '', {'is-border': border, 'is-clear': value.length}]">
    <view class="ml-cascader-picker-warpper" @click="openPopup()">
      <view class="ml-cascader-picker-text">
        <view v-if="value.length" class="ml-cascader-picker-label">{{ selectLabel }}</view>
        <view v-else class="ml-cascader-picker-placeholder">{{ placeholder }}</view>
      </view>
      <view v-if="clearable && value.length" class="ml-cascader-picker-clear-icon" @click.stop="clearEvent">
        <ml-icon name="delete-filling"></ml-icon>
      </view>
      <view v-else class="ml-cascader-picker-icon">
        <ml-icon name="arrow-right" />
      </view>
    </view>

    <ml-picker-drawer v-model="showPopup" title="请选择" height="500rpx" showConfirmButton showCancelButton @confirm="confirmEvent">
      <picker-view v-if="showPicker" :value="selectIndexs" @change="changeEvent" style="height: 400rpx;text-align: center;">
        <picker-view-column v-for="(num, index) in countLevel" :key="index">
          <view class="ml-cascader-picker-picker-item" v-for="(item, cIndex) in pickerDataMaps[index]" :key="cIndex">{{ item[optLabelField] }}</view>
        </picker-view-column>
      </picker-view>
    </ml-picker-drawer>
  </view>
</template>

<script>
import XEUtils from 'xe-utils'

export default {
  name: 'MlCascaderPicker',
  props: {
    value: Array,
    options: Array,
    border: Boolean,
    placeholder: String,
    clearable: Boolean,
    width: String,
    isAll: Boolean,
    optionProps: Object,
    className: String
  },
  inject: {
    form: {
      from: 'mlForm',
      default: null
    }
  },
  data () {
    return {
      showPopup: false,
      showPicker: false,
      selectIndexs: [0],
      // 最多支持6级
      pickerDataMaps: {
        0: [],
        1: [],
        2: [],
        3: [],
        4: [],
        5: []
      }
    }
  },
  computed: {
    isFromReadonly () {
      return this.form ? this.form.readonly : false
    },
    optOptions () {
      return Object.assign({}, this.optionProps)
    },
    optLabelField () {
      return this.optOptions.label || 'label'
    },
    optValueField () {
      return this.optOptions.value || 'value'
    },
    optChildrenField () {
      return this.optOptions.children || 'children'
    },
    selectItems () {
      return this.value.map((val, index) => {
        const list = this.pickerDataMaps[index]
        const item = list ? list.find(item => item[this.optValueField] === val) : null
        return item
      })
    },
    selectLabel () {
      const labels = []
      for (let i = 0; i < this.selectItems.length; i++) {
        const item = this.selectItems[i]
        if (!item) {
          break
        }
        labels.push(item[this.optLabelField])
      }
      return labels.join(' / ')
    },
    treeOpts () {
      return {
        children: this.optChildrenField
      }
    },
    countLevel () {
      let maxLevel = 1
      XEUtils.eachTree(this.options, (item, index, items, path, parent, nodes) => {
        if (maxLevel < nodes.length) {
          maxLevel = nodes.length
        }
      }, this.treeOpts)
      return maxLevel
    }
  },
  watch: {
    options () {
      this.updatePickerData()
    }
  },
  created () {
    this.updatePickerData()
  },
  methods: {
    closePopup () {
      this.showPopup = false
      this.showPicker = false
    },
    openPopup () {
      this.showPopup = true
      setTimeout(() => {
        this.showPicker = true
      }, 50)
    },
    updatePickerData () {
      const dataMaps = {
        0: this.isAll ? [{ [this.optLabelField]: '全部', [this.optValueField]: '' }].concat(this.options) : this.options,
        1: [],
        2: [],
        3: [],
        4: [],
        5: []
      }
      for (let i = 1; i < this.countLevel; i++) {
        const prevOpts = dataMaps[i - 1]
        let prevItem = null
        if (prevOpts) {
          prevItem = prevOpts[this.selectIndexs[i - 1]]
          // if (!prevItem) {
          //   prevItem = prevOpts.find(item => item[this.optValueField] === prevValue)
          // }
        }
        if (prevItem) {
          const currList = prevItem[this.optChildrenField] || []
          dataMaps[i] = currList
          if (!this.selectIndexs[i]) {
            this.selectIndexs[i] = currList.length ? 0 : null
          }
        }
      }
      this.pickerDataMaps = dataMaps
    },
    changeEvent (e) {
      this.selectIndexs = e.detail.value
      this.updatePickerData()
    },
    clearEvent () {
      const value = []
      this.selectIndexs = [0]
      this.confirmEvent()
      this.$emit('clear', { value })
      this.$emit('change', { value, labels: [], selection: [] })
    },
    confirmEvent () {
      const value = []
      const selection = []
      const labels = []
      this.selectIndexs.slice(0, this.countLevel).forEach((valIndex, colIndex) => {
        if (valIndex !== null) {
          const item = this.pickerDataMaps[colIndex][valIndex]
          selection.push(item || null)
          value.push(item ? item[this.optValueField] : null)
          labels.push(item ? item[this.optLabelField] : '')
        }
      })
      this.$emit('input', value)
      this.$emit('change', { value, labels, selection })
      this.closePopup()
    }
  }
}
</script>

<style lang="scss">
.ml-cascader-picker-readonly-content {
  padding: 20rpx;
}
.ml-cascader-picker {
  width: 100%;
  &.is-border {
    border: 1px solid #e5e5e5;
    background: #fff;
  }
}
.ml-cascader-picker-warpper {
  position: relative;
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 0 20rpx;
  height: 70rpx;
  border-radius: $ml-border-radius;
  .ml-cascader-picker-text {
    flex-grow: 1;
    padding-right: 10rpx;
    overflow: hidden;
    .ml-cascader-picker-label,
    .ml-cascader-picker-placeholder {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  .ml-cascader-picker-clear-icon {
    width: 60rpx;
    display: flex;
    flex-shrink: 0;
    align-items: center;
    justify-content: center;
    background: #fff;
    color: $ml-input-clear-icon-color;
    border-radius: 0 10rpx 10rpx 0;
  }
  .ml-cascader-picker-icon {
    width: 34rpx;
    display: flex;
    flex-shrink: 0;
    align-items: center;
    justify-content: center;
    color: #6a6a6a;
  }
}
.ml-cascader-picker-picker-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
</style>
