<router lang="yaml">
meta:
  enabled: false
</router>

<script lang="ts" setup name="apiTrans">
import type { FormInstance } from 'element-plus'

import useSettingsStore from '@/store/modules/settings'
import { getApiById } from '@/api/api/apiApi'
import { createX, deleteX, generateParams, getX, patchX, updateX } from '@/api/api/apiGatewayApi'
import { getObjectOAMParamsListByOamId } from '@/api/biz/bizObjectOAMParamsApi'
import { httpMethod, oamType } from '@/utils/tool'

const settingsStore = useSettingsStore()
const route = useRoute()
const router = useRouter()
const tabbar = useTabbar()

const apiId = parseInt(route.params.apiId.toString())

interface ObjectOAMParams {
  bizId: number
  objectId: number
  oamId: number
  paramId: number
  logicalOperator: string
  compareOperator: string
  paramName: string
  paramValue: string
  paramType: number
  paramRemark: string
  isRuled: number
  ruleId: number
  sortNo: number
}

const state = reactive({
  loading: false,
  dialogState: 1,
  search: {
    apiId,
    keywords: '',
  },
  params: {},
  viewData: {
    bizId: 0,
    bizTitle: '',
    apiTitle: '',
    apiMethod: 1,
    apiCode: '',
    apiType: 0,
    apiParams: '',
    objectId: 0,
    objectType: 0,
    objectCode: '',
    objectTitle: '',
    oamId: 0,
    oamType: 0,
    oamCode: '',
    oamTitle: '',
  },
  paramList: [] as ObjectOAMParams[],
  formData: {
    params: '',
    apiBody: '',
  },
  reservedParams: {
    limit: 1,
    page: 2,
  },
  result: '',
})

const getApiParams = async () => {
  state.loading = true
  const { bizId, objectId, oamId } = state.viewData
  const { data } = await getObjectOAMParamsListByOamId(bizId, objectId, oamId)
  data.forEach((item: any) => {
    item.paramName = item.paramValue
  })

  state.paramList = data
  if (state.viewData.oamType === 7) {
    state.paramList.push(
      {
        bizId: 0,
        objectId: 0,
        oamId: 0,
        paramId: 0,
        logicalOperator: '',
        compareOperator: '',
        paramName: 'page',
        paramValue: '1',
        paramType: 1,
        paramRemark: '',
        isRuled: 0,
        ruleId: 0,
        sortNo: 0,
      },
      {
        bizId: 0,
        objectId: 0,
        oamId: 0,
        paramId: 0,
        logicalOperator: '',
        compareOperator: '',
        paramName: 'limit',
        paramValue: '10',
        paramType: 1,
        paramRemark: '',
        isRuled: 0,
        ruleId: 0,
        sortNo: 0,
      },
    )
  }

  state.loading = false
}

// 查询数据
const getData = async () => {
  state.loading = true
  const { data } = await getApiById(apiId)
  state.viewData.bizId = data.bizId
  state.viewData.bizTitle = data.bizTitle
  state.viewData.apiTitle = data.apiTitle
  state.viewData.apiCode = data.apiCode
  state.viewData.apiParams = data.apiParams
  state.viewData.apiMethod = data.apiMethod
  state.viewData.apiType = data.apiType
  state.viewData.objectId = data.objectId
  state.viewData.objectTitle = data.objectTitle
  state.viewData.objectCode = data.objectCode
  state.viewData.objectType = data.objectType
  state.viewData.oamId = data.oamId
  state.viewData.oamType = data.oamType
  state.viewData.oamTitle = data.oamTitle
  state.viewData.oamCode = data.oamCode

  if (data.oamType > 4) {
    await getApiParams()
  }
}

const paramsTableRef = ref()
const paramsTableKey = ref(0)

onMounted(() => {
  getData()
})

const formRef = ref<FormInstance>()

const onGenerateData = async () => {
  const objectCode = state.viewData.objectCode
  const oamCode = state.viewData.oamCode
  const { data } = await generateParams(objectCode, oamCode)
  state.formData.apiBody = JSON.stringify(data)
}

interface param {
  [x: string]: any
}

const onExecute = async () => {
  const apiMethod = state.viewData.apiMethod
  const objectCode = state.viewData.objectCode
  const oamCode = state.viewData.oamCode
  const queryParams: param = {}
  state.paramList.forEach((item: { paramName: string; paramValue: string }) => {
    queryParams[item.paramName] = item.paramValue
  })

  let apiBody = ''
  if (state.formData.apiBody !== '') {
    apiBody = JSON.parse(state.formData.apiBody)
  }

  if (apiMethod === 1) {
    const { data } = await getX(objectCode, oamCode, queryParams)
    state.result = JSON.stringify(data)
  }
  else if (apiMethod === 2) {
    const { data } = await createX(objectCode, oamCode, apiBody)
    state.result = JSON.stringify(data)
  }
  else if (apiMethod === 3) {
    const { data } = await updateX(objectCode, oamCode, apiBody)
    state.result = JSON.stringify(data)
  }
  else if (apiMethod === 4) {
    const { data } = await patchX(objectCode, oamCode, apiBody)
    state.result = JSON.stringify(data)
  }
  else if (apiMethod === 5) {
    const { data } = await deleteX(objectCode, oamCode, apiBody)
    state.result = JSON.stringify(data)
  }
}

// 返回列表页
function goBack() {
  if (settingsStore.settings.tabbar.enable && settingsStore.settings.tabbar.mergeTabsBy !== 'activeMenu') {
    tabbar.close({ name: 'api' })
  }
  else {
    router.push({ name: 'api' })
  }
}
</script>

<template>
  <div class="absolute-container">
    <page-header :title="state.viewData.apiTitle" :content="state.apiCode">
      <el-button size="default" round @click="goBack">
        <template #icon>
          <el-icon>
            <svg-icon name="i-ep:arrow-left" />
          </el-icon>
        </template>
        返回
      </el-button>
    </page-header>

    <div class="page-main">
      <LayoutContainer left-side-width="350px" hide-left-side-toggle>
        <template #leftSide>
          <el-descriptions
            :title="state.viewData.oamTitle"
            direction="horizontal"
            :column="1"
            size="small"
            border
          >
            <el-descriptions-item
              label-align="right"
              label="URL:"
              width="150px"
            >
              <span>{{ httpMethod(state.viewData.apiMethod) }}: /{{ state.viewData.objectCode }}/{{ state.viewData.oamCode }} </span>
            </el-descriptions-item>

            <el-descriptions-item
              label-align="right"
              label="业务模型"
              width="150px"
            >
              {{ state.viewData.bizTitle }}
            </el-descriptions-item>

            <el-descriptions-item
              label-align="right"
              label="业务对象"
              width="150px"
            >
              {{ state.viewData.objectTitle }}
            </el-descriptions-item>

            <el-descriptions-item
              label-align="right"
              label="编码"
              width="150px"
            >
              {{ state.viewData.oamCode }}
            </el-descriptions-item>

            <el-descriptions-item
              label="行为类型"
              width="150px"
              label-align="right"
            >
              {{ oamType(state.viewData.oamType) }}
            </el-descriptions-item>

            <el-descriptions-item
              label-align="right"
              width="150px"
              label="说明"
            >
              {{ state.viewData.oamDesc }}
            </el-descriptions-item>
          </el-descriptions>
        </template>

        <div class="form">
          <el-form ref="formRef" label-width="100px" label-position="top">
            <el-form-item v-if="state.viewData.oamType > 4" label="查询条件">
              <el-table
                ref="paramsTableRef"
                :key="paramsTableKey"
                :data="state.paramList"
                class="list-table"
                size="small"
                :show-header="false"
                border
                stripe
                highlight-current-row
              >
                <el-table-column label="参数" header-align="center" align="center" width="150">
                  <template #default="scope">
                    <span>{{ scope.row.paramName }}</span>
                  </template>
                </el-table-column>

                <el-table-column label="值" header-align="left" align="left">
                  <template #default="scope">
                    <input v-model="scope.row.paramValue">
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>

            <el-form-item v-if="state.viewData.oamType <= 4" label="数据">
              <el-input v-model="state.formData.apiBody" type="textarea" rows="10" placeholder="数据" />
            </el-form-item>

            <el-form-item v-if="state.result" label="结果">
              <el-input v-model="state.result" type="textarea" rows="10" placeholder="结果" readonly />
            </el-form-item>

            <div class="action-bottom">
              <el-button v-if="state.viewData.oamType <= 4" type="primary" @click="onGenerateData">
                生成API数据
              </el-button>
              <el-button type="primary" @click="onExecute">
                立即执行
              </el-button>
            </div>
          </el-form>
        </div>
      </LayoutContainer>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.absolute-container {
  position: absolute;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .page-header {
    margin-bottom: 0;
  }

  .page-main {
    flex: 1;
    overflow: auto;
    display: flex;
    flex-direction: column;

    .flex-container {
      position: static;
    }
  }
}

.flex-container {
  :deep(.left-side) {
    display: flex;
    flex-direction: column;
    height: 100%;

    .btns {
      display: inline-flex;
      width: 100%;
      margin-bottom: var(--container-padding);

      .add {
        width: 100%;
      }
    }

    .tree {
      flex: 1;
      overflow-y: auto;

      .el-tree {
        .el-tree-node__content {
          height: 40px;
        }

        .is-current > .el-tree-node__content {
          background-color: var(--el-color-primary-light-9);
        }

        .custom-tree-node {
          flex: 1;
          position: relative;
          width: 0;
          height: 100%;
          display: flex;
          flex-direction: column;
          justify-content: center;

          .label {
            display: inline-flex;
            align-items: center;
            width: calc(100% - 10px);
            color: var(--el-text-color-primary);

            .text {
              @include text-overflow;
            }
          }

          &:hover {
            .actions {
              display: block;
            }
          }

          .actions {
            display: none;
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);

            .el-button {
              padding: 5px 8px;
            }
          }
        }
      }
    }
  }

  :deep(.main) {
    .main-container {
      display: flex;
      flex-direction: column;
      justify-content: center;
      width: 100%;
      height: 100%;
    }
  }
}

.form {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;

  .el-form {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;

    .columns-table {
      flex: 1;
      height: 0;
      display: flex;
      flex-direction: column;

      :deep(.el-form-item__content) {
        min-height: 0;

        .el-table {
          height: 100%;
        }
      }
    }
  }
}

.action-bottom {
  padding: var(--container-padding);
  border-top: 1px dashed var(--el-disabled-border-color);
  background-color: var(--g-app-bg);
  transition: background-color 0.3s;
  display: flex;
  justify-content: right;
}
</style>
