<template>
  <div class="partner">
    <container class-name="bg-white">
      <div class="p-6">
        <div class="info-wrapper pt-6 pb-4">
          <div class="title text-xl text-main font-semibold mb-4">
            {{apiInfo.title}}
          </div>
          <div class="">
            <div class="py-0.5">简介: {{apiInfo.description}}</div>
            <div class="py-0.5">版本: {{apiInfo.version}}</div>
            <div class="py-0.5">服务Url: {{apiInfo.termsOfService}}</div>
          </div>
        </div>
        <a-collapse :bordered="true" default-active-key="1" expand-icon-position="right" accordion>
          <!-- <template #expandIcon="props">
            <a-icon type="caret-right" :rotate="props.isActive ? 90 : 0" />
          </template> -->
          <a-collapse-panel
              v-for="(c, index) in apiTags"
              :key="index"
              :header="c.name"
              :style="customStyle">

            <a-collapse default-active-key="1" expand-icon-position="right" accordion>
              <a-collapse-panel
                  v-for="val in getPathList(c.name)"
                  :key="`${val[0]}${val[1]}`"
                  :style="customStyleChild">
                <div slot="header" class="header text-main text-base flex items-center">
                  <a-tag :color="tagColor[val[1]]">{{val[1]}}</a-tag>
                  <div class="mx-2 font-semibold">{{val[0]}}</div>
                  <div class="mx-2 font-normal">{{val[2].summary}}</div>
                </div>
                <div class="">
                  <!-- parameters -->
                  <div class="py-2">
                    <div class="text-sm font-semibold text-main mb-2">Parameters / 请求参数</div>
                    <a-table
                        bordered
                        size="middle"
                        :pagination="false"
                        :columns="parameterTableCols"
                        :data-source="getParameters(val[2].parameters)">
                      <span slot="required" slot-scope="required">{{String(required || '')}}</span>
                    </a-table>
                  </div>
                  <!-- responses -->
                  <div class="py-2">
                    <div class="text-sm font-semibold text-main mb-2">Responses / 响应状态</div>
                    <a-table
                        bordered
                        size="middle"
                        :pagination="false"
                        :columns="responseCols"
                        :data-source="getResponseData(val[2].responses)">
                    </a-table>
                  </div>
                  <!-- 相应参数 -->
                  <div class="py-2">
                    <div class="text-sm font-semibold text-main mb-2">Responses / 响应参数</div>
                    <a-table
                        bordered
                        size="middle"
                        :pagination="false"
                        :columns="responseParameterCols"
                        :data-source="getResponseParameterData(val[2].responses['200'])">
                    </a-table>
                  </div>
                </div>
              </a-collapse-panel>
            </a-collapse>

          </a-collapse-panel>
        </a-collapse>
      </div>
    </container>
  </div>
</template>
<script lang="ts">
import 'tailwindcss/tailwind.css'
import '@/style.css'
import Vue from 'vue'
// import PageHeadBanner from '@/components/PageHeadBanner.vue'
import Container from '@/components/Container.vue'
import { highLights, imgs } from '@/context/partner-page'
import { openApi } from '@/context/openApi'
import { Collapse, Icon, Tag, Table } from 'ant-design-vue'
Vue.use(Collapse).use(Icon).use(Tag).use(Table)
enum Method {
  GET = 'get',
  POST = 'post',
  PUT = 'put',
  DELETE = 'delete',
  UPDATE = 'update',
}

interface Result {
  [key: string]: PathObj
}

interface PathObj {
  [key: string]: [Method, PathDetail][]
}

interface PathDetail {
  tags: string[],
  summary: string,
  operationId: string,
  produces: string[],
  parameters: any[],
  responses: {[key: string]: {
      description: string,
      schema?: {[key: string]: any}
    }}
}

interface Response {
  description: string,
  schema?: any,
}

interface Schema {
  type: string,
  description: string,
  format: string,
  schema: any,
  [key: string]: any
}

const parameterTableCols = [
  {
    title: 'name',
    dataIndex: 'name',
    key: 'name'
  }, {
    title: 'in',
    dataIndex: 'in',
    key: 'in'
  }, {
    title: 'description',
    dataIndex: 'description',
    key: 'description'
  }, {
    title: 'required',
    dataIndex: 'required',
    key: 'required',
    scopedSlots: { customRender: 'required' }
  }, {
    title: 'type',
    dataIndex: 'type',
    key: 'type'
  }
]

const responseCols = [
  {
    title: '状态码',
    dataIndex: 'status',
    key: 'status'
  }, {
    title: '说明',
    dataIndex: 'description',
    key: 'description'
  }, {
    title: 'schema',
    dataIndex: 'schema',
    key: 'schema'
  }
]

const responseParameterCols = [
  {
    title: '参数名称',
    dataIndex: 'name',
    key: 'name'
  }, {
    title: '参数说明',
    dataIndex: 'description',
    key: 'description'
  }, {
    title: '类型',
    dataIndex: 'type',
    key: 'type'
  }, {
    title: 'schema',
    dataIndex: 'schema',
    key: 'schema'
  }
]

export default Vue.extend({
  components: {
    // PageHeadBanner,
    Container
  },
  data () {
    return {
      highLights,
      imgs,
      text: 'A dog is a type of domesticated animal.Known for its loyalty and faithfulness,it can be found as a welcome guest in many households across the world.',
      tagColor: {
        get: '#2db7f5',
        post: '#49cc90',
        put: '#fca130',
        delete: '#f93e3e',
        update: '#108ee9'
      },
      parameterTableCols,
      responseCols,
      responseParameterCols
    }
  },
  created () {
    console.log(openApi, typeof openApi, 'openApi')
    // for (let key in this.generatePathList['index-controller']) {
    //   console.log(key, 'keu')
    // }
  },
  computed: {
    apiInfo () {
      return openApi.info
    },
    definitions () {
      return openApi.definitions
    },
    apiTags () {
      return openApi.tags
    },
    customStyle () {
      return 'background: #fff; font-size: 18px; font-weight: medium'
    },
    customStyleChild () {
      return 'background: #F8F8F8;font-size: 16px; font-weight: medium'
    },
    generatePathList () {
      const result: Result = {}
      const paths = openApi.paths
      Object.entries(paths).forEach(path => {
        // 请求url
        const pathUrl = path[0]
        // 请求url详情
        const pathDetail = path[1]
        const pathDetailEntries = Object.entries(pathDetail) as unknown as Array<[Method, PathDetail]>
        // 获取url对应tagName
        const tagName = pathDetailEntries[0][1].tags[0]
        if (typeof result[tagName] === 'undefined') {
          result[tagName] = {} as PathObj
          result[tagName][pathUrl] = [...pathDetailEntries]
        } else {
          if (typeof result[tagName][pathUrl] === 'undefined') {
            result[tagName][pathUrl] = [...pathDetailEntries]
          } else {
            result[tagName][pathUrl] = [...pathDetailEntries, ...result[tagName][pathUrl]]
          }
        }
      })
      return result
    }
  },
  methods: {
    setParams (params: any[]): any[] {
      if (typeof params === 'undefined') return []
      const arr = params.map(p => {
        if (typeof p.schema !== 'undefined' && p.schema.originalRef) {
          const ref = p.schema.originalRef
          p.children = [] as any[]
          const properties = (this.definitions as any)[ref]?.properties
          console.log(properties, 'properties')
          properties && Object.entries(properties).forEach(property => {
            p.children.push({
              name: property[0],
              ...(property[1] as Schema)
            })
          })
          p.children = this.setParams(p.children)
        }
        return p
      })
      return arr
    },
    getParameters (params: any[]) {
      return this.setParams(params)
    },
    // 获取响应参数
    getResponseParameterData (obj: any) {
      const data = [] as any[]
      if (obj.schema?.items?.originalRef) {
        const ref = obj.schema.items.originalRef
        const params = (this.definitions as any)[ref].properties
        Object.entries(params).forEach(p => {
          let obj = {} as {
            name: string,
            description: string,
            schema: any,
            type: string
          }
          const name = p[0]
          const { description, schema, type } = p[1] as Schema
          obj = { name, description, schema, type }
          data.push(obj)
        })
      }
      return data
    },
    // 获取相应结果
    getResponseData (val: any) {
      const data = [] as Response[]
      Object.entries(val).forEach(v => {
        const obj = {} as {
          status: string,
          description: string,
          schema: any
        }
        obj.status = v[0]
        obj.description = (v[1] as Response).description
        obj.schema = (v[1] as Response).schema ? (v[1] as Response).schema.type : ''
        data.push(obj)
      })
      return data
    },
    // 获取url列表
    getPathList (tagName: string) {
      const apiObj = this.generatePathList[tagName]
      const arr: [string, Method, PathDetail][] = []
      Object.entries(apiObj).forEach(a => {
        a[1].forEach(j => {
          arr.push([a[0], j[0], j[1]])
        })
      })
      return arr
    }
  }
})
</script>
<style lang="less">
.ant-table-placeholder {
  padding: 4px;
  .ant-empty {
    &.ant-empty-normal  {
      margin: 8px;
    }
  }
}

</style>
