import { computed, nextTick, onMounted, ref } from "vue";
import { api as docApi } from "@/api/doc";
import { DocType } from "@/model/enum";

export function useDocApi() {
  const dataNodeType = ref("Object");
  const defaultExpandedKeys = ref([]);
  const currentNodeKey = ref(0);

  const docAppId = ref(0);
  const docAppList = ref([]);
  const docTree = ref([]);
  const docDetail = ref({
    docInfoView: {
      url: "",
      version: "",
      docName: "",
      docTitle: "",
      type: DocType.DOC,
      description: "",
      remark: "",
      requestParams: [],
      responseParams: []
    },
    docInfoConfig: {
      openProdUrl: "",
      openSandboxUrl: ""
    }
  });

  const showUrl = computed(() => {
    return (
      docDetail.value.docInfoConfig?.openProdUrl?.length > 0 &&
      docDetail.value.docInfoConfig?.openSandboxUrl?.length > 0
    );
  });

  const showProdUrl = computed(() => {
    return docDetail.value.docInfoConfig?.openProdUrl?.length > 0;
  });

  const showSandBoxUrl = computed(() => {
    return docDetail.value.docInfoConfig?.openSandboxUrl?.length > 0;
  });

  const showDoc = computed(() => {
    return docDetail.value?.docInfoView?.url?.length > 0;
  });

  const isMarkdown = computed(() => {
    return docDetail.value?.docInfoView?.type === DocType.MARKDOWN;
  });

  const isDoc = computed(() => {
    return docDetail.value?.docInfoView?.type === DocType.DOC;
  });

  /*
      参数	            类型	    是否必填	    最大长度	    描述	            示例值
      app_id	        String	是	        32	    平台分配给开发者的应用ID	2014072300007148
      method	        String	是	        128	    接口名称	alipay.trade.fastpay.refund.query
      format	        String	否	        40	    仅支持JSON	JSON
      charset	        String	是	        10	    请求使用的编码格式，如utf-8,gbk,gb2312等	utf-8
      sign_type	    String	是	        10	    商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2	RSA2
      sign	        String	是	        344	    商户请求参数的签名串，详见签名	详见示例
      timestamp	    String	是	        19	    发送请求的时间，格式"yyyy-MM-dd HH:mm:ss"	2014-07-24 03:07:50
      version	        String	是	        3	    调用的接口版本，固定为：1.0	1.0
      app_auth_token	String	否	        40	    详见应用授权概述
      biz_content	    String	是		请求参数的集合，最大长度不限，除公共参数外所有请求参数都必须放在这个参数中传递，具体参照各产品快速接入文档
   */
  const commonParams = ref([
    {
      name: "app_id",
      type: "String",
      maxLength: 32,
      required: 1,
      description: "应用id",
      example: "2014072300007148"
    },
    {
      name: "method",
      type: "String",
      maxLength: 128,
      required: 1,
      description: "接口名称",
      example: "shop.order.create"
    },
    {
      name: "format",
      type: "String",
      maxLength: 40,
      required: 0,
      description: "返回结果格式,JSON/XML,固定填:JSON",
      example: "JSON"
    },
    {
      name: "charset",
      type: "String",
      maxLength: 10,
      required: 1,
      description: "请求使用的编码格式，如utf-8,gbk,gb2312等",
      example: "utf-8"
    },
    {
      name: "sign_type",
      type: "String",
      maxLength: 10,
      required: 1,
      description: "商户生成签名字符串所使用的签名算法类型,固定填:RSA2",
      example: "RSA2"
    },
    {
      name: "sign",
      type: "String",
      maxLength: 344,
      required: 1,
      description: "商户请求参数的签名串，详见签名",
      example: ""
    },
    {
      name: "timestamp",
      type: "String",
      maxLength: 19,
      required: 1,
      description: `发送请求的时间，格式"yyyy-MM-dd HH:mm:ss"`,
      example: "2014-07-24 03:07:50"
    },
    {
      name: "version",
      type: "String",
      maxLength: 3,
      required: 1,
      description: "调用的接口版本，固定为：1.0",
      example: "1.0"
    },
    {
      name: "app_auth_token",
      type: "String",
      maxLength: 40,
      required: 0,
      description: "详见应用授权概述",
      example: "xxxx"
    },
    {
      name: "biz_content",
      type: "String",
      maxLength: "不限",
      required: 1,
      description:
        "请求参数的集合，最大长度不限，除公共参数外所有请求参数都必须放在这个参数中传递，具体参照各产品快速接入文档",
      example: ""
    }
  ]);
  const resultData = ref([
    {
      name: "code",
      type: "String",
      description: `网关返回码`,
      example: `40004`
    },
    {
      name: "msg",
      type: "String",
      description: `网关返回码描述`,
      example: `Business Failed`
    },
    {
      name: "sub_code",
      type: "String",
      description: `业务返回码，参见具体的API接口文档`,
      example: `isv.invalid-parameter`
    },
    {
      name: "sub_msg",
      type: "String",
      description: `业务返回码描述，参见具体的API接口文档`,
      example: `参数不正确`
    },
    {
      name: "data",
      type: "Object",
      description: "返回数据，见下表 业务返回参数",
      example: ""
    }
  ]);

  /*function onMenuClick(index) {
    if (index.endsWith(".md")) {
      this.loadMarkdown(index);
    }
  }

  function loadMarkdown(path) {
    this.getFile(`static/openapi/${path}?q=${new Date().getTime()}`, cont => {
      content.value = cont;
      contentShow.value = true;
    });
  }*/

  function handleChangeDocApp(id) {
    loadDocTree(id);
  }

  function handleNodeClick(node) {
    if (node.isFolder === 1) {
      return;
    }
    const params = {
      id: node.id
    };
    docApi.getDocDetail(params).then(resp => {
      docDetail.value = resp.data;
    });
  }

  function loadDocApp() {
    docApi.listApp().then(resp => {
      docAppList.value = resp.data;
      if (docAppList.value.length > 0) {
        loadDocTree(docAppList.value[0].id);
      }
    });
  }

  function loadDocTree(id) {
    docAppId.value = id;
    const params = {
      docAppId: id
    };
    docApi.listDocTree(params).then(resp => {
      docTree.value = resp.data;
      // 默认展开并选中第一个
      if (docTree.value?.length > 0) {
        defaultExpandedKeys.value.push(docTree.value[0].docId);
        const children = docTree.value[0]?.children;
        if (children && children.length > 0) {
          nextTick(() => {
            const firstNode = children[0];
            currentNodeKey.value = firstNode.docId;
            handleNodeClick(firstNode);
          });
        }
      }
    });
  }

  onMounted(() => {
    loadDocApp();
  });

  return {
    isMarkdown,
    isDoc,
    docDetail,
    commonParams,
    dataNodeType,
    resultData,
    handleChangeDocApp,
    docAppId,
    docAppList,
    docTree,
    handleNodeClick,
    showUrl,
    showProdUrl,
    showSandBoxUrl,
    showDoc,
    defaultExpandedKeys,
    currentNodeKey
  };
}
