<template>
  <div class="user-manage-container">
    <div class="titleBox">
      <div class="title">字典数据</div>
      <div class="btnBox">
        <el-button type="primary" @click="addItemDict()">
          <el-icon><CirclePlus /></el-icon>
          <span>新增</span>
        </el-button>
        <el-button @click="batchDelete" :disabled="ids.length == 0" typeof="danger">
          <el-icon style="vertical-align: middle">
            <Delete />
          </el-icon>
          <span style="vertical-align: middle">批量删除</span>
        </el-button>
        <el-button type="primary" @click="closeItemDict()"> 关闭</el-button>
      </div>
    </div>
    <div ref="searchBox">
      <el-card class="table-header-wrap">
        <el-form :model="listQuery" :inline="true">
          <el-form-item label="字典名称">
            <el-input
              placeholder="请输入字典名称"
              v-model="listQuery.dictName"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="handleFilter"> 查询 </el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="resetHandleFilter">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <el-card :style="{ height: tableHeight + 'px' }">
      <el-table
        :data="tableData"
        border
        row-key="id"
        @selection-change="handleSelectionChange"
        :tree-props="{ children: 'itemList', hasChildren: true }"
        :height="h"
      >
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column prop="dm" align="center" label="字典代码">
        </el-table-column>
        <el-table-column prop="zdmc" label="字典名称"> </el-table-column>
        <el-table-column prop="py" label="字典拼音" align="center">
        </el-table-column>
        <el-table-column prop="px" label="字典排序" align="center" sortable>
        </el-table-column>
        <el-table-column prop="bz" label="备注"> </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="220">
          <template #default="{ row }">
            <el-button type="primary" @click="update(row)" size="small"
              >编辑</el-button
            >
            <el-button
              type="primary"
              v-if="zdlx === 2"
              @click="addItemDict(row)"
              size="small"
              >添加下级</el-button
            >
            <el-popconfirm
              confirm-button-text="是"
              cancel-button-text="否"
              icon-color="red"
              title="确定要删除?"
              @confirm="delDictItem(row)"
            >
              <template #reference>
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div class="fenye" :style="{ top: tableHeight + 'px' }" v-if="type == 1">
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageCurrent"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      custom-class="way"
      v-model="dialogFormVisible"
      @closed="closeDialog"
      :title="isEdit ? '修改' : '新增'"
    >
      <el-form
        v-if="dialogFormVisible"
        ref="formDom"
        :rules="rules"
        :model="dialogForm"
      >
        <el-form-item label="字典名称" prop="zdmc" label-width="140px">
          <el-input
            v-model="dialogForm.zdmc"
            show-word-limit
            maxlength="50"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="字典拼音" label-width="140px">
          <el-input
            v-model="dialogForm.py"
            show-word-limit
            maxlength="50"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="字典代码" prop="dm" label-width="140px">
          <el-input
            v-model="dialogForm.dm"
            show-word-limit
            maxlength="50"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="px" label-width="140px">
          <el-input-number
            v-model="dialogForm.px"
            class="mx-4"
            :min="1"
            :max="100"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="备注" label-width="140px">
          <el-input
            v-model="dialogForm.bz"
            :autosize="{ minRows: 2, maxRows: 4 }"
            show-word-limit
            maxlength="200"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" v-if="isEdit" @click="onSave"
            >保存</el-button
          >
          <el-button type="primary" v-else @click="onAdd">新增</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { qcckPost, qcckGet,qcckPut,qcckDelete } from "@/api/qcckApi.js";
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import { updateSysDictItem, getSysDictByCode, getSysDictByCodeList, deleteSysDictItem, addSysDictItem} from "@/api/sysDict";
import { useRouter, useRoute } from "vue-router";
const formDom = ref(null);
const rules = ref({
  zdmc: [{ required: true, message: "请输入字典名称" }],
  py: [{ required: true, pattern: /^[a-zA-Z]+$/, message: "请输入字典拼音" }],
  dm: [{ required: true, message: "请输入字典代码" }],
  px: [{ required: true, message: "请输入字典排序" }]
});
const { proxy } = getCurrentInstance();
const type = ref("1");
const router = useRouter();
const route = useRoute();
//查询参数
const currentRow = ref({});
const listQuery = ref({
  dictName: "",
  dictCode: "",
  xtZxbz: ""
});
const total = ref(0);
const pageSize = ref(20);
const pageCurrent = ref(1);
const ids = ref([]);
const topParentId = ref("");
const id = ref("");
const zdlx = ref();

const isEdit = ref(true);
const dialogForm = ref({});
// 数据相关
const tableData = ref([]);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const tableHeight = ref();
const searchBox = ref(null);
const h = ref();
// 表格高度计算
const tabHeightFn = () => {
  tableHeight.value = window.innerHeight - searchBox.value.offsetHeight - 280;
  h.value = window.innerHeight - searchBox.value.offsetHeight - 300;
  window.onresize = function () { tabHeightFn();  };
};
onMounted(() => {
  type.value = route.query.zdlx;
  tabHeightFn();
  getListData();
});

//批量数据
const handleSelectionChange = (val) => {
  ids.value = val.map((v) => { return v.id; });
};

//批量删除数据
const batchDelete = () => {
  proxy.$confirm("确定要删除", "警告", { type: "warning" }).then(() => {
    qcckPost(ids.value,'/mosty-base/sys-dict-item/deleteSysDictItemBatch').then(res=>{
      proxy.$message({ message: "删除成功",type: "success"});
      getListData();
    })
  }).catch(() => {
    proxy.$message.info("已取消");
  });
};
// size 改变触发
const handleSizeChange = (currentSize) => {
  pageSize.value = currentSize;
  getListData();
};

// 页码改变触发
const handleCurrentChange = (currentPage) => {
  pageCurrent.value = currentPage;
  getListData();
};

// 获取数据的方法
const getListData = async () => {
  const params = { dictCode: route.query.zdbh, zdmc: listQuery.value.dictName };
  if (route.query.zdlx == 1) {
    //列表
    params.size = pageSize.value;
    params.current = pageCurrent.value;
    getlist(params);
  } else {
    getree(params);
  }
};

const getlist = async (params) => {
  let res = await getSysDictByCodeList(params);
  topParentId.value = route.query.Pid;
  tableData.value = res ? res.records : [];
  total.value = Number(res.total);
};
const getree = async (params) => {
  let res = await getSysDictByCode(params);
  topParentId.value = res.id;
  zdlx.value = res.zdlx;
  tableData.value = res?.itemList;
};

const handleFilter = () => {
  listQuery.value.current = 1;
  getListData();
};
const resetHandleFilter = () => {
  listQuery.value.dictName = "";
  listQuery.value.current = 1;
  getListData();
};
/**修改字典 */
const update = (row) => {
  isEdit.value = true;
  dialogForm.value = { ...row };
  dialogFormVisible.value = true;
};
function isNull(data) {
  if (!data) return true;
  if (JSON.stringify(data) === "{}") return true;
  if (JSON.stringify(data) === "[]") return true;
  return false;
}
const addItemDict = (row) => {
  id.value = isNull(row) ? topParentId.value : row.id;
  isEdit.value = false;
  dialogForm.value = {};
  dialogFormVisible.value = true;
};
// 返回字典列表页面
const closeItemDict = () => {
  router.push("/dict/index");
};
const onSave = () => {
  formDom.value.validate((valid) => {
    if (!valid) {
      return false;
    }
    updateSysDictItem({
      bz: dialogForm.value.bz,
      id: dialogForm.value.id,
      dm: dialogForm.value.dm,
      px: dialogForm.value.px,
      py: dialogForm.value.py,
      zdbh: dialogForm.value.zdbh,
      zdmc: dialogForm.value.zdmc
    }).then((res) => {
      dialogFormVisible.value = false;
      ElMessage.success("修改成功");
      handleFilter();
    });
  });
};

const onAdd = () => {
  formDom.value.validate((valid) => {
    if (!valid) {
      return false;
    }
    addSysDictItem({
      parentId: id.value,
      bz: dialogForm.value.bz,
      dm: dialogForm.value.dm,
      px: dialogForm.value.px,
      py: dialogForm.value.py,
      zdbh: dialogForm.value.zdbh,
      zdmc: dialogForm.value.zdmc
    }).then((res) => {
      dialogFormVisible.value = false;
      ElMessage.success("新增成功");
      handleFilter();
    });
  });
};

const delDictItem = (row) => {
  deleteSysDictItem({ id: Number(row.id) }).then((res) => {
    ElMessage.success("删除成功");
    handleFilter();
  });
};

const closeDialog = () => {
  dialogForm.value = {};
  dialogFormVisible.value = false;
};

const toGoPage = (row) => {
  router.push("/user/role?zdbh=" + row.zdbh);
};
</script>

<style lang="scss" scoped>
.user-manage-container {
  .table-header-wrap {
    margin-bottom: 22px;
  }

  ::v-deep .avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
  }

  ::v-deep .el-tag {
    margin-right: 6px;
  }

  .pagination {
    margin-top: 20px;
  }
}
::v-deep .el-card__body {
  background-color: rgba(0, 0, 0, 0);
}
::v-deep .el-card {
  --el-card-border-color: #143578;
  --el-card-border-radius: 4px;
  --el-card-padding: 20px;
  --el-card-bg-color: #17096130;
  position: relative;
}
::v-deep .el-table--fit {
  position: absolute;
  top: 14px;
  right: 14px;
  left: 14px;

  // overflow-y: scroll;
  width: calc(100% - 28px);
}
::v-deep .el-dialog {
  --el-dialog-bg-color: #001238;
}
</style>
