<!--
 * @Author: wlo_o
 * @Date: 2022-02-07 16:51:44
 * @LastEditors: wlo_o
 * @LastEditTime: 2022-03-01 11:10:26
 * @FilePath: /frontend/lib/components/MdCategoryDialog.vue
 * @Description: 添加分类
 *
 * Copyright (c) 2022 by 青岛百洋智能科技股份有限公司, All Rights Reserved.
-->
<template>
  <el-dialog
    :title="title"
    :width="'90%'"
    :visible="stateVisible"
    :before-close="handleDialogClose"
    :modal="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    class="oecp-md-category-dialog">
    <el-row>
      <ele-form
        v-bind="formConfig"
        v-model="formData"
        ref="form"/>
    </el-row>
    <el-row v-if="showExtForm&&extFormConfig">
      <ele-form
        v-bind="extFormConfig"
        v-model="extData"
        ref="ext"/>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleDialogClose">取 消</el-button>
      <el-button type="primary" @click="handleDialogOk" :loading="loading">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import OptionsMixin from '../mixins/OptionsMixin'
import { fetchApi } from '../common/apis.js'
import get from 'lodash/get'
import pick from 'lodash/pick'
import isEmpty from 'lodash/isEmpty'
import FormMixin from '../mixins/FormMixin'

export default {
  mixins: [ FormMixin, OptionsMixin ],
  props: {
    visible: { type: Boolean, default: false },
    data: { type: Object, default: () => ({}) },
    title: { type: String, default: '' }
  },
  computed: {
    showExtForm () {
      return !get(this.data, 'parentId')
    }
  },
  watch: {
    visible (val) {
      this.stateVisible = val
    },
    data: {
      handler: function (val) {
        this.formData = val
        this.extData = {}
      },
      immediate: true,
      deep: true
    }
  },
  data () {
    return {
      loading: false,
      stateVisible: this.visible
    }
  },
  methods: {
    // 重载 FormMixin 的方法
    getExtFormConfig () {
      let cfg = this.getMbOptionVar(`categoryFormExtConfig`)
      return cfg ? { ...this.defaultFormConfig, ...cfg } : cfg
    },
    handleDialogClose () {
      this.stateVisible = false
      this.$emit('close', false)
    },
    extFormData2Array () {
      let { extData = {}, extList = [], extFormConfig } = this
      if (isEmpty(extFormConfig)) return []
      let idKv = extList.reduce((rs, o) => { return { ...rs, ...o.extName && { [o.extName]: o.id } } }, {})
      let keys = Object.keys(extFormConfig.formDesc || {}) // 只处理模版内配置的扩展字段
      let newExtList = []
      keys.forEach(key => {
        let extValue = extData[key] === null || extData[key] === undefined ? '' : extData[key]
        newExtList.push({ ...idKv.hasOwnProperty(key) && { id: idKv[key] }, extName: key, extValue })
      })
      return newExtList
    },
    async handleDialogOk () {
      let that = this
      let { formData } = this
      Promise.all([
        that.$refs.form.validate(),
        that.showExtForm && that.extFormConfig ? that.$refs.ext.validate() : Promise.resolve()
      ]).then(() => {
        let ext = that.extFormData2Array()
        that.loading = true
        fetchApi.call(that, '/category/save', { ...formData, ...!isEmpty(ext) && { ext } }).then(function (res) {
          that.stateId = res.id
          that.$emit('close')
          that.$emit('success')
          return Promise.resolve(res)
        }).catch((err) => {
          return Promise.reject(err)
        }).finally(() => { that.loading = false })
      }, (err) => {
        return Promise.reject(err)
      })
    }
  },
  created () {
    // 与 formMixin 内的有差异，只用到 name
    this.formConfig.formDesc = pick(this.formConfig.formDesc, ['name'])
    this.formConfig.order = ['name']
  }
}
</script>
