<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" label-width="120px">
      <el-form-item prop="categoryName" label="分类名称">
        <el-input v-model="dataForm.categoryName" placeholder="分类名称"></el-input>
      </el-form-item>
      <el-form-item prop="categoryCode" label="分类编码">
        <el-input v-model="dataForm.categoryCode" placeholder="分类编码"></el-input>
      </el-form-item>
      <el-form-item prop="parentName" label="上级分类" class="category-list">
        <el-popover v-model="categoryListVisible" ref="categoryListPopover" placement="bottom-start" trigger="click">
          <el-tree :data="categoryList"
                   :props="{ label: 'categoryName', children: 'children' }"
                   node-key="id"
                   ref="categoryListTree"
                   :highlight-current="true"
                   :expand-on-click-node="false"
                   accordion
                   @current-change="categoryListTreeCurrentChangeHandle">
          </el-tree>
        </el-popover>
        <el-input v-model="dataForm.parentName" v-popover:categoryListPopover :readonly="true" placeholder="上级分类">
          <i v-if="dataForm.pid !== '0'" slot="suffix" @click.stop="categoryListTreeSetDefaultHandle()" class="el-icon-circle-close el-input__icon"></i>
        </el-input>
      </el-form-item>
      <el-form-item label="分类类型" prop="categoryType">
        <el-select v-model="dataForm.categoryType" @change="changeOrgType" placeholder="分类类型">
          <el-option v-for="item in secondOrgDictList" :key="item.dictValue" :label="item.dictName" :value="item.dictValue">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="sort" label="排序">
        <el-input-number v-model="dataForm.sort" controls-position="right" :min="0" label="排序"></el-input-number>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
export default {
  data () {
    return {
      visible: false,
      categoryList: [],
      categoryListVisible: false,
      dataForm: {
        id: '',
        categoryName: '',
        pid: '',
        parentName: '',
        sort: 0,
        categoryType: '',
        categoryCode: ''
      },
      secondOrgDictList: []
    }
  },
  computed: {
    dataRule () {
      return {
        categoryName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        parentName: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        categoryCode: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        categoryType: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        sort: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.getcategoryList().then(() => {
          this.categoryListTreeSetDefaultHandle()
          if (this.dataForm.id) {
            this.getInfo()
          }
          if (this.dataForm.id) {
          } else {
            this.dataForm.categoryCode = ''
            this.dataForm.categoryType = ''
          }
        })
      })
      this.getSecondOrgDicList()
    },
    changeOrgType (item) {
      this.dataForm.categoryType = item
    },
    getcategoryList () {
      return this.$http.get('/events/category/list').then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.categoryList = res.data
      }).catch(() => { })
    },
    getSecondOrgDicList () {
      this.$http.get(`/sys/dict/listSimple/category_type`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.secondOrgDictList = res.data
      }).catch(() => { })
    },
    getInfo () {
      this.$http.get(`/events/category/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
        if (this.dataForm.pid === '0') {
          return this.categoryListTreeSetDefaultHandle()
        }
        this.$refs.categoryListTree.setCurrentKey(this.dataForm.pid)
      }).catch(() => { })
    },
    categoryListTreeSetDefaultHandle () {
      this.dataForm.pid = '0'
      this.dataForm.parentName = '一级分类'
    },
    categoryListTreeCurrentChangeHandle (data) {
      this.dataForm.pid = data.id
      this.dataForm.parentName = data.categoryName
      this.categoryListVisible = false
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http[!this.dataForm.id ? 'post' : 'put']('/events/category', this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => { })
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>

<style lang="scss">
.mod-sys__category {
  .category-list {
    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }
}
</style>
