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 queryToSend(params) {
  try {
    const {
      data: { current, records, total, size },
    } = await request.post('/api/merchants/orders/list', {
      prefix: config.kdspApi,
      data: stringify(_.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 queryExpress() {
  try {
    const { data } = await request.get('/api/merchants/companies/list', {
      prefix: config.kdspApi,
    });
    return data;
  } catch (error) {
    return {};
  }
}

export async function getGoods(orderId) {
  const { data } = await request.get(`/api/merchants/orders/skus/list?orderId=${orderId}`, {
    prefix: config.kdspApi,
  });
  return data;
}
export async function uploadFile(file) {
  const params = new FormData();
  params.append('file', file);
  const data = await request.post('/api/merchants/orders/deliveries/batches/import', {
    data: params,
    prefix: config.kdspApi,
  });
  return data;
}
export function downTemplate() {
  window.location.href = 'https://sc-img.q-gp.com/orders/templates/batch_deliveriesV2.xlsx';
}
export async function downOrder(params) {
  const data = await request.post('/api/merchants/orders/export', {
    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 queryToBatchSend(params) {
  const transformedParam = {
    pageNo: params.current,
    pageSize: params.pageSize || 20,
    startTime: params.dateTimeRange?.[0],
    endTime: params.dateTimeRange?.[1],
    status: params?.status ?? 99,
    batchNo: params.batchNo,
  };
  const {
    data: { current, records, total, size },
  } = await request.get('/api/merchants/deliveries/batchlist', {
    prefix: config.kdspApi,
    params: _.omitBy(transformedParam, v => !v),
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  });
  return {
    current,
    data: records.map(v => ({ ...v })),
    total,
    pageSize: size,
  };
}
export async function downUploadeOrder(params) {
  const data = await request.get('/api/merchants/deliveries/batchexport', {
    params,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    prefix: config.kdspApi,
    responseType: 'arrayBuffer',
  });
  const blob = new Blob([data]);
  const status = {
    0: '失败数据',
    1: '成功数据',
    2: '全部数据',
  };
  saveAs(blob, `批量发货-${status[params.status]}-${format(new Date(), 'yyyyMMddHHmmss')}.xlsx`);
}
// 延迟发货
export function apiDelayDeliverGoods(data) {
  return request.post('/api/merchants/orders/logs/add', {
    data,
    prefix: config.kdspApi,
  });
}

/**
 * 多物流发货-查询多物流订单信息
 * @param {*} params
 * @returns
 * @see http://yapi.quantgroups.com/project/389/interface/api/45840
 */
export function apiQueryOrderInfo(params) {
  return request.get('/api/merchants/orders/deliveries/packages/detail', {
    params,
    prefix: config.kdspApi,
  });
}
/**
 * 多物流发货-新建发货/更新发货信息
 * @param {*} data
 * @returns
 * @see http://yapi.quantgroups.com/project/389/interface/api/45816
 */
export function apiDeliveriesAdd(data) {
  return request.post('/api/merchants/orders/deliveries/add', {
    data,
    prefix: config.kdspApi,
  });
}

export function apiDeliveriesEdit(data) {
  return request.post('/api/merchants/orders/deliveries/edit', {
    data,
    prefix: config.kdspApi,
  });
}

/**
 * 多物流发货-查询物流轨迹
 * @see http://yapi.quantgroups.com/project/389/interface/api/46120
 */

export function apiDeliveriesTraceList(data) {
  return request.post('/api/merchants/deliveries/traces/list', {
    data: stringify(data),
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    prefix: config.kdspApi,
  });
}

/**
 * 查询订单收货信息
 * @see http://yapi.quantgroups.com/project/389/interface/api/72539
 */
export function apiQueryReceiverDetail(orderNo) {
  return request.get('/api/merchants/orders/receiver/detail', {
    params: { orderNo },
    prefix: config.kdspApi,
  });
}

/**
 * 获取商家修改收件人手机号操作日志
 * @see http://yapi.quantgroups.com/project/389/interface/api/72544
 */
export function apiQueryModifyReceiverMobileLog(orderNo) {
  const transformedParam = {
    pageNo: 1,
    pageSize: 100,
    orderNo,
  };
  return request.get('/api/merchants/orders/modify-receiver-mobile/page', {
    prefix: config.kdspApi,
    params: transformedParam,
  });
}

/**
 * 修改收件人手机号
 * @see http://yapi.quantgroups.com/project/389/interface/api/72549
 */
export function apiChangeReceiverMobile(params) {
  return request.post('/api/merchants/orders/receiver-mobile/edit', {
    prefix: config.kdspApi,
    data: params,
  });
}
