<template>
  <el-form-item :label="label" :rules="requireRule(!disabled && required, label)" :prop="prop">
    <el-cascader
      v-model="$parent.model[prop]"
      :options="categorys"
      :props="{emitPath: false}"
      :multiple="multiple" :clearable="clearable" filterable :disabled="disabled"/>
  </el-form-item>
</template>

<script>
import mixin from '@/components/element/form/items/mixin'
import { mapGetters } from 'vuex'
import {includes} from 'lodash'
import {categoryList, merchantCategoryList} from '@/api/merchant/merchant'

const extractCategory = (categorys, selections) => {
  return categorys.filter(category => {
          category.childrenCategory = category.childrenCategory?.filter(({categoryId}) => includes(selections, categoryId))
          return  includes(selections, category.categoryId)
        })
        .map(({categoryId, categoryName, childrenCategory}) => ({
          value: categoryId, 
          label: categoryName, 
          children: childrenCategory?.map(({categoryId, categoryName}) => ({
            value: categoryId, 
            label: categoryName
          }))
        }))
}
/**
 * 服务类别层级组件
 */
export default {
  name: 'CategoryCascader',
  mixins: [mixin],
  props: {
    multiple: {
      type: Boolean,
      default: false
    }
  },
  data(){
    return {
      categorys: []
    }
  },
  computed: {
    ...mapGetters(['merchantId']),
  },
  created(){
    if (!this.merchantId) {
      return
    }
    this.getList()
  },
  methods:{
    async getList(){
      const {data: {serviceList, repairList}} = await categoryList()
      const {data: selections} = await merchantCategoryList(this.merchantId)
      const selectionList = selections.map(({categoryId}) => categoryId)
      this.categorys = [
        {value: 1, label: '家政分类', children: extractCategory(serviceList, selectionList)},
        {value: 2, label: '维修分类', children: extractCategory(repairList, selectionList)}
      ]
        
    }
  }
}
</script>
