<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="description">
            <el-input v-model="queryParams.description" placeholder="请输入字典描述" clear />
          </el-form-item>
          <el-form-item label="字典类型" prop="dictKeyType">
            <el-input v-model="queryParams.dictKeyType" 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-col>
        </el-row>

        <!-- 表格数据信息 -->
        <el-table
          ref="dictTable"
          v-loading="loading"
          :data="dictList"
          row-key="id"
          border
          stripe
          header-row-class-name="headBackground"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column key="description" label="字典描述" align="center" prop="description" />
          <el-table-column key="dictKeyType" label="字典类型" align="center" prop="dictKeyType" />
          <el-table-column key="dictKeyValue" label="字典值" align="center" prop="dictKeyValue">
            <template slot-scope="scope">
              <el-link type="primary" @click="hendelTo(scope.row)">{{ scope.row.dictKeyValue }}</el-link>
            </template>
          </el-table-column>
          <el-table-column key="sortNum" label="排序号" align="center" prop="sortNum" />
          <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
            <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>
          </el-table-column>
        </el-table>

        <!-- 分页信息 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.page"
          :limit.sync="queryParams.num"
          align="right"
          @pagination="getAllDictType"
        />
      </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-form-item label="字典描述" prop="description">
          <el-input v-model.trim="form.description" clearable placeholder="请输入字典描述" />
        </el-form-item>
        <el-form-item label="字典类型" prop="dictKeyType">
          <el-input v-model.trim="form.dictKeyType" clearable placeholder="请输入字典类型" />
        </el-form-item>
        <el-form-item label="字典值" prop="dictKeyValue">
          <el-input v-model.trim="form.dictKeyValue" clearable placeholder="请输入字典值" />
        </el-form-item>
        <el-form-item label="排序号" prop="sortNum">
          <el-input
            v-model.trim="form.sortNum"
            placeholder="请输入排序号"
            controls-position="right"
            :minlengh="1"
            :maxlength="5"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="handelSubmit('form')">确定</el-button>
        <el-button size="mini" @click="handelCancel('form')">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getAllDictType, editDictType, addDictType, delDictType } from '@/api/system/dictType.js'
export default {
  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: true,
      // 查询参数
      queryParams: {
        page: 1,
        num: 10,
        description: null,
        dictKeyType: null
      },
      // 总条数
      total: 0,
      // 表格数据
      dictList: [],
      // 弹出框
      dialogVisible: false,
      // 弹出框标题
      title: '',
      // 弹出框表单
      form: {},
      // 字典树数据
      options: [],
      // 表单验证
      rules: {
        description: [
          { required: true, message: '字典描述不能为空', trigger: 'blur' }
        ],
        dictKeyType: [
          { required: true, message: '字典类型不能为空', trigger: 'blur' }
        ],
        dictKeyValue: [
          { required: true, message: '字典值不能为空', trigger: 'blur' }
        ],
        sortNum: [
          { required: true, validator: sortNumRule, trigger: 'blur' }
        ]
      },
      // 控制批量删除按钮
      multiple: true,
      // 删除字典id集合
      ids: [],
      // 自定义treeselect键名
      keyName: null,
      // 当前分页数据条数
      dictTotal: null
    }
  },
  created() {
    this.getAllDictType()
  },
  methods: {
    /** 查询所有字典类型 */
    getAllDictType() {
      getAllDictType(this.queryParams).then(res => {
        if (res.code === 200 & res.data === null) {
          this.dictList = []
          this.total = 0
          return
        }
        const data = res.data
        this.dictList = data.dictTypes
        this.total = data.count
        this.loading = false
      })
    },
    /** 搜索 */
    handelSearch(event) {
      this.$resetBtn(event)
      this.queryParams.page = 1
      this.getAllDictType()
    },
    /** 重置按钮操作 */
    handelReset(event) {
      this.$refs['queryForm'].resetFields()
      this.handelSearch(event)
    },
    /** 新增按钮 */
    handelAdd() {
      this.dialogVisible = true
      this.title = '添加字典'
    },
    /** 修改按钮 */
    handelEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true
      this.title = '修改字典'
    },
    /** 表格多选 */
    handleSelectionChange(val) {
      this.ids = val.map(item => item.id)
      this.multiple = !val.length
    },
    /** 删除按钮 */
    handelDel(id) {
      this.$confirm('您确定要删除该字典吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'btn_custom_cancel',
        closeOnClickModal: false,
        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',
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        if (this.ids.length === this.dictList.length) {
          this.queryParams.page -= 1
        }
        this.delDictType()
      }).catch(() => {
        this.$refs.dictTable.clearSelection()
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /** 删除接口 */
    delDictType() {
      delDictType(this.ids).then(res => {
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.getAllDictType()
        }
      })
    },
    /** 表单提交 */
    handelSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title === '添加字典') {
            addDictType(this.form).then(res => {
              if (res.code === 200) {
                this.$message({
                  message: res.data,
                  type: 'success'
                })
                this.getAllDictType()
                this.dialogVisible = false
              }
            })
          } else {
            editDictType(this.form).then(res => {
              if (res.code === 200) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.getAllDictType()
                this.dialogVisible = false
              }
            })
          }
        }
      })
    },
    /** 表单取消 */
    handelCancel() {
      this.dialogVisible = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {}
      if (this.$refs['form']) {
        this.$refs['form'].resetFields()
      }
    },
    /** 选择字典类型跳转 */
    hendelTo(row) {
      this.$router.push({
        path: '/system/dict/dict-detail/role/',
        query: row
      })
    }
  }
}
</script>

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

</style>
