<template>
  <div class="sy-content">
    <el-row>
      <el-col :span="24">
        <!-- 表单查询 -->
        <el-form ref="queryForm" :model="queryParams" :inline="true" size="small">
          <el-form-item label="字典名称" prop="dictValue">
            <el-input v-model="queryParams.dictValue" placeholder="请输入字典名称" clear />
          </el-form-item>
          <el-form-item label="字典值" prop="dictKey">
            <el-input v-model="queryParams.dictKey" placeholder="请输入字典值" clear />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handelSearch">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="handelReset">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row class="czBtns">
          <el-col>
            <el-button size="mini" icon="el-icon-plus" type="primary" plain @click="handelAdd">新增</el-button>
            <el-button
              type="danger"
              plain
              icon="el-icon-delete-solid"
              size="mini"
              :disabled="multiple"
              @click="handelDelAll"
            >批量删除</el-button>
            <el-button
              size="mini"
              icon="el-icon-back"
              type="warning"
              plain
              @click="(() => { this.$router.push('/system/dict') })"
            >返回</el-button>
          </el-col>
        </el-row>

        <!-- 表格数据信息 -->
        <vxe-table
          resizable
          :tree-config="{ transform: true, rowField: 'id', parentField: 'parentId' }"
          :data="dictList"
          align="center"
          border
          header-row-class-name="headBackground"
          stripe
          :loading="loading"
          @checkbox-change="select"
          @checkbox-all="select"
        >
          <vxe-column type="checkbox" width="60px" />
          <vxe-column field="dictKey" title="字典名称" tree-node show-overflow />
          <vxe-column field="dictValue" title="字典值" show-overflow />
          <vxe-column field="sortNum" title="排序号" show-overflow />
          <vxe-column title="操作">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handelEdit(scope.row)">修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                :disabled="!multiple"
                @click="handelDel(scope.row.id)"
              >删除
              </el-button>
            </template>
          </vxe-column>
        </vxe-table>

        <!-- 分页信息 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.page"
          :limit.sync="queryParams.num"
          align="right"
          @pagination="getPageDictList"
        />
      </el-col>
    </el-row>

    <!-- 弹出框 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级字典" prop="parentId">
              <selectTree v-model="form.parentId" :options="options" placeholder="请选择上级字典" :key-name="keyName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="字典名称" prop="dictKey">
              <el-input v-model.trim="form.dictKey" clearable placeholder="请输入字典名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="字典值" prop="dictValue">
              <el-input v-model.trim="form.dictValue" clearable placeholder="请输入字典值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序号" prop="sortNum">
              <el-input
                v-model.trim="form.sortNum"
                placeholder="请输入排序号"
                controls-position="right"
                :minlength="1"
                :maxlength="5"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handelSubmit('form')">确 定</el-button>
        <el-button @click="handelCancel('form')">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { delDict, addDict, getPageDictList, editDict, getDictListByType } from '@/api/system/dict.js'
import selectTree from '@/components/SelectTree'
export default {
  components: { selectTree },
  data() {
    const sortNumRule = (rule, value, callback) => {
      var reg = /^[1-9][0-9]*$/
      if (!value) {
        callback(new Error('排序号不能为空'))
      }
      if (!(reg.test(value))) {
        callback(new Error('只能输入正整数'))
      }
      callback()
    }
    return {
      // 遮罩层
      loading: false,
      // 查询参数
      queryParams: {
        page: 1,
        num: 10
      },
      // 总条数
      total: 0,
      // 表格数据
      dictList: [],
      // 弹出框
      dialogVisible: false,
      // 弹出框标题
      title: '',
      // 弹出框表单
      form: {
        parentId: 0
      },
      // 字典树数据
      options: [],
      // 表单验证
      rules: {
        dictValue: [
          { required: true, message: '字典值不能为空', trigger: 'blur' }
        ],
        dictKey: [
          { required: true, message: '字典名称不能为空', trigger: 'blur' }
        ],
        sortNum: [
          { required: true, trigger: 'blur', validator: sortNumRule }
        ]
      },
      // 控制批量删除按钮
      multiple: true,
      // 删除字典id集合
      ids: [],
      // 自定义treeselect键名
      keyName: null,
      // 字典类型
      keyType: null
    }
  },
  created() {
    const { id, dictKeyType } = this.$route.query
    this.form.dictTypeId = id
    this.queryParams.dictTypeId = id
    this.keyType = dictKeyType
    this.getPageDictList()
  },
  methods: {
    /** 分页获取字典列表数据 */
    getPageDictList() {
      getPageDictList(this.queryParams).then(res => {
        if (res.code === 200 & res.data === null) {
          this.dictList = []
          this.total = 0
          return
        }
        const data = res.data
        this.dictList = this.$utils.toTreeArray(data.dictPage, { clear: true })
        this.total = data.count
        this.getDictListByType()
      })
    },
    /** 全量获取字典列表数据 */
    getDictListByType() {
      getDictListByType({ keyType: this.keyType }).then(res => {
        const data = res.data
        this.options = this.$utils.toArrayTree(data)
        this.keyName = 'dictKey'
      })
    },
    /** 搜索 */
    handelSearch(event) {
      this.$resetBtn(event)
      this.queryParams.page = 1
      this.getPageDictList()
    },
    /** 重置按钮操作 */
    handelReset(event) {
      this.$refs['queryForm'].resetFields()
      this.handelSearch(event)
    },
    /** 新增按钮 */
    handelAdd() {
      this.dialogVisible = true
      this.title = '添加字典'
      this.reset()
    },
    /** 修改按钮 */
    handelEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true
      this.title = '修改字典'
    },
    /** 表格多选 */
    select({ $table }) {
      const records = $table.getCheckboxRecords()
      this.ids = records.map(item => item.id)
      this.multiple = !records.length
    },
    /** 删除按钮 */
    handelDel(id) {
      this.$confirm('您确定要删除该字典吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'btn_custom_cancel',
        type: 'warning'
      }).then(() => {
        if (this.dictList.length === 1) {
          this.queryParams.page -= 1
        }
        this.ids.push(id)
        this.delDictType()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /** 批量删除 */
    handelDelAll() {
      this.$confirm('您确定要批量删除选中的字典吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'btn_custom_cancel',
        type: 'warning'
      }).then(() => {
        if (this.ids.length === this.dictList.length) {
          this.queryParams.page -= 1
        }
        this.delDictType()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /** 删除接口 */
    delDictType() {
      delDict(this.ids).then(res => {
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.getPageDictList()
        }
      })
    },
    /** 表单提交 */
    handelSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title === '添加字典') {
            addDict(this.form).then(res => {
              if (res.code === 200) {
                this.$message({
                  message: res.data,
                  type: 'success'
                })
                this.getPageDictList()
                this.dialogVisible = false
              }
            })
          } else {
            if (this.form.parentId === undefined) {
              this.form.parentId = 0
              return
            }
            editDict(this.form).then(res => {
              if (res.code === 200) {
                this.$message({
                  message: res.data,
                  type: 'success'
                })
                this.getPageDictList()
                this.dialogVisible = false
              }
            })
          }
        }
      })
    },
    /** 表单取消 */
    handelCancel() {
      this.dialogVisible = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      if (this.$refs['form']) {
        this.$refs['form'].resetFields()
      }
    }
  }
}
</script>

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

</style>
