<template>
  <div>
    <MOSTY.PageTree :pageTitle="'字典数据'" :isShowLeftTree="false">
      <template #serach>
        <div ref="searchBox">
          <el-card class="table-header-wrap" v-if="route.params.zdlx == 1">
            <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>

        <div class="btnBox">
          <el-button type="primary" @click="addItemDict()">
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>新增</span>
          </el-button>
          <el-button type="primary" @click="closeItemDict()"> 关闭</el-button>
        </div>
      </template>
      <template #table>
        <el-card :style="{ height: tableHeight + 'px' }">
          <el-table stripe :data="tableData" border row-key="id"
            :tree-props="{ children: 'itemList', hasChildren: true }" style="width: 100%" height="100%">
            <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>
      </template>
    </MOSTY.PageTree>



    <el-dialog custom-class="way" v-model="dialogFormVisible" :title="isEdit ? '修改' : '新增'" :before-close="closeDialog">
      <el-form v-if="dialogFormVisible" ref="formDom" :rules="rules" :model="dialogForm">
        <el-form-item label="字典名称" prop="zdmc" label-width="140px" style="width: 90%;">
          <el-input v-model="dialogForm.zdmc" show-word-limit maxlength="50" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="字典拼音" prop="py" label-width="140px" style="width: 90%;">
          <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" style="width: 90%;">
          <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" style="width: 90%;">
          <el-input-number v-model="dialogForm.px" class="mx-4" :min="1" :max="100" controls-position="right"
            style="width: 100%;" />
        </el-form-item>
        <el-form-item label="备注" label-width="140px" style="width: 90%;">
          <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 type="primary" v-if="isEdit" @click="onSave">保存</el-button>
          <el-button type="primary" v-else @click="onAdd">新增</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import * as MOSTY from "@/components/MyComponents/index";
import { ref, onMounted, getCurrentInstance } from "vue";
import { updateSysDictItem, getSysDictByCode, getDictTree, deleteSysDictItem, addSysDictItem } from "@/api/sysDict";
import { useRoute } from "vue-router";
const { proxy } = getCurrentInstance();
const formDom = ref(null);
const rules = ref({
  zdmc: [{ required: true, message: "请输入字典名称" }],
  py: [{ required: true, message: "请输入字典拼音" }],
  dm: [{ required: true, message: "请输入字典代码" }],
  px: [{ required: true, message: "请输入字典排序" }]
});
const props = defineProps({
  params: Object,//参数
})
const emits = defineEmits(["cancel"])
const route = useRoute();
//查询参数
const total = ref(0);
const listQuery = ref({
  dictName: "",
  dictCode: "",
  xtZxbz: ""
});
const topParentId = ref("");
const id = ref("");
const zdlx = ref();

const isEdit = ref(true);
const dialogForm = ref({});
// 数据相关
const tableData = ref([]);
const dialogFormVisible = ref(false);
// 获取数据的方法
const getListData = async () => {
  if (props.params.zdlx == 1) {
    const params = {
      dictCode: props.params.zdbh,
      zdmc: listQuery.value.dictName
    };
    const res = await getSysDictByCode(params);
    topParentId.value = res.id;
    zdlx.value = res.zdlx;
    tableData.value = res?.itemList;
    total.value = Number(res.total);
  } else {
    const params = {
      zdbh: props.params.zdbh
    };
    const res = await getDictTree(params);
    topParentId.value = res.id;
    zdlx.value = res.zdlx;
    tableData.value = res?.itemList;
    total.value = Number(res.total);
  }
};
const tableHeight = ref();
const searchBox = ref(null);
const h = ref();
// 表格高度计算
const tabHeightFn = () => {
  tableHeight.value = window.innerHeight - searchBox.value.offsetHeight - 250;
  h.value = window.innerHeight - searchBox.value.offsetHeight - 150 - 78;
};
onMounted(() => {
  tabHeightFn();
  window.onresize = function () {
    tabHeightFn();
  };
  getListData();
});
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 = () => {
  // let arr = store.getters.tagsViewList;
  // for (let i = 0; i < arr.length; i++) {
  //   const e = arr[i];
  //   if (e.path == '/dict/detail') {
  //     arr.splice(i, 1);
  //   }
  // }
  // router.push("/systemConfig/dict");
  emits("cancel")
};
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(() => {
      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(() => {
      dialogFormVisible.value = false;
      ElMessage.success("新增成功");
      handleFilter();
    });
  });
};

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

const closeDialog = () => {
  proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
    .then(() => {
      dialogForm.value = {};
      dialogFormVisible.value = false;
    })
    .catch(() => {
      // catch error
    })
};
</script>

<style lang="scss" scoped>
.btnBox {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}

.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: 0;
  left: 0;
  // height: calc(100% - 28px);
  // overflow-y: scroll;
  // width: calc(100% - 28px);
}

::v-deep .el-dialog {
  --el-dialog-bg-color: #001238;
}

::v-deep .el-dialog__body {
  height: 420px !important;

  .el-form {
    width: 100%;
    // display: flex;
    flex-direction: column;
  }
}
</style>
