import { defHttp } from '@/utils/http/axios';
import qs from 'qs';
import { get } from 'lodash-es';
import buildPaginationQueryOpts from '@/utils/jhipster/sorts';
import { PageRecord } from '@/models/baseModel';
import { useMethods } from '@/hooks/system/useMethods';
import { I<%= entityAngularName %> } from '@/models/<%= entityModelFileName %>.model';
<%_ if (applicationType === 'gateway' && false) { _%>
import { store } from '@/store';
<%_ } _%>
<%_ if (addCustomMethod.indexOf('clientService') !== -1) { _%>
<%- include(`../common/entity-custom/${entityClass}.clientService.ejs`, {position: 'import'}); -%>
<%_ } _%>
<%_
const baseApi = ((applicationType === 'gateway' && locals.microserviceName) ? 'services/' + microserviceName.toLowerCase() + '/api/' : 'api/') + (entityAngularName === 'User' ? 'admin/' : '');
_%>
<%_
const baseApiUrlName = applicationType === 'gateway' ? 'this.serviceBaseApiUrl()' : 'baseApiUrl';
const baseSearchApiUrlName = applicationType === 'gateway' ? 'this.serviceBaseSearchApiUrl()' : 'baseSearchApiUrl';
_%>

const apiUrl = '/<%= baseApi + entityApiUrl %>';
<%_ if (searchEngine === 'elasticsearch') { _%>
const apiSearchUrl = '<%= baseApi %>_search/<%= entityApiUrl %>?query=';
<%_ } _%>

export default {
  // begcode-please-regenerate-this-file 如果您不希望重新生成代码时被覆盖，将please修改为don't ！！！
  <%_ if (searchEngine === 'elasticsearch') { _%>

  search(query, paginationQuery) : Promise<PageRecord<I<%= entityAngularName %>>> {
    return defHttp.get({ url: `${apiSearchUrl}${query}<% if (!paginationNo) { %>&${buildPaginationQueryOpts(paginationQuery)}<% } %>`});
  },
  <%_ } _%>

  find(id: <%- this.getTypescriptKeyType(primaryKey) %>) : Promise<I<%= entityAngularName %>> {
    return defHttp.get({ url: `${apiUrl}/<%= entityAngularName === 'User' ? 'id/' : ''%>${id}` });
  },

  retrieve(paginationQuery?: any) : Promise<PageRecord<I<%= entityAngularName %>>> {
    const options = buildPaginationQueryOpts(paginationQuery);
    return defHttp.get({ url: apiUrl<% if (!paginationNo) { %>, params: options <% } %>});
  },

  stats(queryParams?: any): Promise<any> {
    const params = buildPaginationQueryOpts(queryParams);
    return defHttp.get({ url: `${apiUrl}/stats`, params });
  },

  exist(queryParams?: any): Promise<Boolean> {
    if (!queryParams.hasOwnProperty('<%= primaryKey.name%>.aggregate.count') || !get(queryParams, '<%= primaryKey.name%>.aggregate.count')) {
      queryParams['<%= primaryKey.name%>.aggregate.count'] = true;
    }
    const options = buildPaginationQueryOpts(queryParams);
    return new Promise((resolve, reject) => {
      defHttp
          .get({ url: `${apiUrl}/stats?`, params: options })
          .then(res => { resolve(res && res[0] && res[0]['<%= primaryKey.name%>_count'] > 0)})
          .catch(err => reject(err));
    });
  },
<%_ if (softDelete && !skipSoftDelete) { _%>

  recycleBin(paginationQuery?: any) : Promise<PageRecord<I<%= entityAngularName %>[]>> {
    const options = buildPaginationQueryOpts(paginationQuery);
    return defHttp.get({ url: apiUrl + '/recycle-bin'<% if (!paginationNo) { %>, params: options<% } %>});
  },

  restoreByIds(ids: <%- this.getTypescriptKeyType(primaryKey) %>[]): Promise<I<%= entityAngularName %>> {
    return defHttp.put({ url: `${apiUrl}/recycle-bin/restore`, data: { ids }});
  },

  reallyDelete(ids: <%- this.getTypescriptKeyType(primaryKey) %>[]): Promise<I<%= entityAngularName %>> {
    return defHttp.delete({ url: `${apiUrl}/recycle-bin/delete`, params: {ids} });
  },

  emptyRecycleBin(): Promise<I<%= entityAngularName %>> {
    return defHttp.delete({ url: `${apiUrl}/recycle-bin/empty` });
  },

  findInRecycleBin(id: <%- this.getTypescriptKeyType(primaryKey) %>) : Promise<I<%= entityAngularName %>> {
    return defHttp.get({ url: `${apiUrl}/recycle-bin/<%= entityAngularName === 'User' ? 'id/' : ''%>${id}` });
  },
<%_ } _%>
<%_
    const sortFields = fields.filter(field => field.options && field.options.sortField);
    if (sortFields.length > 0) {
_%>

  updateSortValue(id: <%- this.getTypescriptKeyType(primaryKey) %>, type: 'DROP' | 'STEP' | 'VALUE', newSortValue:number, beforeId: <%- this.getTypescriptKeyType(primaryKey) %>, afterId: <%- this.getTypescriptKeyType(primaryKey) %>, <%= entityInstance %>Criteria: any ) : Promise<Boolean> {
    return defHttp.put({ url: `${apiUrl}/sort-value/${id}/${type}?newSortValue=${newSortValue || ''}&beforeId=${beforeId || ''}&afterId=${afterId || ''}`, params: <%= entityInstance %>Criteria });
  },
<%_ } _%>

  delete(id: <%- this.getTypescriptKeyType(primaryKey) %>) : Promise<any> {
    return defHttp.delete({ url: `${apiUrl}/${id}` });
  },

  deleteByIds(ids: <%- this.getTypescriptKeyType(primaryKey) %>[]): Promise<any> {
    return defHttp.delete({ url: apiUrl, params: {ids} }, { joinParamsToUrl: true });
  },
<%_ if (fieldsContainParentAndChildren) { _%>

  tree(paginationQuery?: any): Promise<PageRecord<I<%= entityAngularName %>[]>> {
    const options = buildPaginationQueryOpts(paginationQuery);
    return defHttp.get({ url: `${apiUrl}/tree`<% if (!paginationNo) { %>, params: options <% } %>});
  },

  treeByParentId(parentId: <%- this.getTypescriptKeyType(primaryKey) %>): Promise<I<%= entityAngularName %>[]> {
    return defHttp.get({ url: `${apiUrl}/${parentId}/tree` });
  },
<%_ } _%>
<%_ if (!skipRestApi || skipRestApi.indexOf('create') === -1 ) { _%>

  create(<%= entityInstance %>: I<%= entityAngularName %>) : Promise<I<%= entityAngularName %>> {
    return defHttp.post({ url: `${apiUrl}`, data: <%= entityInstance %> });
  },
<%_ } _%>

  update(<%= entityInstance %>: I<%= entityAngularName %>, batchIds?: <%- this.getTypescriptKeyType(primaryKey) %>[], batchFields?: String[]) : Promise<I<%= entityAngularName %>> {
    let queryParams = '';
    if (batchIds && batchFields) {
      queryParams = qs.stringify({ batchIds, batchFields }, { arrayFormat: 'repeat' });
    }
    return defHttp.put({ url: `${apiUrl}/${<%= entityInstance %>.<%= primaryKey.name %>}?${queryParams}`, data: <%= entityInstance %> });
  },

  updateRelations(otherEntityIds: String[], relationshipName: String, relatedIds: <%- this.getTypescriptKeyType(primaryKey) %>[], operateType: String ) : Promise<Boolean> {
    const queryParams = qs.stringify({ otherEntityIds, relatedIds, relationshipName }, { arrayFormat: 'repeat' });;
    return defHttp.put({ url: `${apiUrl}/relations/${operateType}`, params: queryParams });
  },
    <%_ if (addCustomMethod.indexOf('clientService') !== -1) { _%>
<%- include(`../common/entity-custom/${entityClass}.clientService.ejs`, {position: 'method', getTypescriptKeyType: this.getTypescriptKeyType}); -%>
    <%_ } _%>

  /**
   * 导出xls
   * @param fileName 文件名
   * @param paginationQuery 分页参数
   * @param isXlsx 是否导出xlsx
   */
  exportExcel(fileName, paginationQuery?: any, isXlsx = false) {
    const { handleExportXls, handleExportXlsx } = useMethods();
    const options = buildPaginationQueryOpts(paginationQuery);
    if (isXlsx) {
      return handleExportXlsx(fileName, `${apiUrl}/export`, options);
    } else {
      return handleExportXls(fileName, `${apiUrl}/export`, options);
    }
  },

  /**
   * 导入xls
   * @param file 导入的文件
   * @param success 成功回调
   */
  importExcel(file, success) {
    const { handleImportXls } = useMethods();
    return handleImportXls(file, `${apiUrl}/import`, success);
  },
  <%_ if (applicationType === 'gateway' && false) { _%>

  serviceBaseApiUrl() {
    return (store.getters.currentServiceConfig.microServicePath ? ('services/' + store.getters.currentServiceConfig.microServicePath) : '') + apiUrl;
  },

  serviceBaseSearchApiUrl() {
    return (store.getters.currentServiceConfig.microServicePath ? ('services/' + store.getters.currentServiceConfig.microServicePath) : '') + apiSearchUrl;
  }
  <%_ } _%>
    // jhipster-needle-service-add-method - JHipster will add getters and setters here, do not remove
}
