<template>
  <el-steps
    v-if="!isSpecial"
    style="max-width: 2000px; margin-top: 5px"
    :active="4"
    simple
    align-center
  >
    <el-step title="查看数据源" />
    <el-step title="输入模拟数据作为入参" />
    <el-step title="执行代码" />
    <el-step title="下方查看结果" />
  </el-steps>
  <el-form ref="queryForm" class="query-form" :model="queryParams">
    <el-row :gutter="20">
      <el-col :span="16">
        <div class="code-editor">
          <java-code-edit
            v-if="codeType !== 'JAVA_SCRIPT'"
            v-model="codeData"
            :editor-placeholder="'请输入Java代码'"
            :editor-height="500"
            :tab-size="2"
          />
          <js-code-edit
            v-else
            v-model="codeData"
            :editor-placeholder="'请输入JavaScript代码'"
            :editor-height="500"
            :tab-size="2"
          />
        </div>
      </el-col>
      <el-col :span="8">
        <el-row>
          <el-col :span="12" v-for="(item, index) in mappings">
            <el-form-item :label="item.mappingValue + ':'" prop="mappingKey">
              <el-input
                placeholder="请输入查询参数"
                v-model="mappings[index].userInput"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item
          label="查询结果:"
          prop="operParam"
          class="json-viewer-father"
          v-if="isSpecial"
        >
          <span
            class="expand"
            @click="
              isExpandVisible = true;
              expandData = mockData;
            "
            v-if="isExpandBtnVisible"
            >展开</span
          >
          <div class="json-viewer">
            <json-viewer
              :value="mockData"
              :expand-depth="100"
              style="width: 100%; height: 300px"
            ></json-viewer>
          </div>
        </el-form-item>
        <el-form-item prop="mockData" v-if="!isSpecial">
          <el-input
            v-model="queryParams.mockData"
            placeholder="请输入模拟数据源"
            :rows="20"
            type="textarea"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-button type="primary" @click="handleSave">保存代码</el-button>
        <el-button type="primary" @click="handleExecute">模拟执行</el-button>
        <el-button type="primary" @click="handleSourceData" v-if="!isSpecial"
          >查看数据源</el-button
        >
        <el-button type="primary" @click="handleSourceData" v-if="isSpecial"
          >查询数据源</el-button
        >
      </el-col>
      <el-col class="preview-bottom">
        <el-row>
          <el-col :span="16">
            输出：
            <span
              style="color: #49c4ff; cursor: pointer"
              @click="
                isExpandVisible = true;
                expandData = resPreviewData;
              "
              >展开</span
            >
            <json-viewer
              class="bottom-printf"
              :value="resPreviewData"
              :expand-depth="105"
              copyable
              sort
            ></json-viewer>
          </el-col>
          <el-col :span="8">
            控制台：
            <el-input
              v-model="errorPreviewData"
              :rows="10"
              style="color: red"
              disabled
              type="textarea"
              clearable
            >
            </el-input>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </el-form>
  <el-dialog title="数据展开" v-model="isExpandVisible">
    <json-viewer
      :value="expandData"
      :expand-depth="100"
      style="width: 100%"
    ></json-viewer
  ></el-dialog>
</template>

<script setup>
/**
 * @author: JimTT
 * @description: 适配器设计
 */

import JsonViewer from "vue-json-viewer";
import JavaCodeEdit from "@/components/codeEdit/JavaCodeEdit.vue";
import JsCodeEdit from "@/components/codeEdit/JsCodeEdit.vue";
import { ElMessage } from "element-plus";
import {
  getMockData,
  getSpecialDetail,
  executeCode,
  savaCode,
} from "@/api/custom-query/adapter";
import { useRouter } from "vue-router";

const isExpandBtnVisible = ref(false);
const isExpandVisible = ref(false);
const unencryptedPortalId = ref(null);
const mockData = ref();
const codeData = ref(null);
const resPreviewData = ref();
const errorPreviewData = ref();
const expandData = ref(null);
const router = useRouter();
const isSpecial = router.currentRoute.value.query.special;
const portalId = router.currentRoute.value.query.portalId;
const queryParams = ref({});
const mappings = ref([]);
const codeType = ref(null);

// 获取专用适配器详情
const getSpecialDetails = async () => {
  const { code, data } = await getSpecialDetail(portalId);
  if (code === 1000) {
    mappings.value = data.mappings;
    unencryptedPortalId.value = data.portalId;
    codeData.value = data.dataAdapter.code;
    codeType.value = data.dataAdapter.type;
  }
};
getSpecialDetails();

// 保存
const handleSave = async () => {
  try {
    const { code } = await savaCode({
      code: codeData.value,
      portalId: unencryptedPortalId.value,
    });
    if (code === 1000) {
      ElMessage.success("保存成功");
    }
  } catch (err) {
    console.log(err);
  }
};

// 执行
const handleExecute = async () => {
  let params = [];
  mappings.value.forEach((item) => {
    params.push({
      key: item.mappingKey,
      value: item.userInput,
    });
  });

  let mockParams = {
    code: codeData.value,
    params,
    portalId: unencryptedPortalId.value,
  };

  try {
    const { code, data } = await executeCode(mockParams);
    if (code === 1000) {
      if (data.success) {
        resPreviewData.value = data.result;
        errorPreviewData.value = data.console;
      } else {
        errorPreviewData.value = data.console;
        resPreviewData.value = data.result;
      }
    }
  } catch (err) {
    console.log(err);
  }
};

// 查看资源
const handleSourceData = async () => {
  let params = [];
  mappings.value.forEach((item) => {
    params.push({
      key: item.mappingKey,
      value: item.userInput,
    });
  });
  const res = await getMockData({
    params,
    portalId: unencryptedPortalId.value,
  });
  if (res.code === 1000) {
    isExpandBtnVisible.value = true;
    mockData.value = res.data;
  }
};
</script>

<style scoped lang="scss">
.data-preview {
  width: 98%;
  margin: 10px auto;
  display: flex;
  justify-content: space-between;
  .copy {
    color: #418dff;
    cursor: pointer;
  }
}
.preview-bottom {
  max-height: 255px;
  .bottom-preview {
    max-height: 255px;
  }
  .bottom-printf {
    max-height: 255px;
    overflow-y: auto;
  }
}
.json-viewer-father {
  position: relative;

  .json-viewer {
    height: 305px;
    overflow: auto;
  }
  .expand {
    display: block;
    position: absolute;
    color: #49c4ff;
    top: 270px;
    left: -50px;
    z-index: 999;
    cursor: pointer;
  }
}
::v-deep .v-codemirror .cm-focused {
  outline: none;
}
::v-deep .jv-container.jv-light .jv-item.jv-undefined {
  display: none;
}
::v-deep .el-textarea.is-disabled .el-textarea__inner {
  color: red;
  background-color: #fff;
}
</style>
