<template>
  <div class="app-container row-container">
    <!--工具栏-->
    <div class="head-container">
      <div class="head-search">
        <!-- 搜索 -->
        <el-input v-model="query.blurry" clearable size="small" placeholder="输入字典名称或字典代码搜索" prefix-icon="el-icon-search" style="width: 240px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-button class="filter-item filter-search" size="mini" type="success" icon="el-icon-search" @click="crud.toQuery">搜索</el-button>
        <el-button v-if="crud.optShow.reset" class="filter-item  filter-refresh" size="mini" type="warning" icon="el-icon-refresh-left" @click="resetQuery()">重置</el-button>
      </div>
      <crudOperation :permission="permission">
        <template v-slot:middle>
          <el-button slot="reference" size="mini" :loading="crud.delAllLoading" :disabled="crud.selections.length === 0" @click="toDelete(crud.selections)">
            <i class="iconfont icon-shanchu" />
            删除
          </el-button>
        </template>
        <template v-slot:right>
          <el-button :loading="crud.downloadLoading" size="mini" :disabled="crud.selections.length === 0" @click="doExport(crud.selections)">
            <i class="iconfont icon-daochu" />
            导出
          </el-button>
        </template>
      </crudOperation>
    </div>
    <!--表单组件-->
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible="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 label="字典名称" prop="dictionaryName">
            <el-input v-model="form.dictionaryName" />
          </el-form-item>
          <el-form-item label="字典代码" prop="dictionaryCode">
            <el-input v-model="form.dictionaryCode" />
          </el-form-item>
          <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 label="排序" prop="dictionaryOrder">
            <el-input-number
              v-model.number="form.dictionaryOrder"
              :min="0"
              :max="999"
              controls-position="right"
            />
          </el-form-item>
          <el-row>
            <el-form-item v-if="form.isTop === '0'" label="上级节点" prop="dictionaryParents">
              <treeselect
                v-model="form.dictionaryParents"
                style="width: 584px;"
                :load-options="loadDicts"
                :options="dicts"
                :normalizer="normalizer"
                placeholder="选择上级节点"
              >
                <div slot="value-label" slot-scope="{ node }">{{ getAutoNameUnknown(node.label) }}</div>
              </treeselect>
            </el-form-item>
          </el-row>
          <el-form-item label="内容说明" prop="dictionaryRemarks">
            <el-input v-model="form.dictionaryRemarks" type="textarea" :rows="4" style="width: 584px;" />
          </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>
    <!-- <el-dialog title="删除字典内容" :visible.sync="deleteVisible" :before-close="handleClose">
      <span class="dialog-right-top" />
      <span class="dialog-left-bottom" />
      <div class="setting-dialog">
        <div class="dialog-delt">
          <p><span>确定删除当前字典内容吗？</span></p>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click.native="handleConfirm">确定</el-button>
        </div>
      </div>
    </el-dialog> -->
    <div class="container-wrap">
      <span class="right-top-line" />
      <span class="left-bottom-line" />
      <!--表格渲染-->
      <!-- @selection-change="selectionChangeHandler"
        @row-click="clickRowHandler" -->
      <!-- height="calc(100vh - 232px)" -->
      <el-table
        ref="table"
        v-loading="crud.loading"
        lazy
        :load="getDictsDatas"
        :data="tableData"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        :row-key="getRowKey"
        style="width: 100%;"
        @select-all="selectAll"
        @select="selectTr"
        @selection-change="crud.selectionChangeHandler"
        @row-click="clickRowHandler"
      >
        <el-table-column type="selection" align="center" width="55" />
        <el-table-column prop="dictionaryName" label="字典名称" />
        <el-table-column prop="dictionaryCode" label="字典代码" />
        <el-table-column prop="dictionaryRemarks" label="内容说明" />
        <el-table-column prop="dictionaryOrder" label="排序" />
        <el-table-column prop="createTime" label="创建日期" width="200px">
          <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 crudDict from '@/api/system/dict'
// import crudDictDetail from '@/api/archivesConfig/dictDetail'
import CRUD, { presenter, header, form } 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 { mapGetters } from 'vuex'
import { exportFile } from '@/utils/index'
import qs from 'qs'

const defaultForm = { id: null, dictionaryName: null, isTop: '1', dictionaryCode: null, dictionaryOrder: 999, dictionaryRemarks: null, dictionaryParents: null }

export default {
  name: 'Dicts',
  components: { crudOperation, Treeselect, pagination },
  cruds() {
    return [
      CRUD({
        title: '字典', idField: 'dictionaryId', url: 'api/dictionary/initDictionaryList',
        crudMethod: { ...crudDict },
        sort: [],
        optShow: {
          add: true,
          edit: true,
          del: false,
          reset: true,
          download: false,
          group: false
        }})
    ]
  },
  mixins: [
    presenter(),
    header(),
    form(function() {
      return Object.assign({ dictionaryParents: this.dictionaryParents }, defaultForm)
    })
  ],
  props: {
    activeAddBtn: {
      type: Boolean
    }
  },
  data() {
    return {
      dicts: [],
      dictionaryParents: null,
      rules: {
        dictionaryName: [
          { required: true, message: '请输入字典名称', trigger: 'blur' }
        ],
        dictionaryCode: [
          { required: true, message: '请输入字典代码', trigger: 'blur' }
        ],
        isTop: [
          { required: true, message: '请选择是否为顶级节点', trigger: 'change' }
        ],
        dictionaryOrder: [
          { required: true, message: '请输入序号', trigger: 'blur', type: 'number' }
        ]
      },
      permission: {
        add: ['admin', 'dict:add'],
        edit: ['admin', 'dict:edit'],
        del: ['admin', 'dict:del']
      },
      deleteVisible: false,
      deleteData: {},
      isAllSelect: false
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  mounted() {
  },
  methods: {
    // 处理vue-treeSelect回显出现unknown问题
    getAutoNameUnknown(name) {
      if (name.lastIndexOf('unknown') > -1) {
        return name.split('(')[0]
      } else {
        return name
      }
    },
    getRowKey(row) {
      return row.dictionaryId
    },
    resetQuery() {
      this.crud.query.blurry = ''
      this.crud.toQuery()
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      if (form.dictionaryParents !== null) {
        form.isTop = '0'
      } else if (form.dictionaryId !== null) {
        form.isTop = '1'
      }
      this.getDictsTreeList()
    },
    // 获取数据前设置默认参数
    [CRUD.HOOK.beforeRefresh]() {
      this.tableData = []
    },
    [CRUD.HOOK.afterRefresh](crud) {
      crud.data.forEach(function(item, index) {
        if (item.sonNum !== 0) {
          item.hasChildren = true
        } else {
          item.hasChildren = false
        }
        if (!item.hasChildren) {
          item.children = null
        }
      })
      this.tableData = this.crud.data
    },
    // 编辑前
    [CRUD.HOOK.beforeToEdit](crud, form) {
      crud.form.id = form.dictionaryId
    },
    // 提交前的验证
    [CRUD.HOOK.afterValidateCU](crud) {
      if (crud.form.isTop === '1') {
        crud.form.dictionaryParents = null
      }
      delete crud.form.isTop
      console.log(crud.form)
      return true
    },
    changeIsTop(val) {
      if (val === '0') {
        this.getDictsTreeList()
      }
    },
    selectAll() {
      this.isAllSelect = !this.isAllSelect
      const data = this.tableData
      this.toggleSelect(data, this.isAllSelect, 'all')
      console.log(data)
    },
    // 选择某行
    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()
        }
      })
    },
    clickRowHandler(row) {
      this.$refs.table.clearSelection()
      this.$refs.table.toggleRowSelection(row)
    },
    getDictsDatas(tree, treeNode, resolve) {
      setTimeout(() => {
        console.log(treeNode)
        crudDict.FetchSonDictionaryList({ pid: tree.dictionaryId }).then(res => {
          const data = res.map(function(obj) {
            if (obj.sonNum !== 0) {
              obj.hasChildren = true
              obj.children = null
            } else {
              obj.hasChildren = false
            }
            return obj
          })
          resolve(data)
        })
      }, 100)
    },
    getDictsTreeList() {
      crudDict.FetchDictionaryTree().then(res => {
        this.dicts = res.map(function(obj) {
          if (obj.sonNum !== 0) {
            obj.hasChildren = true
          } else {
            obj.hasChildren = false
          }
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
        this.crud.loading = false
      })
    },
    // 获取弹窗内字典数据
    loadDicts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        crudDict.FetchDictionaryTree().then(res => {
          parentNode.children = res.map(function(obj) {
            if (obj.children) {
              obj.childMenus = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 100)
        })
      }
    },
    toDelete(datas) {
      this.deleteData = datas
      this.$confirm('此操作将删除当前所选' + this.crud.title + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        this.crud.delAllLoading = true
        const dictionaryIds = []
        this.deleteData.forEach(val => {
          dictionaryIds.push(val.dictionaryId)
        })
        crudDict.del(dictionaryIds).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(() => {
      })
    },
    doExport(data) {
      console.log(data)
      this.crud.downloadLoading = true
      this.$confirm('此操作将导出所选数据' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const ids = []
        data.forEach(val => {
          ids.push(val.dictionaryId)
        })
        const params = {
          'dictionaryIds': ids
        }
        exportFile(this.baseApi + '/api/dictionary/download?' + qs.stringify(params, { indices: false }))
        this.crud.downloadLoading = false
      }).catch(() => {
      })
    },
    normalizer(node) {
      if (node.childDictionarys == null || node.childDictionarys === 'null') {
        delete node.childDictionarys
      }
      return {
        id: node.id,
        label: node.dictionaryName,
        children: node.childDictionarys
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
