import { onMounted, ref, watch, getCurrentInstance } from "vue";
import { ActionType, PageContentProps } from "../types";
import { mapActionToApi } from "../utils/create-operation";
import { mergeParams } from "../utils/merge-params";
import { responseHandle } from "/@/utils/responseHandle";
import { handleTree } from "@pureadmin/utils";
import { usePagination } from "./use-pagination";
import { useCompany } from "/@/hooks/core/useCompany";
import { useNav } from "/@/layout/hooks/nav";
import { useParams } from "./use-params";
import { useUserInfo } from "/@/hooks/core/useUser";
import { httpSupplierList } from "/@/api/supplierManage/supplierAccoutManage";
import { httpCompanyList } from "/@/api/InvoiceSales/invoiceApply";

export function useRequeset(props: PageContentProps) {
  const { contentConfig , otherSearchParameter } = props;
  const { mockData, notNeedCompanyFilter } = contentConfig;

  const { logout } = useNav();
  const loading = ref(false);
  const dataList = ref(mockData ? mockData : []);
  const initRequest = ref(!props.contentConfig.notReuqiredInit);

  const { currentCompany } = useCompany();
  const { isSuperUser } = useUserInfo();

  const { getBasicParams, changeBasicParams } = useParams();
  const paginationConfig = usePagination(props, {
    onSearch
  });

  const { changePagination, getPagination } = paginationConfig;

  async function onSearch() {
    const { contentConfig } = props;
    const { apis, isTree, mockData, listNoRelation, transformCompany, transformField, transformFieldCompany, notDeleteCompanyrProp } = contentConfig;
    const hasCompanyFilter = !notNeedCompanyFilter;
    const vm = getCurrentInstance();

    const companyProp = contentConfig.companyProp
      ? contentConfig.companyProp
      : "companyNo";

    if (!initRequest.value || mockData) return (initRequest.value = true);

    loading.value = true;


    let transCompany = ""
    if (transformCompany || transformField) {
      const { data } = await httpSupplierList({ name: currentCompany.value?.companyName })
      const item = currentCompany.value?.companyName ? data.list.find(item => item.name === currentCompany.value?.companyName) || {} : {};
      transCompany = item.code;
    }

    const params = mergeParams({
      pagination: getPagination ? getPagination() : {},
      basicParams: getBasicParams(),
      company: hasCompanyFilter
        ? { [companyProp]: transformCompany ? transCompany : currentCompany.value.companyNo }
        : {}
    });


    if (transformFieldCompany && params['companyNo']) {
      const { data } = await httpCompanyList({ size: 1000 })
      const name = (data.list.find(({ companyNo }) => companyNo === params['companyNo']) || {}).company_name
      const { data: rdata } = await httpSupplierList({ name })
      const item = name ? rdata.list.find(item => item.name === name) || {} : {};
      params['supplierNo'] = item.code;
      delete params['companyNo']
    }

    if (transformField) {
      params[transformField] = transCompany;
      !notDeleteCompanyrProp && delete params[companyProp];
    }


    console.log(otherSearchParameter, '🚀')
    const { code, data, message } = await apis.httpList({ ...params, ...(otherSearchParameter || {}) ,...(listNoRelation ? { noRela: true } : {}) });


    responseHandle({
      code,
      message,
      logout,
      handler: () => {
        const _list = Array.isArray(data) ? data : data.list;

        let list = contentConfig.handleData
          ? contentConfig.handleData(_list, params)
          : _list;

        if (list instanceof Promise) {
          list.then(res => {
            list = res;
            dataList.value = isTree ? handleTree(list ?? []) : list;
            changePagination("total", data.count);
            props.onGetReuslt && props.onGetReuslt(data);
            props.onGetHandleResult && props.onGetHandleResult(list);
          });
        } else {
          dataList.value = isTree ? handleTree(list ?? []) : list;
          changePagination("total", data.count);
          props.onGetReuslt && props.onGetReuslt(data);
          props.onGetHandleResult && props.onGetHandleResult(list);
        }
      }
    });

    loading.value = false;
  }

  async function onSearchPro(params = {}) {
    const { contentConfig } = props;
    const { apis, isTree } = contentConfig;
    loading.value = true;
    const { code, data, message } = await apis.httpList({
      ...params
    });

    responseHandle({
      code,
      message,
      logout,
      handler: () => {
        const _list = Array.isArray(data) ? data : data.list;

        let list = contentConfig.handleData
          ? contentConfig.handleData(_list)
          : _list;

        if (list instanceof Promise) {
          list.then(res => {
            list = res;
            dataList.value = isTree ? handleTree(list ?? []) : list;
            changePagination("total", data.count);
            props.onGetReuslt && props.onGetReuslt(data);
            props.onGetHandleResult && props.onGetHandleResult(list);
            loading.value = false;
          });
        } else {
          dataList.value = isTree ? handleTree(list ?? []) : list;
          changePagination("total", data.count);
          props.onGetReuslt && props.onGetReuslt(data);
          props.onGetHandleResult && props.onGetHandleResult(list);
          loading.value = false;
        }
      }
    });
  }

  /**
   * 外部使用的请求方法
   */
  function getPageData(parmas: any = {}) {
    changePagination && changePagination("currentPage", 1);
    changeBasicParams && changeBasicParams(parmas);
    onSearch();
  }

  /**
   * 外部action执行传入数据发起请求
   */
  async function onBeforeAction(
    action: ActionType,
    data: any = {},
    responseCallback?: () => void
  ) {
    const { contentConfig } = props;
    const { apis } = contentConfig;
    const key = mapActionToApi[action];

    loading.value = true;

    const { code, message } = await apis[key](data);

    responseCallback && responseCallback();

    responseHandle({
      code,
      message,
      logout,
      handler: () => onSearch()
    });

    loading.value = false;
  }

  //初始化数据
  onMounted(() => onSearch());

  watch(
    () => currentCompany.value,
    () => {
      if (!notNeedCompanyFilter && isSuperUser.value) {
        onSearch();
      }
    }
  );

  return {
    loading,
    dataList,
    getBasicParams,
    getPagination,
    onBeforeAction,
    paginationConfig,
    getPageData,
    onSearch,
    onSearchPro
  };
}
