<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="key值" prop="keyword">
              <el-input v-model="queryParams.keyword" placeholder="请输入key" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-if="false" type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:redis:add']"> 新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:amnt:refreshCache']" type="danger" plain icon="Refresh" @click="handleRefreshCache"
              >刷新累计风保缓存
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="redisList" @selection-change="handleSelectionChange">
        <el-table-column label="类型" align="center" prop="dataType" />
        <el-table-column label="缓存键" align="center" prop="redisKey" show-overflow-tooltip />
        <el-table-column label="过期时间" align="center" prop="expire" />
        <el-table-column label="元素总数" align="center" prop="elCount" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip v-if="false" content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:routeConfig:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:routeConfig:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 后续开发redis数据的新增和修改在这里 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1000" append-to-body>
      <el-form ref="routeConfigFormRef" :model="form" :rules="rules">
        <el-row>
          <el-form-item label="接口编码" prop="businessCode" label-width="120">
            <el-input v-model="form.businessCode" placeholder="请输入接口编码" />
          </el-form-item>
          <el-form-item label="所属系统" prop="ownSystem" label-width="100">
            <el-select v-model="form.ownSystem" placeholder="请输入所属系统" style="width: 200px" clearable>
              <el-option v-for="dict in route_system" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="转发系统" prop="postSystem" label-width="100">
            <el-select v-model="form.postSystem" placeholder="请输入转发系统" style="width: 200px" clearable>
              <el-option v-for="dict in route_system" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="所属系统描述" prop="ownSystemDesc" label-width="120">
            <el-input v-model="form.ownSystemDesc" placeholder="请输入所属系统描述" />
          </el-form-item>
          <el-form-item label="接口提供系统" prop="providesSystem" label-width="100">
            <el-select v-model="form.providesSystem" placeholder="请输入接口提供系统" style="width: 200px" clearable>
              <el-option v-for="dict in route_system" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="请求方式" prop="requestType" label-width="120">
            <el-input v-model="form.requestType" placeholder="请输入请求方式" />
          </el-form-item>
          <el-form-item label="返回格式" prop="responseFormat" label-width="100">
            <el-input v-model="form.responseFormat" placeholder="请输入返回格式" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="请求类" prop="requestClass" label-width="120">
            <el-input v-model="form.requestClass" placeholder="请输入请求类" />
          </el-form-item>
          <el-form-item label="返回类" prop="responseClass" label-width="100">
            <el-input v-model="form.responseClass" placeholder="请输入返回类" />
          </el-form-item>
        </el-row>
        <el-form-item label="请求路径" prop="requestRoute" label-width="120">
          <el-input v-model="form.requestRoute" placeholder="请输入请求路径" />
        </el-form-item>
        <el-form-item label="请求报文list节点" prop="requestJsonArray" label-width="120">
          <el-input
            v-model="form.requestJsonArray"
            type="textarea"
            placeholder='请输入内容,例如：{"1000000293-1": "InputData.LLClaimDetails.LLClaimDetail","1000000293-2": "InputData.ContList.Cont"}'
          />
        </el-form-item>
        <el-form-item label="接口名称" prop="interfaceName" label-width="120">
          <el-input v-model="form.interfaceName" placeholder="请输入接口名称" />
        </el-form-item>
        <el-form-item label="功能描述" prop="featureDescription" label-width="120">
          <el-input v-model="form.featureDescription" type="textarea" placeholder="请输入功能描述" />
        </el-form-item>
        <el-form-item label="请求报文体标签字段" prop="requestBodyTitle">
          <el-input v-model="form.requestBodyTitle" placeholder="请输入请求报文体标签字段" />
        </el-form-item>
        <el-form-item label="响应报文体标签字段" prop="responseBodyTitle">
          <el-input v-model="form.responseBodyTitle" placeholder="请输入响应报文体标签字段" />
        </el-form-item>
        <el-form-item label="请求报文编码" prop="requestEncoder" label-width="120">
          <el-input v-model="form.requestEncoder" placeholder="请输入请求报文编码" />
        </el-form-item>
        <el-form-item label="接口拦截器配置" prop="filterClass" label-width="120">
          <el-input v-model="form.filterClass" placeholder="请输入接口拦截器配置" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="RouteConfig" lang="ts">
import { getRouteConfig, addRouteConfig, updateRouteConfig } from '@/api/system/routeConfig';
import { getRedisList, removeRedisList, refreshCache } from '@/api/system/redisManage';
import { RouteConfigVO } from '@/api/system/routeConfig/types';
import { CacheRedisQuery, SysRedis, CacheRedis } from '@/api/system/redisManage/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { route_config_status, route_system } = toRefs<any>(proxy?.useDict('route_config_status', 'route_system'));

const redisList = ref<SysRedis[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const routeConfigFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: SysRedis = {
  dataType: undefined,
  oldRedisKey: undefined,
  redisKey: undefined,
  redisValue: undefined,
  expire: undefined,
  elCount: undefined
};
const data = reactive<PageData<SysRedis, CacheRedisQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    keyword: undefined
  },
  rules: {
    businessCode: [{ required: true, message: '功能类型不能为空', trigger: 'blur' }],
    ownSystem: [{ required: true, message: '所属系统不能为空', trigger: 'blur' }],
    ownSystemDesc: [{ required: true, message: '所属系统描述不能为空', trigger: 'blur' }],
    providesSystem: [{ required: true, message: '接口提供系统不能为空', trigger: 'blur' }],
    requestType: [{ required: true, message: '请求方式不能为空', trigger: 'blur' }],
    responseFormat: [{ required: true, message: '返回格式不能为空', trigger: 'blur' }],
    requestRoute: [{ required: true, message: '请求路径不能为空', trigger: 'blur' }],
    requestEncoder: [{ required: true, message: '请求报文编码不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询redis数据列表 */
const getList = async () => {
  loading.value = true;
  const res = await getRedisList(queryParams.value);
  redisList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  routeConfigFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: RouteConfigVO[]) => {
  ids.value = selection.map((item) => item.configId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '新增redis值';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: RouteConfigVO) => {
  reset();
  const _configId = row?.configId || ids.value[0];
  const res = await getRouteConfig(_configId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改redis数据';
};

/** 提交按钮 */
const submitForm = () => {
  routeConfigFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.configId) {
        await updateRouteConfig(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addRouteConfig(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: SysRedis) => {
  const _redisKey = row?.redisKey;
  await proxy?.$modal.confirm('是否确认删除键值为"' + _redisKey + '"的数据项？').finally(() => (loading.value = false));
  await removeRedisList(row);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/routeConfig/export',
    {
      ...queryParams.value
    },
    `routeConfig_${new Date().getTime()}.xlsx`
  );
};

/** 刷新缓存按钮操作 */
const handleRefreshCache = async () => {
  await refreshCache();
  proxy?.$modal.msgSuccess('刷新成功');
};

onMounted(() => {
  getList();
});
</script>
