<template>
  <div class="layer-container">
    <div class="head-container">
      <el-input
        v-model="name"
        clearable
        size="small"
        placeholder="输入模型分类名称搜索"
        prefix-icon="el-icon-search"
        class="filter-item"
        @input="refreshTree"
      />
      <div class="opt-box">
        <el-button
          v-permission="permission.add"
          class="filter-item"
          size="mini"
          type="primary"
          @click="addModel"
        >
          新增
        </el-button>
        <el-button
          v-permission="permission.edit"
          class="filter-item"
          size="mini"
          type="success"
          :disabled="!selectedData.id || selectedData.id == '0'"
          @click="editModel"
        >
          修改
        </el-button>
        <el-button
          slot="reference"
          v-permission="permission.del"
          class="filter-item"
          type="danger"
          size="mini"
          :loading="delAllLoading"
          :disabled="!selectedData.id || selectedData.id == '0'"
          @click="deleteModel"
        >
          删除
        </el-button>
      </div>
    </div>

    <el-tree
      :data="modelCategoryData"
      :props="defaultProps"
      :expand-on-click-node="false"
      highlight-current
      @node-click="handleNodeClick"
    />
    <!--表单渲染-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="closeDialog"
      :visible.sync="dialogShow"
      :title="dialogTitle"
      width="480px"
    >
      <el-form ref="form" :model="formData" :rules="rules" size="small" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="分类编号" prop="code">
          <el-input v-model="formData.code" />
        </el-form-item>
        <el-form-item label="上级分类">
          <tree-select
            v-model="formData.parentId"
            :options="modelCategoryData"
            style="width: 360px"
            placeholder="选择上级分类（顶级分类该项不选）"
          />
        </el-form-item>
        <el-form-item label="分类排序" prop="sort">
          <el-input v-model="formData.sort" />
        </el-form-item>
        <el-form-item label="分类描述" prop="desc">
          <el-input type="textarea" :rows="3" v-model="formData.desc" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="closeDialog">取消</el-button>
        <el-button :loading="submitLoading" type="primary" @click="doSubmit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import permission from '@/directive/permission'
import { getCategoryTree, add, edit, del } from '@/api/modelLibrary/category'
// vue-treeselect
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
const defaultForm = {
  id: '',
  name: '',
  code: '',
  sort: '',
  parentId: '0',
  desc: '',
}
export default {
  name: 'ModelCategory',
  directives: { permission },
  components: { TreeSelect },
  props: {
    modelCategoryData: {
      type: Array,
      default() {
        return []
      },
    },
  },
  data() {
    return {
      name: '', //左侧部门树形图搜索条件
      defaultProps: {
        // tree组件懒加载默认参数
        children: 'children',
        label: 'name',
        isLeaf: 'leaf',
      },
      permission: {
        add: ['admin', 'layer:add'],
        edit: ['admin', 'layer:edit'],
        del: ['admin', 'layer:del'],
      },
      rules: {
        name: [{ required: true, message: '请输入模型分类名称', trigger: 'blur' }],
      },
      delAllLoading: false,
      submitLoading: false,
      dialogShow: false,
      dialogTitle: '新增模型分类',
      formData: {},
      selectedData: {},
    }
  },

  methods: {
    // 切换部门
    handleNodeClick(data) {
      this.selectedData = data
      this.$emit('changeCategory', data)
    },
    // 打开新增
    addModel() {
      const { id, name } = this.selectedData
      let title = id ? `是否在【${name}】下创建新模型分类？` : `是否创建新模型分类？`
      this.$confirm(title, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.dialogTitle = '新增模型分类'
          this.formData = Object.assign({}, defaultForm, { parentId: id ? id : '0' })
          this.dialogShow = true
          console.log(this.formData)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消',
          })
        })
    },
    editModel() {
      this.dialogTitle = '编辑模型分类'
      this.formData = this.selectedData
      this.dialogShow = true
    },
    deleteModel() {
      const { id, name } = this.selectedData
      this.$confirm(`确定删除【${name}】吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // const ids = [id]
          try {
            await del({ id })
            this.refreshTree()
          } catch (err) {
            console.log(err)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消',
          })
        })
    },
    async doSubmit() {
      console.log(this.formData)
      try {
        if (!this.formData.id) {
          await add(this.formData)
        } else {
          await edit(this.formData)
        }
        this.closeDialog()
        this.refreshTree()
      } catch (err) {
        console.log(err)
      }
    },
    closeDialog() {
      this.selectedData = {}
      this.dialogShow = false
    },
    refreshTree() {
      this.$emit('getModelCategory')
    },
  },
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .vue-treeselect__control,
::v-deep .vue-treeselect__placeholder,
::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
.layer-container {
  .opt-box {
    display: flex;
  }
}
</style>
