<template>
  <div class="meun-edit">
    <el-form ref="dataForm" v-loading="formLoading" :model="formData" :rules="rules" label-width="80px">
      <el-form-item :label="$t('pages.sysMenuManager.form.currentEvent')">
        <el-tag>{{ eventName }}</el-tag>
      </el-form-item>
      <el-form-item :label="$t('pages.sysMenuManager.form.menuName')" prop="menuName">
        <el-input
          v-model.trim="formData.menuName"
          :placeholder="$t('pages.sysMenuManager.placeholder.menuName')"
        />
      </el-form-item>
      <el-form-item :label="$t('pages.sysMenuManager.form.permissionName')" prop="alias">
        <el-input
          v-model.trim="formData.alias"
          :placeholder="$t('pages.sysMenuManager.placeholder.permissionName')"
        />
      </el-form-item>
      <el-form-item :label="$t('pages.sysMenuManager.form.menuType')" prop="menuType">
        <el-radio-group v-model="formData.menuType">
          <el-radio :label="1">{{ $t('pages.sysMenuManager.menuType.directory') }}</el-radio>
          <el-radio :label="2">{{ $t('pages.sysMenuManager.menuType.menu') }}</el-radio>
          <el-radio :label="3">{{ $t('pages.sysMenuManager.menuType.button') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('pages.sysMenuManager.form.menuIcon')">
        <el-input v-model="formData.icon" placeholder="icon code" disabled>
          <template v-if="formData.icon" slot="prepend">
            <svg-icon :icon-class="formData.icon" style="font-size:20px;" />
          </template>
          <el-button
            slot="append"
            icon="el-icon-help"
            @click="iconsVisible = true;"
          >{{ $t('pages.sysMenuManager.action.selectIcon') }}</el-button>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('pages.sysMenuManager.form.menuStatus')" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="0">{{ $t('pages.sysMenuManager.status.normal') }}</el-radio>
          <el-radio :label="1">{{ $t('pages.sysMenuManager.status.disabled') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('pages.sysMenuManager.form.sortWeight')">
        <el-input
          v-model="formData.sort"
          v-number
          :placeholder="$t('pages.sysMenuManager.placeholder.sortWeight')"
        />
      </el-form-item>
      <el-form-item v-if="isMenuTypeToMenu" :label="$t('pages.sysMenuManager.form.menuPath')" prop="path">
        <el-input
          v-model.trim="formData.path"
          :placeholder="$t('pages.sysMenuManager.placeholder.menuPath')"
        />
      </el-form-item>
      <el-form-item :label="$t('pages.sysMenuManager.form.menuRouter')" prop="router">
        <el-input
          v-model.trim="formData.router"
          :placeholder="$t('pages.sysMenuManager.placeholder.menuRouter')"
        />
      </el-form-item>
      <el-form-item v-if="isMenuTypeToMenu" :label="$t('pages.sysMenuManager.form.relatedResources')">
        <el-select
          v-model="formData.resourceIds"
          multiple
          style="width:100%"
          class="filter-item"
          :placeholder="$t('pages.sysMenuManager.placeholder.relatedResources')"
        >
          <el-option
            v-for="item in resources"
            :key="item.id"
            :label="item.resourceName +'，'+ item.perm"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('pages.sysMenuManager.action.submit') }}</el-button>
      </el-form-item>
    </el-form>
    <iconsPanel
      :visible.sync="iconsVisible"
      @iconClick="handlerIconClick"
    />
  </div>
</template>
<script>
import IconsPanel from '@/components/IconsPanel'
import { deepClone } from '@/utils'
import { addMenu, updateMenu, getResources, getMenu } from '@/api/ops-system'

const defaultFormData = () => {
  return {
    menuName: '',
    alias: '',
    menuType: 1,
    icon: '',
    id: '',
    parentId: '0',
    path: '',
    resourceIds: [],
    router: '',
    status: 0,
    sort: 0
  }
}
export default {
  name: 'MenuEdit',
  components: { IconsPanel },
  props: {
    nodeData: {
      type: Object,
      default: null
    },
    /**
     * addRoot: add root node
     * addChildren: add child node
     * updateNode: update node
     */
    event: {
      type: String,
      default: 'addRoot'
    }
  },
  data() {
    return {
      formLoading: false,
      submitLoading: false,
      iconsVisible: false,
      formData: defaultFormData(),
      resources: []
    }
  },
  computed: {
    isMenuTypeToMenu() {
      return this.formData.menuType === 2
    },
    isUpdate() {
      return this.event === 'updateNode'
    },
    isAdd() {
      return this.event === 'addChildren'
    },
    isAddRoot() {
      return this.event === 'addRoot'
    },
    eventName() {
      if (this.isAdd) {
        return this.$t('pages.sysMenuManager.event.addChild', { name: this.nodeData.menuName })
      }
      if (this.isUpdate) {
        return this.$t('pages.sysMenuManager.event.updateNode', { name: this.nodeData.menuName })
      }

      if (this.isAddRoot) {
        return this.$t('pages.sysMenuManager.event.addRoot')
      }
      return this.$t('pages.sysMenuManager.event.invalid')
    },
    rules() {
      return {
        menuName: [{ required: true, message: this.$t('pages.sysMenuManager.validation.menuNameRequired'), trigger: 'blur' }],
        menuType: [{ required: true, message: this.$t('pages.sysMenuManager.validation.menuTypeRequired'), trigger: 'blur' }],
        status: [{ required: true, message: this.$t('pages.sysMenuManager.validation.menuStatusRequired'), trigger: 'blur' }]
      }
    }
  },
  watch: {
    nodeData: {
      immediate: true,
      deep: true,
      handler(newVal) {
        const that = this
        if (this.isUpdate) {
          that.formData = deepClone(newVal)
          that.formLoading = true
          getMenu(newVal.id).then(res => {
            that.formLoading = false
            const { body } = res
            that.formData = body
          }).catch(er => {
            that.formLoading = false
          })
          return
        }
        that.formData = defaultFormData()
        if (that.isAdd) {
          that.formData.parentId = newVal.id
          return
        }
      }
    }
  },
  created() {
    this.renderResources()
  },
  methods: {
    renderResources() {
      getResources().then(res => {
        const { body } = res
        this.resources = body || []
      })
    },
    handlerIconClick(value) {
      this.formData.icon = value
    },
    handleSubmit() {
      const that = this
      that.$refs.dataForm.validate(valid => {
        if (valid) {
          that.submitLoading = true
          if (that.isAdd || this.isAddRoot) {
            addMenu(that.formData).then(res => {
              that.submitLoading = false
              this.$emit('success', 'create', deepClone(that.formData))
              const parentId = that.formData.parentId
              that.formData = defaultFormData()
              that.formData.parentId = parentId
            }).catch(er => {
              that.submitLoading = false
              console.error(er)
              this.$emit('fail')
            })
            return
          }
          updateMenu(that.formData).then(res => {
            that.submitLoading = false
            that.$emit('success', 'update', deepClone(that.formData))
          }).catch(er => {
            that.submitLoading = false
            console.error(er)
            that.$emit('fail')
          })
        } else {
          console.error('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
