import { graphql } from '@/services/mgr/api';
import type { RequestOptionsType } from '@ant-design/pro-utils';

async function getSingleTable(code: string) {
  const gqlString = `query{
  singleTable(specification:{
  code:{
      _v:eq,
      _val:"${code}"
  }
  }){
  id,code,name,description,canCreate,canEdit,canRemove,canImport,canExport,orders,scroll,createAccess,editAccess,removeAccess,importAccess,
  entityMetadata{
      id,code,name,description,type
      propertys{
      id,code,name,description,type,genericType
      }
  },
  fields{
      id,code,name,ordinal,valueType,dataType,hideInSearch,hideInTable,hideInCreateForm,hideInEditForm,required,width,colSize,keys,display
  }
  }
}`;
  const graphqlParams = {
    operationName: null,
    variables: {},
    query: gqlString,
  };
  return await graphql(graphqlParams);
}

async function getEnumList(enumType: string, keys: string, display: string) {
  const keyList = keys.split(',');
  const displayList = display.split(',');
  const specfication =
    'id,' + keyList.concat(displayList.filter((v) => !keyList.includes(v))).join(',');
  const gqlString = `query{${enumType}{${specfication}}}`;
  const graphqlParams = {
    operationName: null,
    variables: {},
    query: gqlString,
  };
  const reqData = await graphql(graphqlParams);
  return reqData.data[enumType] as any[];
}

async function getEnumSelectOptions(enumType: string, keys: string, display: string) {
  const enumList = await getEnumList(enumType, keys, display);
  const displayList = display.split(',');
  return enumList.map((em) => {
    const option: RequestOptionsType = {
      value: em.id,
      label: displayList.map((d) => em[d]).join('-'),
    };
    return option;
  });
}

export { getSingleTable, getEnumList, getEnumSelectOptions };
