<!-- 角色管理 -->
<template>
  <basic-container>
    <el-form>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="类型">
            <el-input v-model="searchList.dictType" placeholder="请输入角色名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="字典类型">
            <el-select v-model="searchList.systemFlag" clearable placeholder="请选择数据权限">
              <el-option v-for="item in dictType" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" :icon="Search" @click="getList">查询</el-button>
          <el-button :icon="Refresh" @click="clearSearch">清空</el-button>
        </el-col>
      </el-row>
    </el-form>
    <div>
      <el-row style="margin-bottom: 10px">
        <el-button type="primary" :icon="Plus" @click="addOrUpdateHandle(false)">新增</el-button>
        <!-- <el-button type="primary" :icon="RefreshLeft" @click="addOrUpdateHandle(0)">缓存</el-button> -->
      </el-row>
      <el-table v-loading="tableLoading" border :data="tableData" row-key="id">
        <el-table-column type="index" label="序号" align="center" width="60" />
        <el-table-column prop="dictType" label="类型" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="systemFlag" label="字典类型">
          <template #default="{ row }">
            {{ row.systemFlag === "1" ? "系统类" : "业务类" }}
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注信息" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="220" align="center" class-name="small-padding fixed-width">
          <template #default="{ row }">
            <div class="table_btn">
              <el-button size="small" :icon="EditPen" @click="addOrUpdateHandle(row)">编辑</el-button>
              <el-button size="small" :icon="Delete" @click="handleDelete(row)">删除</el-button>
              <el-button size="small" :icon="Menu" @click="openDictItem(row)">字典项</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="tablePage.total > 0"
        v-model:page="tablePage.currentPage"
        v-model:limit="tablePage.pageSize"
        :total="tablePage.total"
        @pagination="getList"
      />

      <el-dialog v-model="dictVisible" :title="title" width="50%" :before-close="dictClose">
        <el-form :model="dictForm" ref="dictRef" :rules="dictRules" label-width="80px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="类型" prop="dictType">
                <el-input v-model="dictForm.dictType" placeholder="请输入类型" clearable :disabled="title === '修改'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="描述" prop="description">
                <el-input v-model="dictForm.description" placeholder="请输入描述" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="字典类型" prop="systemFlag">
                <el-select v-model="dictForm.systemFlag" clearable placeholder="请选择字典类型">
                  <el-option v-for="item in dictType" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注信息">
                <el-input v-model="dictForm.remarks" placeholder="请输入备注信息" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="title === '修改'">
            <el-col :span="12">
              <el-form-item label="创建时间">
                <el-input v-model="dictForm.createTime" disabled />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-row class="btn_center">
            <el-button v-if="title === '添加'" type="primary" @click="addDict">保存</el-button>
            <el-button v-if="title === '修改'" type="primary" @click="saveDict">修改</el-button>
            <el-button @click="dictVisible = false">取消</el-button>
          </el-row>
        </template>
      </el-dialog>

      <el-dialog v-model="dictItemVisible" title="字典项管理" width="70%">
        <el-row>
          <el-button :icon="Plus" type="primary" @click="openDictItemDialog(false)">新增</el-button>
        </el-row>
        <el-table v-loading="dialogTableLoading" border :data="dialogTableData" row-key="id">
          <el-table-column type="index" label="序号" align="center" width="60" />
          <el-table-column prop="dictType" label="类型" />
          <el-table-column prop="value" label="数据值" />
          <el-table-column prop="label" label="标签名" />
          <el-table-column prop="description" label="描述" />
          <el-table-column prop="sortOrder" label="排序" />
          <el-table-column prop="remarks" label="备注信息" />
          <el-table-column label="操作" width="160" align="center" class-name="small-padding fixed-width">
            <template #default="{ row }">
              <div class="table_btn">
                <el-button size="small" :icon="EditPen" @click="openDictItemDialog(row)">编辑</el-button>
                <el-button size="small" :icon="Delete" @click="deldictItem(row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <template #footer>
          <pagination
            v-show="dialogPage.total > 0"
            v-model:page="dialogPage.currentPage"
            v-model:limit="dialogPage.pageSize"
            :total="dialogPage.total"
            @pagination="getDictItem"
          />
        </template>
      </el-dialog>

      <el-dialog v-model="dictItemCreate" :title="dictItemTitle" width="50%" :before-close="dictItemClose">
        <el-form :model="dictItem" ref="dictItemRef" :rules="dictItemRules" label-width="80px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="类型" prop="dictType">
                <el-input v-model="dictItem.dictType" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据值" prop="value">
                <el-input v-model="dictItem.value" placeholder="请输入数据值" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="标签名" prop="label">
                <el-input v-model="dictItem.label" placeholder="请输入标签名" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="描述" prop="description">
                <el-input v-model="dictItem.description" placeholder="请输入描述" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="排序" prop="sortOrder">
                <el-input-number v-model="dictItem.sortOrder" controls-position="right" :min="0" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注信息" prop="remarks">
                <el-input v-model="dictItem.remarks" placeholder="请输入备注信息" clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-row class="btn_center">
            <el-button v-if="dictItemTitle === '新增'" type="primary" @click="addDictItem">保存</el-button>
            <el-button v-if="dictItemTitle === '编辑'" type="primary" @click="saveDictItem">修改</el-button>
            <el-button @click="dictItemCreate = false">取消</el-button>
          </el-row>
        </template>
      </el-dialog>
    </div>
  </basic-container>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { Search, Refresh, EditPen, Plus, Delete, Menu } from "@element-plus/icons-vue";

import { deepClone } from "@/utils/util";
import { ITablePage } from "@//const/interface_type";
import {
  getDictList,
  addDictObj,
  putDictObj,
  delDictObj,
  getDictItemList,
  createDictItem,
  updateDictItem,
  deleteDictItem
} from "@/api/admin";

interface ISearchList {
  dictType: string;
  systemFlag: string;
}

const searchList = ref<ISearchList>({
  dictType: "",
  systemFlag: ""
}); // 搜索数据
const dictType = ref([
  {
    label: "系统类",
    value: "1"
  },
  {
    label: "业务类",
    value: "0"
  }
]); // 数据权限
const tableData = ref([]); // 表格数据
const tablePage = ref<ITablePage>({
  currentPage: 1,
  pageSize: 10,
  total: 0
});
const tableLoading = ref<boolean>(false); // 表格loading

const dictVisible = ref<boolean>(false); // 新增/修改/查看 弹窗是否展示
const title = ref<string>(""); // 新增/修改/查看 弹窗标题
const dictForm = ref({
  dictType: "",
  description: "",
  systemFlag: "",
  remarks: "",
  createTime: ""
});
const dictRef = ref<FormInstance>();
const roleFormDisabled = ref<boolean>(false);
const dictRules = ref<FormRules>({
  dictType: [{ required: true, message: "请输入字典名称", trigger: "blur" }],
  description: [{ required: true, message: "请输入字典描述", trigger: "blur" }],
  systemFlag: [{ required: true, message: "请选择字典类型", trigger: "change" }]
});

const dictItemVisible = ref<boolean>(false); // 字典项弹窗是否展示
const checkDictId = ref("");
const checkDictType = ref("");
const dialogTableData = ref([]);
const dialogTableLoading = ref(false);
const dialogPage = ref<ITablePage>({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

const dictItemCreate = ref<boolean>(false);
const dictItemTitle = ref("");
const dictItem = ref({
  dictType: "",
  dictId: "",
  value: "",
  label: "",
  description: "",
  sortOrder: 1,
  remarks: ""
});
const dictItemRef = ref<FormInstance>();
const dictItemRules = ref<FormRules>({
  value: [{ required: true, message: "请输入数据值", trigger: "blur" }],
  label: [{ required: true, message: "请输入标签名", trigger: "blur" }],
  description: [{ required: true, message: "请输入字典描述", trigger: "blur" }],
  sortOrder: [{ required: true, message: "请输入排序", trigger: "blur" }]
});

// 搜索/获取列表
const getList = () => {
  tableLoading.value = true;
  const payload = {
    current: tablePage.value.currentPage,
    size: tablePage.value.pageSize,
    descs: "create_time",
    ...searchList.value
  };
  getDictList(payload).then((res: any) => {
    if (res.code === 0) {
      tableData.value = res.data.records;
      tablePage.value.total = res.data.total;
      tableLoading.value = false;
    }
  });
};

getList();

// 清空搜索条件
const clearSearch = () => {
  searchList.value = {
    dictType: "",
    systemFlag: ""
  };
  getList();
};

// 添加/查看/编辑 列表数据
const addOrUpdateHandle = (row: any) => {
  if (row) {
    title.value = "修改";
    dictForm.value = deepClone(row);
  } else {
    title.value = "添加";
    dictForm.value = {
      dictType: "",
      description: "",
      systemFlag: "",
      remarks: "",
      createTime: ""
    };
  }
  dictVisible.value = true;
};

// 保存添加
const addDict = () => {
  dictRef.value?.validate((valid: boolean) => {
    if (valid) {
      addDictObj(dictForm.value).then((res: any) => {
        if (res.code === 0) {
          ElMessage.success("创建成功");
          clearDialogData();
          dictVisible.value = false;
          getList();
        }
      });
    } else {
      return false;
    }
  });
};

// 保存编辑
const saveDict = () => {
  dictRef.value?.validate((valid: boolean) => {
    if (valid) {
      putDictObj(dictForm.value).then((res: any) => {
        if (res.code === 0) {
          ElMessage.success("修改成功");
          clearDialogData();
          dictVisible.value = false;
          getList();
        }
      });
    } else {
      return false;
    }
  });
};
// 删除数据
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`是否确认删除名称为 “${row.dictType}” 的数据项?`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    delDictObj(row.id).then(() => {
      ElMessage({
        type: "success",
        message: `删除 “${row.dictType}” 成功`
      });
      getList();
    });
  });
};

// 添加/查看/编辑 弹窗关闭前
const dictClose = (done: () => void) => {
  clearDialogData();
  done();
};

// 清空弹窗数据
const clearDialogData = () => {
  dictForm.value = {
    dictType: "",
    description: "",
    systemFlag: "",
    remarks: "",
    createTime: ""
  };
  roleFormDisabled.value = false;
  dictRef.value?.clearValidate();
};

// 打开字典项弹窗
const openDictItem = (row: any) => {
  checkDictId.value = row.id;
  checkDictType.value = row.dictType;
  getDictItem();
};

// 获取弹窗字典项列表
const getDictItem = () => {
  const data = {
    current: dialogPage.value.currentPage,
    size: dialogPage.value.pageSize,
    dictId: checkDictId.value
  };
  getDictItemList(data).then((res: any) => {
    if (res.code === 0) {
      dialogTableData.value = res.data.records;
      dialogPage.value.total = res.data.total;
      dictItemVisible.value = true;
    }
  });
};

// 打开字典项详情修改/新增弹窗
const openDictItemDialog = (row: any) => {
  // console.log(checkDictId.value);
  dictItem.value.dictType = checkDictType.value;
  dictItem.value.dictId = checkDictId.value;
  if (row) {
    dictItemTitle.value = "编辑";
    dictItem.value = deepClone(row);
  } else {
    dictItemTitle.value = "新增";
  }
  dictItemCreate.value = true;
};

// 提交新增字典项
const addDictItem = () => {
  dictItemRef.value?.validate((valid: boolean) => {
    if (valid) {
      createDictItem(dictItem.value).then(() => {
        ElMessage.success("添加成功");
        clearItemDialog();
      });
    } else {
      return false;
    }
  });
};

// 提交修改字典项
const saveDictItem = () => {
  dictItemRef.value?.validate((valid: boolean) => {
    if (valid) {
      updateDictItem(dictItem.value).then(() => {
        ElMessage.success("修改成功");
        clearItemDialog();
      });
    } else {
      return false;
    }
  });
};

// 提交删除字典项
const deldictItem = (row: any) => {
  ElMessageBox.confirm(`是否确认删除名称为 “${row.label}” 的数据项?`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteDictItem(row.id).then(() => {
      ElMessage({
        type: "success",
        message: `删除 “${row.label}” 成功`
      });
      getDictItem();
    });
  });
};

//
const dictItemClose = (done: () => void) => {
  clearItemDialog();
  done();
};

const clearItemDialog = () => {
  dictItem.value = {
    dictType: "",
    dictId: "",
    value: "",
    label: "",
    description: "",
    sortOrder: 1,
    remarks: ""
  };
  dictItemRef.value?.clearValidate;
  dictItemCreate.value = false;
  getDictItem();
};
</script>

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