<template>
  <Container v-loading="loading">
      <el-tabs v-if="merchantId" v-model="type" type="card">
        <el-tab-pane label="家政分类" name="1">
            <Checkbox v-model="selections" v-for="item in serviceList" :data="item" :key="item.id"/>
        </el-tab-pane>
        <el-tab-pane label="维修分类" name="2">
            <Checkbox v-model="selections" v-for="item in repairList" :data="item" :key="item.id"/>
        </el-tab-pane>
        <div style="width: 100%; text-align:center">
            <el-button type="primary" @click="handleSave" :loading="saving">保存</el-button>
        </div>
      </el-tabs>
      <el-alert v-else title="当前用户不存在店铺信息" type="error" :closable="false" center/>
  </Container>
</template>

<script>
import Checkbox from './components/Checkbox.vue'
import { mapGetters } from 'vuex'
import {categoryList, merchantCategoryModify, merchantCategoryList} from '@/api/merchant/merchant'

export default {
    name: 'MerchantCategory',
    components: {Checkbox},
    data(){
      return {
        type: '1',
        loading: false,
        saving: false,
        serviceList: [],
        repairList: [],
        selections: []
      }
    },
    computed: {
      ...mapGetters(['merchantId']),
    },
    async created(){
      if (!this.merchantId) {
        return
      }
      this.loading = true
      await this.getList()
      await this.getDetail()
      this.loading = false
    },
    methods: {
      async getList() {
        const {code, data} = await categoryList()
        const transfer = list => list.map(({categoryId, categoryName, childrenCategory}) => ({
          id: categoryId, 
          name: categoryName, 
          children: (childrenCategory || []).map(({categoryId, categoryName}) => ({
            id: categoryId, 
            name: categoryName
          }))
        }))
        if (code === 200) {
          const {serviceList, repairList} = data
          this.serviceList = transfer(serviceList)
          this.repairList = transfer(repairList)
        }
      },
      async handleSave() {
        const params = {
          merchantId: this.merchantId,
          categoryIds: this.selections
        }
        this.saving = true
        const {code} = await merchantCategoryModify(params)
        if (code === 200) {
          this.$message.success('保存成功')
          this.getDetail()
        }
        this.saving = false
      },
      async getDetail(){
        const {code, data} = await merchantCategoryList(this.merchantId)
        if (code === 200) {
          this.selections = data.map(({categoryId}) => categoryId)
        }
      }
    }
}
</script>