<template>
  <div>

    <MOSTY.PageTree :pageTitle="'系统配置'" :isShowLeftTree="false">
      <template #serach>
        <el-divider />
        <MOSTY.Search :searchArr="searchArr" @submit="handleFilter" />
        <el-divider />
        <div class="btnBox">
          <el-button type="primary" @click="addConfig">
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>新增</span>
          </el-button>
        </div>
      </template>
      <template #table>
        <div class="eltab9">
          <MOSTY.Table :table-columns="tableColumn" :tableData="tableData" :tableloading="tableloading"
            :isSelect="false" :isSort="false" @SortChange="SortChange" style="width: 100%;" :actionsW='260'>
            <template #xtCjsj="{ row }">
              {{ $filters.dateFilter(row.xtCjsj) }}
            </template>
            <template #actions="{ row }">
              <el-button @click="updateDict(row)" size="small">修改</el-button>
              <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
                @confirm="delConfig(row)">
                <template #reference>
                  <el-button type="danger" size="small">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </MOSTY.Table>
          <div class="fenye">
            <MOSTY.Pages :pageConfiger="listQuery" @changeNo="handleCurrentChange" @changeSize="handleSizeChange">
            </MOSTY.Pages>
          </div>

        </div>
      </template>
    </MOSTY.PageTree>

    <div v-if="dialogFormVisible" class="dialog">
      <MOSTY.FromPage :title="isEdit ? '修改' : '新增'" @closeDialog="closeDialog">
        <template #content>
          <el-form ref="formRef" class="mosty-from-wrap" :inline="true" label-position="top" :model="dialogForm"
            :rules="rules">
            <el-form-item class="one" label="配置名称" prop="pzmc" label-width="140px">
              <el-input v-model="dialogForm.pzmc" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item class="one" label="配置键" prop="pzj" label-width="140px">
              <el-input v-model="dialogForm.pzj" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item class="one" label="配置值" prop="pzz" required label-width="140px">
              <el-input v-model="dialogForm.pzz" autocomplete="off"></el-input>
            </el-form-item>
            <!-- <el-form-item class="one" prop="xtZxbz" label="状态">
          <el-select
            style="width: 100%"
            v-model="dialogForm.xtZxbz"
            placeholder="请选择配置状态"
          >
            <el-option label="正常" :value="0"></el-option>
            <el-option label="注销" :value="1"></el-option>
          </el-select>
        </el-form-item> -->
            <el-form-item class="one" label="备注" label-width="140px">
              <el-input v-model="dialogForm.bz" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
                show-word-limit></el-input>
            </el-form-item>
          </el-form>
        </template>
        <template #footer>

          <!-- 修改 -->
          <el-button v-if="isEdit" type="primary" size="small" @click="onSave" :loading="buttonLoading">保存</el-button>
          <!-- 新增 -->
          <el-button v-else type="primary" size="small" @click="onAdd" :loading="buttonLoading">保存</el-button>
          <el-button size="small" @click="closeDialog">关闭</el-button>
        </template>
      </MOSTY.FromPage>


    </div>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import * as MOSTY from "@/components/MyComponents/index";
import { ref, reactive, onMounted, onUnmounted, getCurrentInstance } from "vue";
import {
  getSysConfigList,
  addSysConfig,
  updateSysConfig,
  deleteSysConfig
} from "@/api/user-manage";
const { proxy } = getCurrentInstance();
const keyCount = ref(0); //tabel组件刷新值
const searchArr = reactive([
  {
    showType: "input",
    label: '配置名称:',
    prop: "configName",
    width: '250px',
    placeholder: '请输入配置名称'
  },
  {
    showType: "input",
    label: '配置键:',
    prop: "configKey",
    width: '250px',
    placeholder: '请输入配置键'
  },
]);
const tableColumn = ref([
  {
    title: "配置名称",
    prop: "pzmc",
  },
  {
    title: "配置键",
    prop: "pzj",
  },
  {
    title: "配置值",
    prop: "pzz",
  },
  {
    title: "修改人姓名",
    prop: "xtZhxgrxm",
  },
  {
    title: "备注",
    prop: "bz",
  },
  {
    title: "采集时间",
    prop: "xtCjsj",
    slot: true
  },

  {
    title: "操作",
    prop: "actions",
    fixed: 'right',
    slot: true
  }
])
const tableHeight = ref(); // 表格高度
const formRef = ref(null);
const rules = ref({
  pzmc: [{ required: true, message: "请填写配置名称", trigger: "blur" }],
  pzj: [{ required: true, message: "请填写配置键", trigger: "blur" }],
  pzz: [{ required: true, message: "请填写配置值", trigger: "blur" }],
  xtZxbz: [{ required: true, message: "请选择配置状态", trigger: "blur" }],
});
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 10,
  total: 0,
  dictName: "",
  dictCode: "",
  xtZxbz: ""
});
const isEdit = ref(true);
const dialogForm = ref({});
const buttonLoading = ref(false);
// 数据相关
const tableData = ref([]);
const dialogFormVisible = ref(false);
// 获取数据的方法
const getListData = async () => {
  const params = listQuery.value;
  params.size = listQuery.value.pageSize
  params.current = listQuery.value.pageCurrent
  const res = await getSysConfigList(params);
  tableData.value = res?.records;
  listQuery.value.total = Number(res.total);
};
const reset = () => {
  listQuery.value = {
    pageCurrent: 1,
    pageSize: 10,
    total: 0,
    configName: "",
    configKey: ""
  };
  getListData();
};
const handleFilter = (obj) => {
  if (obj) {
    listQuery.value.configName = obj.configName ? obj.configName : null
    listQuery.value.configKey = obj.configKey ? obj.configKey : null
  }

  listQuery.value.pageCurrent = 1;
  getListData();
};
getListData();

// 分页相关
/**
 * size 改变触发
 */
const handleSizeChange = (currentSize) => {
  listQuery.value.pageSize = currentSize;
  getListData();
};

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

/**修改字典 */
const updateDict = (row) => {
  isEdit.value = true;
  dialogForm.value = { ...row };
  dialogFormVisible.value = true;
};

const addConfig = (row) => {
  isEdit.value = false;
  dialogForm.value = {};
  dialogFormVisible.value = true;
};
const onSave = () => {
  formRef.value.validate((valid) => {
    if (!valid) {
      ElMessage.error("请完成必填项！");
      return false;
    }
    buttonLoading.value = true;
    updateSysConfig({
      ...dialogForm.value
    })
      .then((res) => {
        dialogFormVisible.value = false;
        ElMessage.success("修改成功");
        handleFilter();
      })
      .finally(() => {
        buttonLoading.value = false;
      });
  });
};

const onAdd = () => {
  formRef.value.validate((valid) => {
    if (!valid) {
      ElMessage.error("请完成必填项！");
      return false;
    }
    buttonLoading.value = true;
    addSysConfig({
      ...dialogForm.value
    })
      .then((res) => {
        dialogFormVisible.value = false;
        ElMessage.success("新增成功");
        handleFilter();
      })
      .finally(() => {
        buttonLoading.value = false;
      });
  });
};

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

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

};

onMounted(() => {

  proxy.mittBus.on("mittFn", (data) => {
    keyCount.value = data;
  });
});
onUnmounted(() => {
  proxy.mittBus.off("mittFn");
});
</script>

<style lang="scss" scoped>
@import "~@/assets/css/layout.scss";
@import "~@/assets/css/element-plus.scss";



.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;
  }
}

.btnBox {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}
</style>
