<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="$t('wms.basedata.class.class_name')">
              <el-select
                v-model="query.class_code"
                :placeholder="$t('wms.basedata.class.search_placeholder')"
                clearable
                filterable
                size="mini"
                class="filter-item"
                style="width: 185px;"
                @change="hand">
              <el-option
                v-for="item in classNames"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </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"
        >
          {{ $t('wms.basedata.class.expand_all') }}
        </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="$t('wms.basedata.class.class_code')" prop="class_code">
            <el-input v-model="form.class_code" style="width: 370px;" />
          </el-form-item>
          <el-form-item :label="$t('wms.basedata.class.class_name')" prop="class_name">
            <el-input v-model="form.class_name" style="width: 370px;" />
          </el-form-item>
          <el-form-item :label="$t('wms.basedata.class.class_desc')" prop="class_desc">
            <el-input v-model="form.class_desc" style="width: 370px;" />
          </el-form-item>
          <el-form-item :label="$t('wms.basedata.class.is_top')">
            <el-radio-group v-model="form.isTop" style="width: 140px">
              <el-radio label="1">{{ $t('common.Yes') }}</el-radio>
              <el-radio label="0">{{ $t('common.No') }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.isTop === '0'" style="margin-bottom: 0;" :label="$t('wms.basedata.class.parent_class')" prop="pid">
            <treeselect
              v-model="form.parent_class_id"
              :load-options="loadClass"
              :options="classes"
              style="width: 370px;"
              :placeholder="$t('wms.basedata.class.select_parent_class')"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">{{ $t('common.Cancel') }}</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">{{ $t('common.Confirm') }}</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="id"
        @select="crud.selectChange"
        @select-all="crud.selectAllChange"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column prop="class_code" :label="$t('wms.basedata.class.class_code')" />
        <el-table-column prop="class_name" :label="$t('wms.basedata.class.class_name')" />
        <el-table-column prop="class_desc" :label="$t('wms.basedata.class.class_desc')" />
        <el-table-column prop="update_optname" :label="$t('common.update_optname')" />
        <el-table-column prop="update_time" :label="$t('common.update_time')" />
        <el-table-column prop="is_modify" :formatter="modifyFormat" :label="$t('wms.basedata.class.is_modify')" />
        <el-table-column
          v-permission="['admin','Classstandard:edit','Classstandard:del']"
          :label="$t('wms.basedata.class.operation')"
          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="$t('wms.basedata.class.delete_confirm')"
            />
            <el-button slot="right" size="mini" type="text" icon="el-icon-circle-plus-outline" @click="crud.toAddAndData(addSibling(scope.row))">{{ $t('wms.basedata.class.add_sibling') }}</el-button>
            <el-button slot="right" size="mini" type="text" icon="el-icon-circle-plus" @click="crud.toAddAndData(addChildren(scope.row))">{{ $t('wms.basedata.class.add_children') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudClassstandard from '@/views/wms/basedata/class/classstandard'
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'
import i18n from '@/i18n'

let defaultForm = {
  class_id: null,
  base_data_type: null,
  path_code: null,
  class_code: null,
  long_class_code: null,
  class_name: null,
  class_desc: null,
  parent_class_id: null,
  is_leaf: null,
  sub_count: null,
  is_modify: null,
  is_delete: null,
  class_level: null,
  ext_id: null,
  ext_parent_id: null,
  create_id: null,
  create_name: null,
  create_time: null,
  update_optid: null,
  update_optname: null,
  update_time: null,
  isTop: '1'
}
export default {
  name: 'Classstandard',
  dicts: [],
  components: { pagination, crudOperation, rrOperation, udOperation, Treeselect },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: i18n.t('wms.basedata.class.title'),
      url: 'api/Classstandard',
      idField: 'class_id',
      sort: 'class_id,desc',
      crudMethod: { ...crudClassstandard },
      optShow: {
        add: true,
        reset: true
      }
    })
  },
  data() {
    return {
      classes: [],
      classNames: [],
      permission: {},
      rules: {
        path_code: [
          { required: true, message: i18n.t('wms.basedata.class.not_empty'), trigger: 'blur' }
        ],
        class_code: [
          { required: true, message: i18n.t('wms.basedata.class.not_empty'), trigger: 'blur' }
        ],
        class_name: [
          { required: true, message: i18n.t('wms.basedata.class.not_empty'), trigger: 'blur' }
        ],
        is_leaf: [
          { required: true, message: i18n.t('wms.basedata.class.not_empty'), trigger: 'blur' }
        ],
        is_modify: [
          { required: true, message: i18n.t('wms.basedata.class.not_empty'), trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getClassNames() // 获取分类
  },
  methods: {
    getClassNames() {
      crudClassstandard.getClassName().then((res) => { // 获取分类名称，查询根据分类编码查找对应分支树
        this.classNames = res
      })
    },
    getClassDatas(tree, treeNode, resolve) {
      const params = { pid: tree.id }
      setTimeout(() => {
        crudClassstandard.getClass(params).then(res => {
          resolve(res.content)
        })
      }, 100)
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    modifyFormat(row, index) {
      if (row.is_modify === '1') {
        return i18n.t('common.Yes')
      } else {
        return i18n.t('common.No')
      }
    },
    dataTypeChange(data) {
      crudClassstandard.getClass({ base_data_type: data }).then(res => {
        this.classes = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      if (form.parent_class_id !== '0' && form.parent_class_id !== null) {
        form.isTop = '0'
      } else if (form.class_id !== '0' && form.class_id !== null) {
        form.isTop = '1'
      }
      form.enabled = `${form.enabled}`
      if (form.class_id != null) {
        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: i18n.t('wms.basedata.class.top_class_not_empty'),
          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.content
        this.buildClass(date)
        this.classes = date
      })
    },
    getClass() {
      crudClassstandard.getClass({ enabled: true }).then(res => {
        this.classes = res.content.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.content.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,
        long_class_code: null,
        class_name: null,
        class_desc: null,
        parent_class_id: null,
        is_leaf: null,
        sub_count: null,
        is_modify: null,
        is_delete: null,
        class_level: null,
        ext_id: null,
        ext_parent_id: null,
        create_id: null,
        create_name: null,
        create_time: null,
        update_optid: null,
        update_optname: null,
        update_time: null,
        isTop: null
      }
    },
    addSibling(row) {
      this.clearFrom() // 将默认的表单数据清除
      defaultForm.id = row.id // 获取分类树的id - 懒加载依赖此id，不可为空
      defaultForm.class_id = row.class_id
      defaultForm.parent_class_id = row.parent_class_id // 同级为父类class_id
      defaultForm.isTop = row.isTop
      return defaultForm
    },
    addChildren(row) {
      this.clearFrom()
      defaultForm.id = row.id // 获取分类树的id
      defaultForm.class_id = row.parent_class_id
      defaultForm.parent_class_id = row.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++) {
            debugger
            dafult[a].click()
          }
        }
      }
    },
    hand(value) {
      this.crud.toQuery()
    }
  }
}
</script>

<style scoped>

</style>
