<template>
  <div>
    <el-row>
      <el-col :span="12">
        <!-- 表单查询 -->
        <el-form ref="queryForm" :model="queryParams" :inline="true" size="small">
          <el-form-item label="" prop="dictKey">
            <el-input v-model="queryParams.dictKey" prefix-icon="el-icon-search" placeholder="请输入名称" clear />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="small" @click="handelSearch">搜索</el-button>
            <el-button type="info" icon="el-icon-refresh" size="small" @click="handelReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="12">
        <el-row class="czBtns" style="float: right;">
          <el-col>
            <el-button size="small" icon="el-icon-plus" type="primary" @click="handelAdd">新增</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete-solid"
              size="small"
              :disabled="multiple"
              @click="handelDelAll"
            >批量删除</el-button>
            <el-button size="small" icon="el-icon-back" type="info" @click="handelGo">返回</el-button>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <!-- 表格数据信息 -->
        <el-table
          ref="table"
          :data="mulData"
          row-key="id"
          header-row-class-name="headBackground"
          @select="select"
          @select-all="selectAll"
          @selection-change="selectChange"
        >
          <el-table-column type="selection" align="left" />
          <el-table-column label="名称" prop="dictKey" show-overflow-tooltip header-align="left" />
          <el-table-column label="值" prop="dictValue" show-overflow-tooltip align="left" />
          <el-table-column label="排序号" prop="sortNum" show-overflow- align="left" width=100 />
          <el-table-column label="操作" align="left" 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)"
              >删除
              </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="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 :key="key" v-model="form.parentId" :options="options" placeholder="请选择上级字典" :key-name="keyName" menu-name="主字典" />
            </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" maxlength="15" 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" maxlength="15" 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 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 { delDict, addDict, getPageDictList, editDict, getDictListByType, getDictDetail } from '@/api/system/dict.js'
import selectTree from '@/components/SelectTree'
import multiple from '@/views/system/mixins/multiple'
export default {
  components: { selectTree },
  mixins: [multiple],
  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,
        dictValue: null,
        dictKey: null
      },
      // 总条数
      total: 0,
      // 表格数据
      mulData: [],
      // 弹出框
      dialogVisible: false,
      // 弹出框标题
      title: '',
      // 弹出框表单
      form: {
        parentId: 0,
        dictValue: null,
        dictKey: null,
        sortNum: null
      },
      // 字典树数据
      options: [],
      // 表单验证
      rules: {
        dictValue: [
          { required: true, message: '字典值不能为空', trigger: 'blur' }
        ],
        dictKey: [
          { required: true, message: '字典名称不能为空', trigger: 'blur' }
        ],
        sortNum: [
          { required: false, trigger: 'blur', validator: sortNumRule }
        ]
      },
      // 控制批量删除按钮
      multiple: true,
      // 删除字典id集合
      ids: [],
      // 自定义treeselect键名
      keyName: null,
      // 字典类型
      keyType: null,
      // 更新下拉树
      key: 0
    }
  },
  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.mulData = []
          this.total = 0
          return
        }
        const data = res.data
        this.mulData = data.dictPage
        this.total = data.count
        this.defaultExpand(this.mulData)
      })
    },
    /** 默认收起所有行 */
    defaultExpand(data) {
      data.forEach(item => {
        this.$refs.table && this.$refs.table.toggleRowExpansion(item, false)
        if (item.children && item.children.length) {
          this.defaultExpand(item.children)
        }
      })
    },
    /** 全量获取字典列表数据 */
    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)
    },
    /** 返回按钮 */
    handelGo() {
      this.$store.dispatch('tagsView/delVisitedView', this.$route)
      this.$router.push('/system/dict')
    },
    /** 新增按钮 */
    handelAdd() {
      this.dialogVisible = true
      this.key++
      this.title = '新增字典'
      this.reset()
      this.getDictListByType()
    },
    /** 修改按钮 */
    handelEdit(row) {
      this.key++
      getDictDetail({ dictId: row.id }).then(res => {
        if (res.code === 200) {
          this.form = res.data
          this.getDictListByType()
        }
      })
      this.dialogVisible = true
      this.title = '修改字典'
    },
    /** 表格多选 */
    selectChange(selection) {
      this.ids = selection
      this.multiple = !selection.length
    },
    /** 删除按钮 */
    handelDel(row) {
      this.$confirm('您确定要删除该字典吗?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'btn_custom_cancel',
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        if (row.children && row.children.length) {
          this.$message({
            type: 'warning',
            message: '请先删除下级字典'
          })
        } else {
          if (this.mulData.length === 1 && this.queryParams.page > 1) {
            this.queryParams.page -= 1
          }
          this.ids.push(row.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.some(o => o.children && o.children.length)) {
          this.$message({
            type: 'warning',
            message: '请先删除下级字典'
          })
          this.$refs.table.clearSelection()
        } else {
          this.ids = this.ids.map(item => item.id)
          if (this.ids.length === this.mulData.length && this.queryParams.page > 1) {
            this.queryParams.page -= 1
          }
          this.delDictType()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
        this.$refs.table.clearSelection()
      })
    },
    /** 删除接口 */
    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
            }
            if (this.form.parentId === this.form.id) {
              this.$message({
                message: '不可选择与自身相同的上级字典',
                type: 'warning'
              })
              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>
