<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true">
      <el-form-item label="字典名称" prop="dictName">
        <el-input
          v-model="queryParams.dictName"
          placeholder="请输入字典名称"
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="字典类型" prop="dictType">
        <el-input
          v-model="queryParams.dictType"
          placeholder="请输入字典类型"
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="字典状态"
          clearable
          style="width: 200px">
                    <el-option
                      v-for="dict in sysStatusDicts"
                      :key="dict.dictValue"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"/>
          <!--          <el-option :key="0" label="正常" :value="0"/>-->
          <!--          <el-option :key="1" label="停用" :value="1"/>-->
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:dict:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleRefresh"
          v-hasPermi="['system:dict:list']"
        >刷新缓存
        </el-button>
      </el-col>

    </el-row>

    <el-table :data="dictList" size="mini">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-descriptions v-for="(dictData,index) in props.row.dictDataList" :key="index" :column="4" size="mini">
            <el-descriptions-item label="标签">{{ dictData.dictLabel }}</el-descriptions-item>
            <el-descriptions-item label="键值">{{ dictData.dictValue }}</el-descriptions-item>
            <el-descriptions-item label="排序">{{ dictData.dictSort }}</el-descriptions-item>
            <el-descriptions-item label="备注">{{ dictData.remark }}</el-descriptions-item>
          </el-descriptions>
        </template>
      </el-table-column>
      <el-table-column label="字典编号" prop="id" width="100"/>
      <el-table-column label="字典名称" prop="dictName"/>
      <el-table-column label="字典类型" prop="dictType"/>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" width="180"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dict:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:dict:delete']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top: 10px;text-align: center">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 添加或修改字典配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" size="mini" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="字典名称" prop="dictName">
              <el-input v-model="form.dictName" placeholder="请输入字典名称" style="width: 180px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字典类型" prop="dictType">
              <el-input v-model="form.dictType" placeholder="请输入字典类型" style="width: 180px"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button type="text" icon="el-icon-circle-plus-outline"
                       style="float: right;font-size: 22px; margin-top: -8px" @click="addDictData"></el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12" v-for="(dictData,index) in form.dictDataList" :key="index">
            <el-card shadow="always" class="item-card">
              <div slot="header" class="clearfix">
                <span>字典数据{{ index + 1 }}</span>
                <el-button type="text" icon="el-icon-delete" @click="delDictData(index)"
                           style="float: right;color: red; padding: 3px 0"></el-button>
              </div>
              <el-form ref="dictDataForm" :model="dictData" :rules="rules" size="mini" label-width="50px">
                <el-form-item label="标签" prop="dictLabel">
                  <el-input v-model="dictData.dictLabel"/>
                </el-form-item>
                <el-form-item label="键值" prop="dictValue">
                  <el-input v-model="dictData.dictValue"/>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="dictData.remark"/>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listDict,
  getDict,
  delDict,
  addDict,
  updateDict, refreshDictCache, getDictData,
} from "@/api/system/dict";

export default {
  name: "dict",
  data() {
    return {
      sysStatusDicts:[],
      // 总条数
      total: 0,
      // 字典表格数据
      dictList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],

      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dictName: undefined,
        dictType: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      defaultProps: {
        dictDataList: "dictDataList",
        label: "menuName"
      },
      // 表单校验
      rules: {
        dictName: [
          {required: true, message: "字典名称不能为空", trigger: "blur"}
        ],
        dictType: [
          {required: true, message: "字典类型不能为空", trigger: "blur"}
        ],
        dictSort: [
          {required: true, message: "字典顺序不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.initData();
  },
  methods: {
    initData(){
      this.getList();
      getDictData('sys_status').then(res => {
        this.sysStatusDicts=res.data
      })
    },
    /** 查询字典列表 */
    getList() {
      listDict(this.queryParams).then(response => {
          this.dictList = response.data.records;
          this.total = response.data.total;
        }
      );
    },

    // 字典状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.dictName + '"字典吗？').then(function () {
        return changeCStatus(row.id, row.status);
      }).then(() => {
        this.$message.success(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        dictName: undefined,
        dictType: undefined,
        dictSort: 0,
        status: "0",
        remark: undefined,
        dictDataList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加字典";
    },
    /** 刷新字典缓存操作 */
    handleRefresh() {
      refreshDictCache().then(res => {
        if (res.success) {
          this.$message({
            message: '操作成功!',
            type: 'success'
          });
        }
      })


    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDict(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改字典";
      });
    },

    addDictData() {
      let child = {
        dictLabel: undefined,
        dictValue: undefined,
        remark: undefined
      }
      this.form.dictDataList.push(child)
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateDict(this.form).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDict(this.form).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除字典编号为"' + ids + '"的数据项？').then(() => {
        return delDict(ids);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {
      });
    },
  }
};
</script>

<style scoped lang="scss">
.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
  margin-bottom: 10px;
}

.item-card ::v-deep {
  margin-bottom: 10px;

  .el-card__header {
    padding: 10px 10px 0px 10px;
  }

  .el-card__body {
    padding: 10px;
  }
}

</style>
