<template>
  <div>
    <Title>
      <template v-slot:titleName>系统接口列表</template>
      <template v-slot:titleContent></template>
      <template v-slot:titleOperate>
        <el-link type="primary" @click="showExportApis">导出接口列表({{ exportApis.length }})</el-link>
      </template>
    </Title>

    <!--搜索条件-->
    <div  class="form-container ab-p-l-20" >
        <el-radio-group style="padding-bottom: 25px;" v-model="radioModel" v-for="subsystem in subsystems" :key="subsystem">
            <el-radio-button :label="subsystem" @change="versionGroup='';useTableQueryReload(tableRef)" />
        </el-radio-group>
    </div>
    <!--表列表-->
    <div class="table-container">
      <vxe-grid ref="tableRef" v-bind="tableOptions">
        <template #buttons_toolbar>
          <el-space wrap>
            <el-text style="font-size: 30px;" tag="b">{{ currentSubSystem }}</el-text>
            <el-select v-show="versionGroups.length>1" v-model="versionGroup" placeholder="Select" style="width: 100px;" @change="useTableQueryReload(tableRef)">
              <el-option v-for="item in versionGroups" :key="item" :label="item+'版本'" :value="item"/>
            </el-select>
          </el-space>
        </template>
        <template #tools_toolbar>
          <el-input style="margin-right: 15px; " v-model="filterName" type="search" placeholder="表内搜索" @keyup="useInVxeGridSearch(tableRef)"></el-input>
        </template>
        <template #url="{ row }">
          <el-text v-if="row.deprecated" tag="del">{{ row.url }}</el-text>
          <el-text v-else>{{ row.url }}</el-text>
        </template>
        <template #summary="{ row }">
            <el-text v-if="row.deprecated" type="danger">(已过时，建议使用其他接口代替)<el-text tag="del">{{ row.summary }}</el-text></el-text>
            <el-text v-else>{{ row.summary }}</el-text>
        </template>
        <template #operate="{ row }">
          <el-link type="primary"  :underline="false"  @click="showDetail(row)"  title="详情"><el-icon size="20"><Document /></el-icon></el-link>
          <el-link type="primary" :underline="false" @click="addExportApis(row)"  title="添加到导出接口列表"><el-icon size="20" ><Plus /></el-icon></el-link>
        </template>
      </vxe-grid>
    </div>
  </div>

  <!--导出接口列表-->
  <el-drawer v-model="dialogFormVisible" direction="rtl" size="50%" title="导出接口列表">
    <vxe-toolbar ref="exportToolbarRef" custom>
      <template #tools>
        <el-input style="margin-right: 15px; " v-model="exportFilterName" type="search" placeholder="表内搜索" @keyup="exportTableSearch" ></el-input>
      </template>
    </vxe-toolbar>
    
    <vxe-table ref="exportTableRef" :data="currentExportApis" :params="{tableDataCache: exportApis,filterNameRef: exportFilterName, children: false,allTreeExpand:false,}" >
      <vxe-column type="seq" title="序号" ></vxe-column>
      <vxe-column field="subsystem" title="系统名称"></vxe-column>
      <vxe-column field="method" title="接口方法"></vxe-column>
      <vxe-column field="url" title="接口地址"></vxe-column>
      <vxe-column field="summary" title="接口说明"></vxe-column>
      <vxe-column title="操作">
        <template #default="{ row }">
          <el-link type="primary"  :underline="false"  @click="deleteExportApis(row)"  title="删除"><el-icon size="20"><Delete /></el-icon></el-link>
        </template>
      </vxe-column>
    </vxe-table>
    <el-row justify="end" style="margin-top: 10px;">
      <el-col :span="8" style="text-align: right;">
        <el-button type="primary" @click="exportApis=[];currentExportApis=[];dialogFormVisible=false">清空</el-button>
        <el-button type="success" @click="exportDoc">导出</el-button>
      </el-col>
    </el-row>
  </el-drawer>

  
<!--接口详情-->
<el-drawer v-model="detailVisible" direction="rtl" size="85%" title="接口详情">
  <Detail :api="detailData" :key="detailData.method+detailData.subsystem+detailData.url"></Detail>
</el-drawer>

</template>
  

<script lang="ts">
export default { name: "dataDictionary" }
</script>
<script setup lang="ts">
import { VxeGridInstance, VxeGridProps } from 'vxe-table'
import  Detail from './detail.vue'
import Title from "@/framework/components/Title/index.vue";
import { getAbacusAPISubsystems,getAbacusAPIs,exportAbacusAPIs } from '@/subsystem/api/sms/index'
import { useQueryParamsHandle,useInVxeGridSearch,useInVxeTableSearch,useQueryAndClientPaging,useTableQueryReload } from '@/framework/hooks/useVxeTableHandle'
import { gridDefaultProps } from '@/framework/utils/standard/vxe.ts'
const dialogFormVisible=ref(false)
const detailVisible=ref(false)
const detailData=ref({})

const exportApis=ref([])
const exportToolbarRef = ref<VxeToolbarInstance>()
const exportTableRef = ref<VxeTableInstance>()//表详情表格对象

const exportFilterName=ref('')
const currentExportApis=ref([])
const exportTableSearch = () => {
  currentExportApis.value=useInVxeTableSearch(exportTableRef.value)
}

const showDetail = (row) => {
  detailVisible.value=true
  detailData.value=row
}


const deleteExportApis = (row) => {
  exportApis.value = exportApis.value.filter(o => o.subsystem+o.method+o.url!==row.subsystem+row.method+row.url)
  currentExportApis.value=exportApis.value
}
const showExportApis = () => {
  if (exportApis.value.length <= 0) {
    ElMessage({message: '未选择需要导出的接口',type: 'error',})
    return false;
  }
  dialogFormVisible.value=true
  currentExportApis.value=exportApis.value
  exportFilterName.value=''
  nextTick(() => {
    // 将表格和工具栏进行关联
    const $table = exportTableRef.value
    const $toolbar = exportToolbarRef.value
    if ($table && $toolbar) {
      $table.connect($toolbar)
    }
  })
}
const exportDoc = () => {
  if (exportApis.value.length <= 0) {
    ElMessage({message: '请选择需要导出的接口',type: 'error',})
    return false;
  }
  let items = new Array();
  exportApis.value.forEach(api=>
    items.push(api.subsystem+"/"+api.method+api.url)
  )
  console.log(items);
  exportAbacusAPIs(JSON.stringify(items)).then((data: any) => {
    console.log(data);
    //window.location.href = "/"+data;
    dialogFormVisible.value=false
    exportApis.value=[]
    ElMessage({message: '导出完成',type: 'success',})
    return false;
  }).finally(() => {
  });
}

const addExportApis = (row) => {
  if(undefined!==exportApis.value.find(item => item.subsystem+item.method+item.url===row.subsystem+row.method+row.url)){
    ElMessage({message: '接口已存在',type: 'error',})
    return false
  }
  exportApis.value.push(row)
  ElMessage({message: '添加成功',type: 'success',})
}

const subsystems = ref([])
const radioModel=ref('');

const versionGroups=ref([])
const versionGroup=ref('')
const currentSubSystem=ref('')

/**表格初始化 */
const filterName = ref('')
const tableData = ref([])
const tableRef = ref<VxeGridInstance>()//表格对象
const tableOptions = reactive<VxeGridProps>(gridDefaultProps({
  params: reactive<VxeTableParam>({
    clientPage: true, //是否客户端分页
    tableDataCache: tableData, //表格数据缓存
    filterNameRef: filterName, //表内搜索引用
    // searchProps: [],//需要检索列的key
    children: false,//树形表格场景，表内搜索筛选后的数据，是否作为子节点展示，默认否
    allTreeExpand:false,//树形表格场景，表内搜索筛选后的数据，是否自动展开子节点，默认否
  }),
  rowConfig: {keyField: 'id'},//自定义行数据唯一主键的字段名
  sortConfig: { trigger: 'cell', remote: true, }, //排序配置
  pagerConfig: { enabled: true, pageSize: 10, pageSizes: [10, 20, 50, 100] },//分页配置
  toolbarConfig: { custom: true, slots: { buttons: 'buttons_toolbar', tools: 'tools_toolbar' }, },//工具栏配置
  proxyConfig: {
    seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
    sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
    filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
    props: { result: 'data', total: 'total' },// 对应响应结果，按照后台服务PageResult对象配置
    ajax: {
      // 接收 Promise 对象
      query: ({ page, sorts, filters }) => {
        const queryParams = useQueryParamsHandle({'subsystem':radioModel.value}, page, sorts, filters)//请求参数处理
        return useQueryAndClientPaging(tableRef,page, sorts,function(){ return getAndHandleAbacusAPIs(queryParams)  }) //客户端分页
      },
    }
  },
  columns: [
    { type: 'seq', title: '序号', width:'50px' },
    { field: 'method', title: '接口方法',minWidth:'5%'},
    { field: 'url', title: '接口地址',minWidth:'20%',slots: {default: 'url'}},
    { field: 'summary', title: '接口说明' ,minWidth:'40%',slots: {default: 'summary'} },
    { field: '', title: '操作',slots: {default: 'operate'},align:'center',minWidth:'5%'},//操作类居中显示 
  ]
}))

/**获取并处理子系统接口数据*/
const getAndHandleAbacusAPIs = (queryParams) => {
  if(""===queryParams.subsystem)
    return []
  versionGroups.value=[]
  return getAbacusAPIs(queryParams).then((data: any) => {
    currentSubSystem.value=data[0].info.title
    if(""==versionGroup.value)
      versionGroup.value=data[0].group
    let apiList=new Array
    data.forEach(item => {
      versionGroups.value.push(item.group);
      item.apis.forEach(api => { Object.assign( api , {version:item.group,subsystem:radioModel.value}) });
      if(item.group===versionGroup.value){
        apiList=apiList.concat(item.apis)
      }
    });

    return apiList
  }).finally(() => {
  });
}




onMounted(() => {
  getAbacusAPISubsystems().then((data: any) => {
      subsystems.value=data
      radioModel.value=data[0]
      useTableQueryReload(tableRef.value)
  }).finally(() => {
  })
});


defineExpose({
  // deptQuery
})


</script>

<style lang="scss" scoped>
</style>
