import { stringify } from 'querystring';
import _ from 'lodash';
import request from '@/utils/request';
import { saveAs } from 'file-saver';
import { format } from 'date-fns';
import config from '../../../config/env.config';
// 分页查询
export async function query(data) {
  const params = {
    ...data,
    pageNo: data.current,
    startDate: data.settlementTime?.[0],
    endDate: data.settlementTime?.[1],
    pageFlag: 4,
  };
  try {
    const {
      data: { current, records, total, size },
    } = await request.get('/api/kdsp/settlement/wait-confirm/page/query', {
      prefix: config.kdspApi,
      params: _.omitBy(params, v => !v),
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    });
    return {
      current,
      data: records.map(v => ({ ...v, logisticsStatus: `_${v.logisticsStatus}` })),
      total,
      pageSize: size,
    };
  } catch (error) {
    return {};
  }
}

export async function updateStatus(params) {
  const data = await request.post('/api/kdsp/settlement/status/update', {
    prefix: config.kdspApi,
    data: stringify(_.omitBy(params, v => !v)),
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  });
  return data;
}

export async function uploadFile(file, settlementNo) {
  const params = new FormData();
  params.append('file', file);
  params.append('settlementNo', settlementNo);

  const data = await request.post('/api/kdsp/settlement/doc/upload', {
    data: params,
    prefix: config.kdspApi,
  });
  return data;
}

export async function download(params) {
  const data = await request.post('/api/kdsp/settlement/detail/download/v1', {
    data: stringify(_.omitBy(params, v => !v)),
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    prefix: config.kdspApi,
    responseType: 'arrayBuffer',
  });
  const blob = new Blob([data]);
  saveAs(blob, `商户货款结算明细-${format(new Date(), 'yyyyMMddHHmmss')}.xlsx`);
}
// 附件信息
export async function docQuery(settlementNo) {
  const data = await request.get(`/api/kdsp/settlement/doc/query?settlementNo=${settlementNo}`, {
    prefix: config.kdspApi,
  });
  if (data.businessCode === '0000') {
    return data.data;
  }
  return [];
}

export async function uploadPic(params) {
  const data = await request.post('/api/kdsp/settlement/invoice/img/upload', {
    prefix: config.kdspApi,
    data: stringify(_.omitBy(params, v => !v)),
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  });
  return data;
}
