<template>
  <!--用户数据-->
  <div class="elect-cont-right">
    <!--工具栏-->
    <div class="head-container">
      <crudOperation :permission="permission">
        <template v-slot:left>
          <el-button v-permission="permission.add" size="mini" @click="crud.toAdd">
            <i class="iconfont icon-xinzeng" />
            新增
          </el-button>
          <el-button v-permission="permission.edit" size="mini" :disabled="selections.length !== 1" @click="crud.toEdit(selections[0])">
            <i class="iconfont icon-bianji" />
            编辑
          </el-button>
          <el-button slot="reference" v-permission="permission.del" size="mini" :loading="crud.delAllLoading" :disabled="selections.length === 0" @click="toDelete(selections)">
            <i class="iconfont icon-shanchu" />
            删除
          </el-button>
        </template>
        <template v-slot:right>
          <el-button :loading="crud.downloadLoading" size="mini" :disabled="selections.length === 0" @click="doExport(selections)">
            <i class="iconfont icon-daochu" />
            导出
          </el-button>
          <span class="tip">注意：门类节点下才可新增档案分类</span>
        </template>
      </crudOperation>
    </div>
    <!--表单组件-->
    <el-dialog
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      append-to-body
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      :title="crud.status.title"
    >
      <div class="setting-dialog">
        <el-form ref="form" inline :model="form" :rules="rules" size="small" label-width="90px">
          <el-form-item v-if="crud.status.add === 1" label="所属门类" prop="categoryId">
            <treeselect
              v-model="form.categoryId"
              :options="categoryDatas"
              placeholder="选择所属门类"
              flat
              :multiple="false"
              :normalizer="normalizer"
              @select="selectCategoryTree"
            />
          </el-form-item>
          <el-form-item v-if="crud.status.edit === 1" label="所属门类" prop="categoryId">
            <el-input v-model="form.categoryName" disabled />
          </el-form-item>
          <el-form-item label="分类编码" prop="code">
            <el-input v-model="form.code" />
          </el-form-item>
          <el-form-item label="分类名称" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="排序" prop="classSeq">
            <el-input-number
              v-model.number="form.classSeq"
              :min="0"
              :max="999"
              controls-position="right"
            />
          </el-form-item>
          <el-row>
            <el-form-item label="顶级分类" prop="isTop">
              <el-radio-group v-model="form.isTop" @input="changeIsTop">
                <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'"
              label="上级分类"
              prop="pid"
            >
              <!-- :load-options="loadClassifyTree" -->
              <treeselect
                v-model="form.pid"
                :options="classifyOptions"
                :normalizer="classifyNormalizer"
                placeholder="选择门类之后再选择上级范围"
              />
            </el-form-item>
          </el-row>
          <el-form-item label="描述信息" prop="remark">
            <el-input v-model="form.remark" rows="5" type="textarea" style="width: 586px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确定</el-button>
        </div>
      </div>
    </el-dialog>
    <!--表格渲染-->
    <div class="container-right">
      <span class="right-top-line" />
      <span class="left-bottom-line" />
      <!-- :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" -->
      <el-table
        ref="table"
        v-loading="crud.loading"
        lazy
        :data="tableData"
        :row-key="getRowKey"
        :load="getSonClass"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        highlight-current-row
        @select-all="selectAll"
        @select="selectTr"
        @selection-change="selectionChangeHandler"
        @row-click="clickRowHandler"
      >
        <el-table-column type="selection" align="center" width="55" />
        <el-table-column label="分类名称" prop="name" />
        <el-table-column label="分类编号" prop="code" />
        <el-table-column label="排序" prop="classSeq" />
        <el-table-column label="所属门类" prop="categoryName" />
        <el-table-column prop="createTime" label="创建日期">
          <template slot-scope="scope">
            <div>{{ scope.row.createTime | parseTime }}</div>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination v-if="crud.data.length!==0" />
    </div>
  </div>
</template>

<script>
import { FetchCategoryMenu } from '@/api/system/category/category'
import crudClassify from '@/api/system/archivesClass'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import { exportFile } from '@/utils/index'
import qs from 'qs'
import { mapGetters } from 'vuex'

const defaultForm = {
  id: null,
  categoryId: null,
  name: null,
  code: null,
  isTop: '1',
  classSeq: 999,
  pid: null,
  remark: null
}

export default {
  name: 'Classify',
  components: { crudOperation, pagination, Treeselect },
  cruds() {
    return CRUD({ title: '分类', url: 'api/archivesClass/initArchivesClass', crudMethod: { ...crudClassify }, optShow: {
      add: false,
      edit: false,
      del: false,
      reset: false,
      download: false,
      group: false
    }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  props: {
    selectedCategory: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      tableData: [],
      classifyOptions: [],
      categoryDatas: [],
      selections: [],
      isAllSelect: false,
      rules: {
        categoryId: [{ required: true, message: '请选择所属门类', trigger: 'change' }],
        code: [{ required: true, message: '分类编码不可为空', trigger: 'blur' }],
        name: [{ required: true, message: '分类名称不可为空', trigger: 'blur' }],
        classSeq: [{ required: true, message: '请输入序号', trigger: 'blur', type: 'number' }],
        isTop: [{ required: true, message: '请选择是否为顶级分类', trigger: 'change' }],
        pid: [{ required: true, message: '请选择上级分类', trigger: 'change' }]
      },
      permission: {
        add: ['admin', 'classify:add'],
        edit: ['admin', 'classify:edit'],
        del: ['admin', 'classify:del']
      }
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  watch: {
    selectedCategory: function(newValue, oldValue) {
      this.crud.refresh()
    }
  },
  created() {
  },
  methods: {
    getRowKey(row) {
      return row.id
    },
    // 获取数据前设置默认参数
    [CRUD.HOOK.beforeRefresh]() {
      this.tableData = []
      this.crud.query.categoryId = this.selectedCategory.id
    },
    [CRUD.HOOK.afterRefresh](crud) {
      crud.data.forEach(function(item, index) {
        if (item.sonNum !== 0) {
          item.hasChildren = true
          item.children = null
        } else {
          item.hasChildren = false
        }
      })
      this.tableData = this.crud.data
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      console.log(crud.form)
      delete crud.form.isTop
      return true
    },
    changeIsTop(val) {
      if (this.crud.status.edit) {
        if (val === '1') {
          this.form.pid = null
        }
      }
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.getCategoryDataTree()
      if (this.crud.status.edit) {
        this.getClassifyTree(this.form.categoryId)
      } else {
        this.form.categoryId = null
        this.classifyOptions = []
      }
      if (form.id != null) {
        if (form.pid === null) {
          form.isTop = '1'
        } else {
          form.isTop = '0'
        }
      }
    },
    selectCategoryTree(val) {
      console.log(val)
      this.getClassifyTree(val.id)
    },
    filterData(data) {
      return data.filter(node => {
        if (node.children && node.children.length > 0) {
          node.children = this.filterData(node.children) // 递归处理子节点
        }
        return node.isType !== 3 // 过滤掉isType为3的节点
      })
    },
    getCategoryDataTree() {
      FetchCategoryMenu().then(res => {
        this.categoryDatas = this.filterData(res)
      })
    },
    getClassifyTree(categoryId) {
      crudClassify.FetchArchivesClassTree({ 'categoryId': categoryId }).then(res => {
        this.classifyOptions = res.map(function(obj) {
          if (obj.childArchivesClass !== null) {
            obj.hasChildren = true
          } else {
            obj.hasChildren = false
          }
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    // 获取弹窗内门类数据
    loadClassifyTree({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        crudClassify.FetchArchivesClassTree().then(res => {
          parentNode.children = res.map(function(obj) {
            if (obj.childArchivesClass !== 0) {
              obj.hasChildren = true
            } else {
              obj.hasChildren = false
            }
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 100)
        })
      }
    },
    getSonClass(tree, treeNode, resolve) {
      setTimeout(() => {
        crudClassify.FetchSonArchivesClass({ pid: tree.id }).then(res => {
          const data = res.map(function(obj) {
            if (obj.sonNum !== 0 && obj.sonNum) {
              obj.hasChildren = true
              obj.children = null
            } else {
              obj.hasChildren = false
            }
            return obj
          })
          resolve(data)
        })
      }, 100)
    },
    selectAll() {
      this.isAllSelect = !this.isAllSelect
      const data = this.tableData
      this.toggleSelect(data, this.isAllSelect, 'all')
    },
    // 选择某行
    selectTr(selection, row) {
      this.$set(row, 'isChecked', !row.isChecked)
      this.$nextTick(() => {
        this.isAllSelect = row.isChecked
        this.toggleSelect(row, row.isChecked, 'tr')
      })
    },
    // 递归子级
    toggleSelect(data, flag, type) {
      if (type === 'all') {
        if (data.length > 0) {
          data.forEach((item) => {
            this.toggleSelection(item, flag)
            if (item.children && item.children.length > 0) {
              this.toggleSelect(item.children, flag, type)
            }
          })
        }
      } else {
        if (data.children && data.children.length > 0) {
          data.children.forEach((item) => {
            item.isChecked = flag
            this.$refs.table.toggleRowSelection(item, flag)
            this.toggleSelect(item, flag, type)
          })
        }
      }
    },
    // 改变选中
    toggleSelection(row, flag) {
      this.$set(row, 'isChecked', flag)
      this.$nextTick(() => {
        if (flag) {
          this.$refs.table.toggleRowSelection(row, flag)
        } else {
          this.$refs.table.clearSelection()
        }
      })
    },
    // table - 当前选中得row
    clickRowHandler(row) {
      this.$refs.table.clearSelection()
      this.$refs.table.toggleRowSelection(row)
    },
    selectionChangeHandler(val) {
      this.selections = val
    },
    doExport(data) {
      crud.downloadLoading = true
      this.$confirm('此操作将导出所选数据' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const ids = []
        data.forEach(val => {
          ids.push(val.id)
        })
        const params = {
          'classIds': ids
        }
        exportFile(this.baseApi + '/api/archivesClass/download?' + qs.stringify(params, { indices: false }))
      }).catch(() => {
      })
    },
    toDelete(datas) {
      this.$confirm('此操作将删除当前所选' + this.crud.title + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        this.crud.delAllLoading = true
        const ids = []
        datas.forEach(val => {
          ids.push(val.id)
        })
        crudClassify.del(ids).then(() => {
          this.crud.notify('删除成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
          this.crud.delAllLoading = false
          this.crud.refresh()
        }).catch(err => {
          this.crud.delAllLoading = false
          console.log(err)
        })
      }).catch(() => {
      })
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.cnName,
        children: node.children,
        isDisabled: node.isType !== 2
      }
    },
    classifyNormalizer(node) {
      if (node.childArchivesClass && !node.childArchivesClass.length) {
        delete node.childArchivesClass
      }
      return {
        id: node.id,
        label: node.name,
        children: node.childArchivesClass
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.tip{
  line-height: 28px;
}
</style>
