<template>
  <el-container class="content-height-fit">
    <el-container style="width: 100%; padding: 16px">
      <div class="app-container w100p blue-top-border" style="padding: 0px">
        <div class="filter-container">
          <el-input v-model="filterText" placeholder="关键字" class="filter-item" clearable />
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
          <el-button v-if="$requirePermission('XT.ZD.C')" v-waves class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">新增</el-button>
        </div>
        <div class="content-container">
          <el-row class="tree-title">
            <el-col :span="4">类型名称</el-col>
            <el-col :span="4">类型编码</el-col>
            <el-col :span="4">上级字典</el-col>
            <el-col :span="4">上级数据条目</el-col>
            <el-col :span="4">备注</el-col>
            <el-col :span="4">操作</el-col>
          </el-row>
          <el-scrollbar wrap-class="scrollbar-wrapper" style="height: calc(100vh - 262px); overflow-x: hidden">
            <el-tree
              ref="tree"
              v-loading="listLoading"
              default-expand-all
              :data="list"
              node-key="id"
              :props="{ children: 'children', label: 'name' }"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
            >
              <el-row slot-scope="{ data }" class="custom-tree-node">
                <el-col :span="4">
                  <span>{{ data.name }}</span>
                </el-col>
                <el-col :span="4">
                  <span>{{ data.code }}</span>
                </el-col>
                <el-col :span="4">
                  <span>{{ data.parentName }}</span>
                </el-col>
                <el-col :span="4">
                  <span>{{ data.parentEntryName }}</span>
                </el-col>
                <el-col :span="4">
                  <span>{{ data.remark }}</span>
                </el-col>
                <el-col :span="4">
                  <span>
                    <el-button type="text" size="small" @click="() => handleCreate(data)">新增子项</el-button>
                    <el-button type="text" size="small" @click="() => handleUpdate(data)">修改</el-button>
                    <el-button type="text" size="small" @click="() => handleDelete(data)">删除</el-button>
                  </span>
                </el-col>
              </el-row>
            </el-tree>
          </el-scrollbar>
        </div>
        <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
          <el-form ref="dataForm" v-loading="formLoading" :rules="rules" :model="dict" label-width="120px">
            <el-row :gutter="16">
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="名称" prop="name">
                  <el-input v-model="dict.name" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="编码" prop="code">
                  <el-input v-model="dict.code" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="上级字典" prop="parentCode">
                  <el-select v-model="dict.parentCode" filterable class="w100p">
                    <el-option v-for="item in flatList" :key="item.code" :label="item.name" :value="item.code" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="上级字典条目" prop="parentEntryCode">
                  <el-select v-model="dict.parentEntryCode" filterable class="w100p">
                    <el-option v-for="item in entryList" :key="item.code" :label="item.name" :value="item.code" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="dict.remark" type="textarea" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button :disabled="formLoading" @click="dialogFormVisible = false">取消</el-button>
            <el-button :disabled="formLoading" type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">确认</el-button>
          </div>
        </el-dialog>
      </div>
    </el-container>
  </el-container>
</template>

<script>
import * as dictApi from '@/api/dict'
import * as entryApi from '@/api/dict-entry'
import waves from '@/directive/waves' // waves directive

export default {
  name: 'DictMng',
  directives: { waves },
  data() {
    return {
      filterText: '',
      list: [],
      row: {},
      flatList: [],
      entryList: [],
      dict: {
        id: undefined,
        name: undefined,
        code: undefined,
        parentCode: undefined,
        parentEntryCode: undefined
      },
      formLoading: false,
      listLoading: false,
      listQuery: {
        name: undefined,
        code: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '创建'
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { max: 64, message: '长度必须少于64个字符', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入编码', trigger: 'blur' },
          { max: 32, message: '长度必须少于32个字符', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    'dict.parentCode': function(val) {
      var parentDict = this.flatList.find(t => t.code === val)
      if (parentDict) {
        this.dict.parentName = parentDict.name
        entryApi.lookupByDict({ dictName: parentDict.name }).then(res => {
          this.entryList = res
        })
      } else {
        this.dict.parentName = undefined
        this.entryList = []
      }
    },
    'dict.parentEntryCode': function(val) {
      var parentEntry = this.entryList.find(t => t.code === val)
      if (parentEntry) {
        this.dict.parentEntryName = parentEntry.name
      }
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1 || data.code.indexOf(value) !== -1
    },
    getList() {
      this.listLoading = true
      // var query = Object.assign({}, this.listQuery, { isRoot: true });
      dictApi
        .getList(this.listQuery)
        .then(res => {
          // 构建树型结构
          var roots = res.filter(t => t.parentCode == null)
          roots.forEach(t => this.makeTree(res, t))
          this.list = roots
          this.flatList = res.map(t => {
            return { code: t.code, name: t.name }
          })
        })
        .finally(() => {
          this.listLoading = false
          this.$nextTick(() => {
            this.$refs.tree.filter(this.filterText)
          })
        })
    },
    makeTree(list, parent) {
      var parentCode = parent ? parent.code : null
      var children = list.filter(t => t.parentCode === parentCode)

      parent.children = children
      parent.children.forEach(t => {
        this.makeTree(list, t)
      })
    },
    handleFilter() {
      this.getList()
    },
    resetDict() {
      this.dict = {
        id: undefined,
        name: undefined,
        code: undefined,
        parentCode: undefined,
        parentEntryCode: undefined
      }
    },
    handleCreate(row) {
      this.resetDict()
      if (row) {
        this.dict.parentCode = row.code
        this.dict.parentName = row.name
      }
      this.row = row
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.formLoading = false
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.formLoading = true
          dictApi.create(this.dict).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.dict = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.formLoading = false
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.formLoading = true
          const updateData = Object.assign({}, this.dict)
          dictApi.update(updateData.id, updateData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        dictApi
          .remove(row.id)
          .then(() => {
            this.getList()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
          .finally(() => {
            this.listLoading = false
          })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.content-container {
  ::v-deep .scrollbar-wrapper {
    overflow-x: hidden;
  }

  ::v-deep .el-tree-node {
    border-top: 1px solid #dfe6ec;
  }

  ::v-deep .el-tree {
    border-bottom: 1px solid #dfe6ec;
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    height: 32px;
  }

  .tree-title {
    background: #2294ff;
    color: #fff;
    font-weight: bold;
    font-size: 1.1em;

    .el-col {
      padding: 8px;
      padding-left: 24px;
    }
  }
}
</style>
