<template>
  <el-drawer
    :title="drawerTitle"
    :visible.sync="visibleProxy"
    direction="rtl"
    size="80%"
    :before-close="handleBeforeClose"
  >
    <div v-loading="loading" class="editor-body">
      <el-form
        ref="form"
        label-position="right"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item :label="$t(`${pre}.title`)" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item :label="$t(`${pre}.describe`)" prop="describe">
          <el-input type="textarea" :maxlength="30" show-word-limit v-model="form.describe" />
        </el-form-item>
        <el-form-item :label="$t(`${pre}.parent_category`)" prop="category_id">
          <el-cascader
            v-model="form.category_id"
            :options="categoryTreeData"
            :props="{
              value: 'id',
              label: 'name',
              expandTrigger: 'hover',
              checkStrictly: true
            }"
          />
        </el-form-item>
        <el-form-item :label="$t(`${pre}.view_permission`)" prop="role_ids">
          <el-select v-model="form.role_ids" multiple :placeholder="$t(`${pre}.please_select`)">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.name"
              :value="String(item.id)"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t(`${pre}.sort`)" prop="sort">
          <el-input-number v-model="form.sort" :min="0" />
        </el-form-item>
        <el-form-item :label="$t(`${pre}.type`)">
          <el-radio-group v-model="form.type">
            <el-radio label="md">{{ $t(`${pre}.document`) }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="form.type === 'md'" style="width:100%">
          <mavon-editor
            ref="mavon"
            style="height:500px"
            v-model="form.markdown"
            @imgAdd="handleUploadImages"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :disabled="submitting" @click="handleAdd">
            {{ $t(`${pre}.add`) }}
          </el-button>
          <el-button @click="closeDrawer">{{ $t(`${pre}.cancel`) }}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-drawer>
</template>

<script>
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import axios from 'axios'

export default {
  name: 'MarkdownEditor',
  components: { mavonEditor },
  props: {
    visible: { type: Boolean, default: false },
    editData: { type: Object, default: null },
    categoryTreeData: { type: Array, default: () => [] },
    roleList: { type: Array, default: () => [] },
    pre: { type: String, required: true }
  },
  data () {
    return {
      loading: false,
      submitting: false,
      isEdit: false,
      editId: null,
      form: this.getDefaultForm(),
      rules: {
        title: [{ required: true, message: this.$t(`${this.pre}.enter_title`), trigger: 'blur' }],
        describe: [{ required: true, message: this.$t(`${this.pre}.enter_describe`), trigger: 'blur' }],
        category_id: [{ required: true, message: this.$t(`${this.pre}.select_parent_menu`), trigger: 'blur' }],
        role_ids: [{ required: true, message: this.$t(`${this.pre}.select_role_group`), trigger: 'blur' }]
      }
    }
  },
  computed: {
    visibleProxy: {
      get () { return this.visible },
      set (val) { this.$emit('update:visible', val) }
    },
    drawerTitle () {
      return this.isEdit ? this.$t(`${this.pre}.edit_document`) : this.$t(`${this.pre}.add_document`)
    }
  },
  watch: {
    visible (val) {
      if (val && this.editData) {
        this.isEdit = true
        this.editId = this.editData.id
        this.form = {
          title: this.editData.title,
          category_id: this.editData.category_id,
          describe: this.editData.describe,
          markdown: this.editData.markdown || '',
          type: this.editData.type || 'md',
          role_ids: this.editData.role_ids ? this.editData.role_ids.map(String) : [],
          url: this.editData.url || '',
          sort: this.editData.sort || 0
        }
        this.$nextTick(() => {
          if (this.$refs.form) this.$refs.form.clearValidate()
        })
      } else if (val && !this.editData) {
        this.isEdit = false
        this.editId = null
        this.resetForm()
      }
    }
  },
  methods: {
    getDefaultForm () {
      return {
        title: undefined,
        category_id: undefined,
        describe: undefined,
        markdown: '',
        type: 'md',
        role_ids: [],
        url: '',
        sort: 0
      }
    },
    resetForm () {
      this.form = this.getDefaultForm()
      this.submitting = false
      this.isEdit = false
      this.editId = null
    },
    handleAdd () {
      this.$refs.form.validate(valid => {
        if (!valid) return
        if (this.form.type === 'md' && !this.form.markdown) {
          this.$message.warning(this.$t(`${this.pre}.content_required`))
          return
        }
        this.submitting = true
        this.$emit('submit', this.isEdit
          ? { id: this.editId, ...this.form }
          : { ...this.form }
        )
      })
    },
    handleBeforeClose (done) {
      this.$confirm(this.$t(`${this.pre}.confirm_close`))
        .then(() => {
          this.resetForm()
          done()
        })
        .catch(() => {})
    },
    closeDrawer () {
      this.resetForm()
      this.$emit('update:visible', false)
    },
    handleUploadImages (pos, file) {
      const formdata = new FormData()
      formdata.append('file', file)
      formdata.append('type', 'image')
      axios({
        url: process.env.VUE_APP_UPLOAD_PATH,
        method: 'post',
        data: formdata,
        headers: { 'Content-Type': 'multipart/form-data' }
      }).then(url => {
        this.$refs.mavon.$img2Url(pos, process.env.VUE_APP_PRO_PUBLIC_URL + url.data.url)
      })
    }
  }
}
</script>

<style scoped>
.editor-body {
  padding: 10px 20px;
}
</style>
