<template>
  <el-collapse
    ref="collapse"
    :class="{ 'ht-collapse-mobile': isMobile }"
    :accordion="accordion"
    :value="openDefaultArr"
    @change="handleChange"
  >
    <slot></slot>
  </el-collapse>
</template>
<script>
  import regionValidator from '@/mixins/regionValidator.js'
  import mobileMode from '@/mixins/mobileMode.js'
  export default {
    name: 'HtCollapse',
    mixins: [regionValidator, mobileMode],
    props: {
      accordion: {
        type: Boolean,
        default: false,
      },
      openDefault: {
        type: Array,
        default: () => {
          return []
        },
      },
      isVerify: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        openDefaultArr: [],
        preActiveNames: [],
      }
    },
    watch: {
      openDefault: {
        handler(val) {
          if (val && val.length) {
            //this.openDefaultArr = val
          }
        },
        immediate: true,
      },
      openDefaultArr: {
        handler(val) {
          this.$root.$emit('collapse-active-names', val)
        },
        deep: true,
        immediate: true,
      },
    },
    created() {
      this.$root.$on('add-new-collapse-item', this.handleOnItem)
    },
    mounted() {
      this.openDefaultArr = this.openDefault
      this.preActiveNames = [].concat(this.openDefaultArr)
    },
    beforeDestroy() {
      this.$root.$off('add-new-collapse-item', this.handleOnItem)
    },
    methods: {
      handleOnItem(result, type) {
        if (
          result &&
          !this.openDefaultArr.includes(result) &&
          type != 'collapse'
        ) {
          this.openDefaultArr.push(result)
        }
        // 不论折叠或者展开，默认都展开第一条记录
        if (this.openDefaultArr && this.openDefaultArr.length <= 0) {
          this.openDefaultArr.push(result)
        }
      },
      handleChange(activeNames) {
        // 收起来时才去判断是否校验
        if (activeNames.length < this.preActiveNames.length) {
          if (this.isVerify) {
            this.validateRegion('.el-collapse-item.is-active').then(
              (errorItems) => {
                if (errorItems.length > 0) {
                  // 还原将要折叠的面板
                  this.openDefaultArr = [].concat(this.preActiveNames)
                } else {
                  // 更新当前打开的面板名称数组
                  this.preActiveNames = [].concat(activeNames)
                  this.openDefaultArr = [].concat(activeNames)
                  this.$emit('change', activeNames)
                }
              }
            )
            return
          }
          this.openDefaultArr = [].concat(activeNames)
        }
        this.preActiveNames = [].concat(activeNames)
        this.openDefaultArr = [].concat(activeNames)
        this.$emit('change', activeNames)
      },
    },
  }
</script>
<style lang="scss" scoped>
  .ht-collapse-mobile {
    margin: 0 4px;
  }
</style>
