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

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import PSModule from './components/Module.vue'
import PSApi from './components/Api.vue'
import { deleteApiById, getApiByList, updateApiStatus } from '@/api/api/apiApi'
import { deleteModuleById, getModuleByList } from '@/api/api/apiModuleApi'
import useSettingsStore from '@/store/modules/settings'
import { apiType } from '@/utils/tool'

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

interface TreeNode {
  label: string
  isLeaf: boolean
  moduleId: number
  children?: TreeNode[]
}

interface Api {
  moduleId: number
  apiId: number
  apiType: number
  apiTitle: string
  apiCode: string
  apiDesc: string
  apiParams: string
  status: number
}

const state = reactive({
  loading: false,
  keywords: '',
  modules: [] as TreeNode[],
  curModuleId: 0,
  apiList: [] as Api[],
  dialogState: 1,
  search: {
    keywords: '',
  },
})

const leftTreeRef = ref()
const ModuleRef = ref()
const getApiData = async () => {
  const curModuleId = state.curModuleId
  if (curModuleId > 0) {
    state.loading = true
    const { data } = await getApiByList({ moduleId: curModuleId })
    state.apiList = data
    state.loading = false
  }
}

const getModuleData = async () => {
  const { data } = await getModuleByList('')
  const children: TreeNode[] = []
  data.forEach((item: any) => {
    return children.push({
      label: item.moduleTitle,
      moduleId: item.moduleId,
      isLeaf: true,
    })
  })
  state.modules = [
    {
      label: '功能模块',
      isLeaf: false,
      moduleId: -1,
      children,
    },
  ]

  if (data && data.length > 0) {
    state.curModuleId = data[0].moduleId

    await getApiData()
    await nextTick(() => {
      leftTreeRef.value.setCurrentKey(data[0].moduleId)
    })
  }
}
// 模块新增
const onModuleAdd = () => {
  ModuleRef.value.showAddModule()
}

// 模块编辑
const onModuleEdit = (data: { moduleId: number }) => {
  const moduleId = data.moduleId
  ModuleRef.value.showEditModule(moduleId)
}

// 模块删除
const onModuleDelete = (data: any) => {
  ElMessageBox.confirm(`确认删除「${data.modTitle}」吗？`, '确认信息').then(async () => {
    await deleteModuleById(data.moduleId)
    await getModuleData()
    ElMessage.success({
      message: '删除成功',
      center: true,
    })
  })
}

onMounted(() => {
  getModuleData()
})

// 模块选择
const onTreeNodeClick = (node: TreeNode) => {
  if (node.isLeaf) {
    state.curModuleId = node.moduleId
    getApiData()
  }
}

const apiTableRef = ref()
const apiRef = ref()

// 检索对象
const onSearch = () => {
  getApiData()
}

// 新增API
const onApiAdd = () => {
  apiRef.value.showAddApi(state.curModuleId)
}

// 编辑API
const onApiEdit = (data: { moduleId: number; apiId: number }) => {
  const moduleId = data.moduleId
  const apiId = data.apiId
  apiRef.value.showEditApi(moduleId, apiId)
}

// 删除API
const onApiDelete = (row: any) => {
  const { moduleId, apiId, apiTitle } = row
  ElMessageBox.confirm(`确认删除「${apiTitle}」吗？`, '确认信息').then(async () => {
    await deleteApiById(moduleId, apiId)
    await getApiData()
    ElMessage.success({
      message: '删除成功',
      center: true,
    })
  })
}

// 编辑对象
const onApiTrans = (row: { moduleId: number; apiId: number }) => {
  if (settingsStore.settings.tabbar.enable && settingsStore.settings.tabbar.mergeTabsBy !== 'activeMenu') {
    tabbar.open({
      name: 'apiTrans',
      params: {
        moduleId: row.moduleId,
        apiId: row.apiId,
      },
    })
  }
  else {
    router.push({
      name: 'apiTrans',
      params: {
        moduleId: row.moduleId,
        apiId: row.apiId,
      },
    })
  }
}

async function onChangeStatus(row: { moduleId: number; apiId: number; status: number }) {
  const res = await updateApiStatus(row.moduleId, row.apiId, row.status)
  ElMessage.success({
    message: res.msg,
    center: true,
  })
}
</script>

<template>
  <div class="absolute-container">
    <tool-header title="API管理">
      <template #right>
        <el-button type="primary" plain @click="onModuleAdd">
          <template #icon>
            <el-icon>
              <svg-icon name="i-ep:plus" />
            </el-icon>
          </template>
          新增模块
        </el-button>
      </template>
    </tool-header>

    <div class="page-main">
      <LayoutContainer left-side-width="250px" hide-left-side-toggle>
        <template #leftSide>
          <el-scrollbar class="tree">
            <ElTree ref="leftTreeRef" :data="state.modules" default-expand-all node-key="moduleId" @node-click="onTreeNodeClick">
              <template #default="{ node, data }">
                <div class="custom-tree-node">
                  <div class="label" :title="node.label">
                    <el-icon v-if="data.isLeaf" size="16px" style="margin-right: 5px;">
                      <svg-icon name="uim:box" />
                    </el-icon>
                    <div class="text">
                      {{ data.label }}
                    </div>
                  </div>
                  <div v-if="data.isLeaf" class="actions">
                    <el-button-group>
                      <el-button type="info" plain size="small" @click.stop="onModuleEdit(data)">
                        <template #icon>
                          <el-icon>
                            <svg-icon name="i-ep:edit" />
                          </el-icon>
                        </template>
                      </el-button>
                      <el-button type="danger" plain size="small" @click.stop="onModuleDelete(data)">
                        <template #icon>
                          <el-icon>
                            <svg-icon name="i-ep:delete" />
                          </el-icon>
                        </template>
                      </el-button>
                    </el-button-group>
                  </div>
                </div>
              </template>
            </ElTree>
          </el-scrollbar>
        </template>

        <div class="container">
          <tool-bar>
            <template #right>
              <el-input v-model="state.search.keywords" placeholder="请输入名称，支持模糊查询" style="padding-right: 10px;" clearable />
              <el-button type="primary" @click="onSearch">
                <template #icon>
                  <el-icon>
                    <svg-icon name="i-ep:search" />
                  </el-icon>
                </template>
              </el-button>

              <el-button type="primary" plain size="default" @click.stop="onApiAdd">
                <template #icon>
                  <el-icon>
                    <svg-icon name="i-ep:plus" />
                  </el-icon>
                </template>
                新增API
              </el-button>
            </template>
          </tool-bar>

          <el-table ref="apiTableRef" v-loading="state.loading" class="list-table" :data="state.apiList" border stripe highlight-current-row height="100%">
            <el-table-column type="index" label="序号" header-align="center" align="center" width="70" />

            <el-table-column prop="apiTitle" label="名称" header-align="center" align="center" width="200">
              <template #default="scope">
                <span> {{ scope.row.apiTitle }} </span>
              </template>
            </el-table-column>

            <el-table-column prop="apiType" label="请求" header-align="center" align="center" width="100">
              <template #default="scope">
                <span> {{ apiType(scope.row.apiType) }} </span>
              </template>
            </el-table-column>

            <el-table-column prop="apiCode" label="代码" header-align="left" align="left" width="200">
              <template #default="scope">
                <span> {{ scope.row.apiCode }} </span>
              </template>
            </el-table-column>

            <el-table-column prop="apiDesc" label="说明" header-align="center" align="left">
              <template #default="scope">
                <span> {{ scope.row.apiDesc }} </span>
              </template>
            </el-table-column>

            <el-table-column prop="status" label="状态" header-align="center" align="center" width="100">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.status"
                  :active-value="1"
                  :inactive-value="0"
                  :loading="scope.row.loading"
                  inline-prompt
                  active-text="启用"
                  inactive-text="禁用"
                  @change="(status) => onChangeStatus(scope.row)"
                />
              </template>
            </el-table-column>

            <el-table-column label="操作" header-align="center" align="center" width="210">
              <template #default="scope">
                <el-button type="primary" size="small" plain @click="onApiTrans(scope.row)">事务</el-button>
                <el-button type="warning" size="small" plain @click="onApiEdit(scope.row)">编辑</el-button>
                <el-button type="danger" size="small" plain @click="onApiDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </LayoutContainer>
    </div>
    <PSModule ref="ModuleRef" @success="getModuleData" />
    <PSApi ref="apiRef" @success="getApiData" />
  </div>
</template>

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

  .absolute-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;
              }
            }
          }
        }
      }
    }
  }
</style>
