<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-form
          :inline="true"
          class="demo-form-inline"
          label-position="right"
          label-width="90px"
          label-suffix=":"
        >
          <el-form-item label="分类名称">
            <el-select
              v-model="query.class_code"
              placeholder="请选择分类名称"
              clearable
              filterable
              size="mini"
              class="filter-item"
              style="width: 185px;"
              @change="hand"
            >
              <el-option
                v-for="item in classNames"
                :key="item.class_code"
                :label="item.class_name"
                :value="item.class_code"
              />
            </el-select>
          </el-form-item>
          <rrOperation :crud="crud" />
        </el-form>
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission">
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="success"
          icon="el-icon-s-operation"
          @click="ToExpandall"
        >
          全部展开
        </el-button>
      </crudOperation>
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="500px"
      >
        <el-form ref="form" :model="form" :rules="rules" size="mini" label-width="80px">
          <el-form-item label="分类编码" prop="class_code">
            <el-input v-model="form.class_code" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="分类名称" prop="class_name">
            <el-input v-model="form.class_name" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="简要描述" prop="class_desc">
            <el-input v-model="form.class_desc" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="顶级类目">
            <el-radio-group v-model="form.isTop" style="width: 140px">
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.isTop === '0'" style="margin-bottom: 0;" label="上级类目" prop="pid">
            <treeselect
              v-model="form.parent_class_id"
              :load-options="loadClass"
              :options="classes"
              style="width: 370px;"
              placeholder="选择上级类目"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        lazy
        :load="getClassDatas"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        :data="crud.data"
        row-key="class_id"
        @select="crud.selectChange"
        @select-all="crud.selectAllChange"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column prop="class_code" label="分类编码" />
        <el-table-column prop="class_name" label="分类名称" />
        <el-table-column prop="class_desc" label="分类简要描述" />
        <el-table-column prop="update_name" label="修改人" />
        <el-table-column prop="update_time" label="修改时间" min-width="100" show-overflow-tooltip />
        <el-table-column prop="is_modify" label="是否可修改">
          <template slot-scope="scope">
            {{ scope.row.is_modify?'是':'否' }}
          </template>
        </el-table-column>
        <el-table-column
          v-permission="['admin','Classstandard:edit','Classstandard:del']"
          label="操作"
          width="250px"
          align="center"
        >
          <template slot-scope="scope">
            <udOperation
              style="display: inline"
              :data="scope.row"
              :permission="permission"
              :disabled-edit="scope.row.is_modify === '0'"
              :disabled-dle="scope.row.is_modify === '0'"
              msg="确定删除吗,如果存在下级节点则一并删除，此操作不能撤销！"
            />
            <el-button slot="right" size="mini" type="text" icon="el-icon-circle-plus-outline" @click="crud.toAddAndData(addSibling(scope.row))">新增同级</el-button>
            <el-button slot="right" size="mini" type="text" icon="el-icon-circle-plus" @click="crud.toAddAndData(addChildren(scope.row))">新增子级</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudClassstandard from './mdBaseClassstandard'
import CRUD, { crud, form, header, presenter } from '@crud/crud'
import Treeselect, { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import rrOperation from '@crud/RR.operation'
import pagination from '@crud/Pagination'

let defaultForm = {
  id: null,
  class_id: null,
  base_data_type: null,
  path_code: null,
  class_code: null,
  class_name: null,
  class_desc: null,
  parent_class_id: null,
  is_leaf: true,
  sub_count: null,
  is_modify: true,
  is_delete: false,
  class_level: null,
  ext_id: null,
  ext_parent_id: null,
  create_id: null,
  create_name: null,
  create_time: null,
  update_id: null,
  update_name: null,
  update_time: null,
  isTop: '1'
}
export default {
  name: 'Classstandard',
  dicts: ['base_data'],
  components: { pagination, crudOperation, rrOperation, udOperation, Treeselect },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: '基础类别',
      url: 'api/Classstandard',
      idField: 'class_id',
      sort: 'class_id,desc',
      crudMethod: { ...crudClassstandard },
      optShow: {
        add: true,
        reset: true
      }
    })
  },
  data() {
    return {
      classes: [],
      classNames: [],
      permission: {},
      rules: {
        class_id: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        path_code: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        class_code: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        class_name: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        is_leaf: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        is_modify: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        is_delete: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        create_id: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        create_name: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        create_time: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getClassNames() // 获取分类
  },
  methods: {
    getClassNames() {
      crudClassstandard.getClassName().then((res) => { // 获取分类名称，查询根据分类编码查找对应分支树
        this.classNames = res
      })
    },
    getClassDatas(tree, treeNode, resolve) {
      const params = { pid: tree.class_id }
      setTimeout(() => {
        crudClassstandard.getClass(params).then(res => {
          resolve(res)
        })
      }, 100)
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      if (form.parent_class_id !== '0' && form.parent_class_id !== null) {
        form.isTop = '0'
      } else if (form.id !== '0' && form.id !== null) {
        form.isTop = '1'
      }
      // form.enabled = `${form.enabled}`
      // 为了初始化数据 -> 树的数据
      if (form.id !== null && form.id !== '0' && form.id !== '') {
        this.getSubTypes(form.id)
      } else {
        this.getClass()
      }
    },
    // 提交前的验证
    [CRUD.HOOK.afterValidateCU]() {
      if (this.form.parent_class_id !== null && this.form.parent_class_id === this.form.class_id) {
        this.$message({
          message: '顶级类目不能为空',
          type: 'warning'
        })
        return false
      }
      if (this.form.isTop === '1') {
        this.form.parent_class_id = 0
      }
      return true
    },
    getSubTypes(id) { // 获取当前对象与所有父类数据
      crudClassstandard.getClassSuperior(id).then(res => {
        const date = res
        this.buildClass(date)
        this.classes = date
      })
    },
    getClass() { // 点击新增的时候触发
      crudClassstandard.getClass({ enabled: true }).then(res => {
        this.classes = res.map(function(obj) { // 为了设置子级属性,才会显示展开图标
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    buildClass(classes) {
      classes.forEach(data => {
        if (data.children) {
          this.buildClass(data.children)
        }
        if (data.hasChildren && !data.children) {
          data.children = null
        }
      })
    },
    // 获取弹窗内数据
    loadClass({ action, parentNode, callback }) { // 展开显示子级数据，只需要吧父类底下的子级返回去
      if (action === LOAD_CHILDREN_OPTIONS) {
        crudClassstandard.getClass({ pid: parentNode.id }).then(res => {
          parentNode.children = res.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 100)
        })
      }
    },
    clearFrom() {
      defaultForm = {
        id: null,
        class_id: null,
        base_data_type: null,
        path_code: null,
        class_code: null,
        class_name: null,
        class_desc: null,
        parent_class_id: null,
        is_leaf: true,
        sub_count: null,
        is_modify: true,
        is_delete: false,
        class_level: null,
        ext_id: null,
        ext_parent_id: null,
        create_id: null,
        create_name: null,
        create_time: null,
        update_id: null,
        update_name: null,
        update_time: null,
        isTop: null
      }
    },
    addSibling(row) {
      this.clearFrom() // 将默认的表单数据清除
      defaultForm.id = row.id // 获取分类树的id - 懒加载依赖此id，不可为空
      defaultForm.class_id = row.class_id // 获取分类树的id
      defaultForm.parent_class_id = row.parent_class_id ? row.parent_class_id : null // 同级为父类class_id
      defaultForm.isTop = row.isTop
      return defaultForm
    },
    addChildren(row) {
      this.clearFrom()
      defaultForm.id = row.class_id // 获取分类树的id
      defaultForm.parent_class_id = row.class_id // 子级为本身的class_id
      defaultForm.isTop = row.isTop
      return defaultForm
    },
    // 全部展开 参考：https://www.cnblogs.com/toughy/p/12667805.html
    ToExpandall() {
      const els = document.getElementsByClassName('el-table__expand-icon')
      if (this.crud.data.length !== 0 && els.length !== 0) {
        for (let j1 = 0; j1 < els.length; j1++) {
          els[j1].classList.add('dafult')
        }
        if (this.$el.getElementsByClassName('el-table__expand-icon--expanded')) {
          const open = this.$el.getElementsByClassName('el-table__expand-icon--expanded')
          for (let j = 0; j < open.length; j++) {
            open[j].classList.remove('dafult')
          }
          const dafult = this.$el.getElementsByClassName('dafult')
          for (let a = 0; a < dafult.length; a++) {
            dafult[a].click()
          }
        }
      }
    },
    hand(value) {
      this.crud.toQuery()
    }
  }
}
</script>

<style scoped>

</style>
