<template>
  <div>
    <div style="display:flex">
      <div class="dict-type">
        <en-table-layout :tableData="tableDataType.data" :loading="loading" @cell-click="tableClick"
          style="cursor: pointer;">
          <div slot="toolbar" class="inner-toolbar">
            <div class="toolbar-btns">
              <span style="font-size:15px;padding-right:10px">字典分类列表</span>
              <el-button size="mini" v-if="checkPermission(['dictDataType:add'])" type="primary"
                @click="handleAddType">新增</el-button>
            </div>
            <div class="toolbar-search">

            </div>
          </div>

          <template slot="table-columns">
            <el-table-column prop="id" label="字典编号" />
            <el-table-column prop="name" label="字典名称" />
            <el-table-column prop="type" label="字典类型" />
            <el-table-column label="操作" width="150px">
              <template slot-scope="scope">
                <el-button size="mini" v-if="checkPermission(['dictDataType:edit'])"
                  @click="handleEditType(scope.$index, scope.row)">编辑</el-button>
                <el-button size="mini" v-if="checkPermission(['dictDataType:del'])" type="danger"
                  @click="handleDeleteType(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </template>

          <el-pagination v-if="tableDataType" slot="pagination" @size-change="handlePageSizeChangeType"
            @current-change="handlePageCurrentChangeType" :current-page="tableDataType.page_no"
            :page-sizes="[10, 20, 50, 100]" :page-size="tableDataType.page_size"
            layout="total, sizes, prev, pager, next, jumper" :total="tableDataType.data_total">
          </el-pagination>
        </en-table-layout>
      </div>
      <div class="dict-data">
        <en-table-layout :tableData="tableData.data" :loading="loading">
          <div slot="toolbar" class="inner-toolbar">
            <div class="toolbar-btns">
              <span style="font-size:15px;padding-right:10px">字典数据列表</span>
              <el-button size="mini" v-if="checkPermission(['dictData:add']) && params.dict_type" type="primary"
                @click="handleAddData">新增</el-button>
            </div>
            <div class="toolbar-search">

            </div>
          </div>

          <template slot="table-columns">
            <el-table-column prop="id" label="字典编码" />
            <el-table-column prop="label" label="字典标签" />
            <el-table-column prop="value" label="字典键值" />
            <el-table-column prop="sort" label="字典排序" />
            <el-table-column label="是否默认选中">
              <template slot-scope="{ row }">{{ row.default_flag === true ? '是' : '否' }}</template>
            </el-table-column>
            <el-table-column label="操作" width="150px">
              <template slot-scope="scope">
                <el-button size="mini" v-if="checkPermission(['dictData:edit'])"
                  @click="handleEditData(scope.$index, scope.row)">编辑</el-button>
                <el-button size="mini" v-if="checkPermission(['dictData:del'])" type="danger"
                  @click="handleDeleteData(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </template>

          <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
            @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[10, 20, 50, 100]"
            :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper"
            :total="tableData.data_total">
          </el-pagination>
        </en-table-layout>
      </div>
    </div>
    <el-dialog :title="dictTypeForm.id ? '编辑' : '添加'" :visible.sync="dialogTypeVisible" width="500px">
      <el-form :model="dictTypeForm" :rules="dictTypeRules" ref="dictTypeForm" label-width="120px">
        <el-form-item label="字典名称" prop="name">
          <el-input v-model="dictTypeForm.name" :minlength="2" :maxlength="20" clearable placeholder="请输入字典名称"></el-input>
        </el-form-item>
        <el-form-item label="字典类型" prop="type">
          <el-input v-model="dictTypeForm.type" :minlength="2" :maxlength="50" clearable placeholder="请输入字典类型"></el-input>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-radio v-model="dictTypeForm.status" :label="0">开启</el-radio>
          <el-radio v-model="dictTypeForm.status" :label="1">关闭</el-radio>
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="dictTypeForm.remark" type="textarea" :autosize="{ minRows: 3, maxRows: 4 }"
            placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTypeVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitTypeForm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="dictDataForm.id ? '编辑' : '添加'" :visible.sync="dialogVisible" width="500px">
      <el-form :model="dictDataForm" :rules="dictDataRules" ref="dictDataForm" label-width="120px">
        <el-form-item label="字典类型" prop="dict_type">
          <el-input v-model="dictDataForm.dict_type" :disabled="true" placeholder="请输入字典类型"></el-input>
        </el-form-item>
        <el-form-item label="是否默认选中" prop="是否默认选中">
          <el-radio v-model="dictDataForm.default_flag" :label="true">是</el-radio>
          <el-radio v-model="dictDataForm.default_flag" :label="false">否</el-radio>
        </el-form-item>
        <el-form-item label="字典标签" prop="label">
          <el-input v-model="dictDataForm.label" :minlength="1" :maxlength="20" clearable
            placeholder="请输入字典标签"></el-input>
        </el-form-item>
        <el-form-item label="字典值" prop="value">
          <el-input v-model="dictDataForm.value" :minlength="2" :maxlength="20" clearable placeholder="请输入字典值"></el-input>
        </el-form-item>
        <el-form-item label="顺序号" prop="sort">
          <el-input v-model="dictDataForm.sort" :minlength="2" :maxlength="20" clearable placeholder="请输入顺序号"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="dictDataForm.remark" type="textarea" :autosize="{ minRows: 3, maxRows: 4 }"
            placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDataForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as API_Setting from '@/api/setting'
import { RegExp } from '~/ui-utils'
export default {
  name: 'dictData',
  data() {
    return {
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10
      },
      paramsType: {
        page_no: 1,
        page_size: 10
      },
      // 列表数据
      tableData: '',
      tableDataType: '',
      // 字典表单
      dictDataForm: {},
      dictTypeForm: {},
      // 字典表单 规则
      dictTypeRules: {
        name: [
          this.MixinRequired('请输入字典名称！'),
          { min: 2, max: 20, message: '长度在 2 到 20 个字符' },
          {
            validator: (rule, value, callback) => {
              if (value && !RegExp.userName.test(value)) {
                callback(new Error('只支持汉字、字母、数字、“-”、“_”的组合！'))
              } else {
                callback()
              }
            }
          }
        ],
        type: [
          this.MixinRequired('请输入字典类型！'),
          { min: 2, max: 50, message: '长度在 2 到 50 个字符' },
          {
            validator: (rule, value, callback) => {
              if (value && !RegExp.userName.test(value)) {
                callback(new Error('只支持汉字、字母、数字、“-”、“_”的组合！'))
              } else {
                callback()
              }
            }
          }
        ]
      },
      dictDataRules: {
        dict_type: [
          this.MixinRequired('请输入字典类型！'),
          { min: 2, max: 50, message: '长度在 2 到 50 个字符' },
          {
            validator: (rule, value, callback) => {
              if (value && !RegExp.userName.test(value)) {
                callback(new Error('只支持汉字、字母、数字、“-”、“_”的组合！'))
              } else {
                callback()
              }
            }
          }],
        label: [
          this.MixinRequired('请输入字典标签！'),
          { min: 1, max: 20, message: '长度在 1 到 20 个字符' }],
        value: [this.MixinRequired('请输入字典值！')],
        sort: [this.MixinRequired('显示顺序不能为空！')]
      },
      // 字典表单 dialog
      dialogVisible: false,
      dialogTypeVisible: false
    }
  },
  mounted() {
    this.GET_DictDataList()
    this.GET_DictTypeList()
  },
  methods: {
    tableClick(row) {
      this.params.dict_type = row.type
      this.GET_DictDataList()
    },
    /** 分页大小发生改变 */
    handlePageSizeChangeType(size) {
      this.paramsType.page_size = size
      this.GET_DictTypeList()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChangeType(page) {
      this.paramsType.page_no = page
      this.GET_DictTypeList()
    },

    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_DictDataList()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_DictDataList()
    },
    handleAddType() {
      this.dictTypeForm = {
        status: 0
      }
      this.dialogTypeVisible = true
    },
    /** 添加字典 */
    handleAddData() {
      this.dictDataForm = {
        status: 0,
        sort: 0,
        dict_type: this.params.dict_type,
        default_flag: false
      }
      this.dialogVisible = true
    },
    handleEditType(index, row) {
      this.dictTypeForm = this.MixinClone(row)
      this.dialogTypeVisible = true
    },
    /** 编辑字典 */
    handleEditData(index, row) {
      this.dictDataForm = this.MixinClone(row)
      this.dialogVisible = true
    },
    handleDeleteType(index, row) {
      this.$confirm('确定要删除这个字典分类吗？', '提示', { type: 'warning' }).then(() => {
        API_Setting.deleteDictType({ id: row.id }).then(() => {
          this.$message.success('删除成功！')
          this.GET_DictTypeList()
        })
      }).catch(() => { })
    },
    /** 删除字典 */
    handleDeleteData(index, row) {
      this.$confirm('确定要删除这个字典吗？', '提示', { type: 'warning' }).then(() => {
        API_Setting.deleteDictData({ id: row.id }).then(() => {
          this.$message.success('删除成功！')
          this.GET_DictDataList()
        })
      }).catch(() => { })
    },
    /** dialog打开后重置form表单校验结果 */
    handleDialogOpen() {
      setTimeout(() => { this.$refs['dictDataForm'].clearValidate() })
    },
    submitTypeForm() {
      this.$refs['dictTypeForm'].validate((valid) => {
        if (valid) {
          const { id } = this.dictTypeForm
          const params = this.MixinClone(this.dictTypeForm)
          params.id = id
          if (id) {
            API_Setting.editDictType(params).then(response => {
              this.dialogTypeVisible = false
              this.$message.success('修改成功！')
              this.GET_DictTypeList()
            })
          } else {
            API_Setting.addDictType(params).then(() => {
              this.dialogTypeVisible = false
              this.$message.success('添加成功！')
              this.GET_DictTypeList()
            })
          }
        } else {
          this.$message.error('表单填写有误，请核对！')
          return false
        }
      })
    },
    /** 提交字典表单 */
    submitDataForm() {
      this.$refs['dictDataForm'].validate((valid) => {
        if (valid) {
          const { id } = this.dictDataForm
          const params = this.MixinClone(this.dictDataForm)
          params.id = id
          if (id) {
            API_Setting.editDictData(params).then(response => {
              this.dialogVisible = false
              this.$message.success('修改成功！')
              this.GET_DictDataList()
            })
          } else {
            API_Setting.addDictData(params).then(() => {
              this.dialogVisible = false
              this.$message.success('添加成功！')
              this.GET_DictDataList()
            })
          }
        } else {
          this.$message.error('表单填写有误，请核对！')
          return false
        }
      })
    },

    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        keyword: data
      }
      this.params.page_no = 1
      this.GET_DictDataList()
    },
    /** 获取字典类型列表 */
    GET_DictTypeList() {
      this.loading = true
      API_Setting.getDictTypeList(this.paramsType).then(response => {
        this.loading = false
        this.tableDataType = response
      }).catch(() => { this.loading = false })
    },
    /** 获取字典列表 */
    GET_DictDataList() {
      this.loading = true
      API_Setting.getDictDataList(this.params).then(response => {
        this.loading = false
        this.tableData = response
      }).catch(() => { this.loading = false })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.dict-type {
  width: 50%;
}

.dict-data {
  width: 50%;
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
