import request from '@/utils/request'
import axios from 'axios'
import { getToken } from '@/utils/auth'

// JD订单列表
export function listJDOrders(query) {
  return request({
    url: '/system/jdorder/list',
    method: 'get',
    params: query
  })
}

/** 快捷录单页：型号及该型号最近一次订单的付款/后返 */
export function listQuickRecordModelOptions() {
  return request({
    url: '/system/jdorder/quickRecord/modelOptions',
    method: 'get'
  })
}

/** 快捷录单页：型号后缀店铺选项（系统参数 quickRecord.modelShopOptions） */
export function listQuickRecordShopOptions() {
  return request({
    url: '/system/jdorder/quickRecord/shopOptions',
    method: 'get'
  })
}

/** 一键迁移：拆分 model_number 末尾店铺前缀到 model_shop */
export function migrateModelShopSplit() {
  return request({
    url: '/system/jdorder/migrateModelShop',
    method: 'post'
  })
}

// JD订单详情
export function getJDOrder(id) {
  return request({
    url: `/system/jdorder/${id}`,
    method: 'get'
  })
}

/**
 * 列表编辑行为 Vue 响应式对象时，axios 内部 JSON.stringify 可能遗漏部分枚举字段；
 * 先转为普通对象，并始终带上 extraCost（对应后端 JDOrder.extraCost / jd_order.extra_cost）。
 */
export function normalizeJDOrderPutPayload(data) {
  if (!data || typeof data !== 'object') return {}
  let plain
  try {
    plain = JSON.parse(JSON.stringify(data))
  } catch (e) {
    plain = Object.assign({}, data)
  }
  const pick = v => {
    if (v === undefined || v === null || v === '') return undefined
    return v
  }
  const raw =
    pick(data.extraCost) ??
    pick(data.extra_cost) ??
    pick(plain.extraCost) ??
    pick(plain.extra_cost)
  const num = raw !== undefined ? Number(raw) : NaN
  plain.extraCost = Number.isFinite(num) ? num : 0
  delete plain.extra_cost
  return plain
}

// 更新JD订单
export function updateJDOrder(data) {
  return request({
    url: '/system/jdorder',
    method: 'put',
    data: normalizeJDOrderPutPayload(data)
  })
}

// 一键转链
export function generatePromotionContent(data) {
  return request({
    url: '/jarvis/jdorder/generatePromotionContent',
    method: 'post',
    data: data
  })
}

// 创建商品（基于转链生成的文案与图片）
export function createProductByPromotion(data) {
  return request({
    url: '/erp/product/createByPromotion',
    method: 'post',
    data: data
  })
}

// 上架商品
export function publishProduct(data) {
  return request({
    url: '/erp/product/publish',
    method: 'post',
    data
  })
}

// 地区下拉
export function getProvinces() {
  return request({
    url: '/erp/region/provinces',
    method: 'get'
  })
}

export function getCities(provId) {
  return request({
    url: '/erp/region/cities',
    method: 'get',
    params: { provId }
  })
}

export function getAreas(provId, cityId) {
  return request({
    url: '/erp/region/areas',
    method: 'get',
    params: { provId, cityId }
  })
}

// 类目下拉
export function getCategories(params) {
  return request({
    url: '/erp/product/categories',
    method: 'get',
    params
  })
}

// 会员名下拉
export function getUsernames(params) {
  return request({
    url: '/erp/product/usernames',
    method: 'get',
    params
  })
}

// ERP 账号下拉（备用）
export function getERPAccounts() {
  return request({
    url: '/erp/product/ERPAccount',
    method: 'get'
  })
}

// 属性下拉
export function getProperties(params) {
  return request({
    url: '/erp/product/pv',
    method: 'get',
    params
  })
}

// 开礼金
export function createGiftCoupon(data) {
  return request({
    url: '/jarvis/jdorder/createGiftCoupon',
    method: 'post',
    data
  })
}

// 转链（支持礼金）
export function transferWithGift(data) {
  return request({
    url: '/jarvis/jdorder/transfer',
    method: 'post',
    data
  })
}

// 批量创建礼金券
export function batchCreateGiftCoupons(data) {
  return request({
    url: '/jarvis/jdorder/batchCreateGiftCoupons',
    method: 'post',
    data
  })
}

// 文本URL替换（批量创建礼金并替换）
export function replaceUrlsWithGiftCoupons(data) {
  return request({
    url: '/jarvis/jdorder/replaceUrlsWithGiftCoupons',
    method: 'post',
    data
  })
}

// 导出JD订单列表
export function exportJDOrders(query) {
  return request({
    url: '/system/jdorder/export',
    method: 'post',
    params: query
  })
}

// 删除JD订单（支持批量，ids为逗号分隔或数组）
export function delJDOrder(ids) {
  // 兼容数组或字符串
  const idPath = Array.isArray(ids) ? ids.join(',') : ids
  return request({
    url: `/system/jdorder/${idPath}`,
    method: 'delete'
  })
}

// 后返表上传记录列表
export function listGroupRebateExcelUploads(query) {
  return request({
    url: '/system/jdorder/groupRebateUpload/list',
    method: 'get',
    params: query
  })
}

/** 删除后返表上传记录，并回滚对应订单后返备注（新导入数据） */
export function deleteGroupRebateUpload(id) {
  return request({
    url: '/system/jdorder/groupRebateUpload/' + id,
    method: 'delete'
  })
}

function postGroupRebateMultipart(url, formData) {
  return axios
    .post(process.env.VUE_APP_BASE_API + url, formData, {
      headers: { Authorization: 'Bearer ' + getToken() },
      transformRequest: [
        (data, headers) => {
          if (data instanceof FormData) {
            if (headers && typeof headers.delete === 'function') {
              headers.delete('Content-Type')
            } else if (headers) {
              delete headers['Content-Type']
            }
          }
          return data
        }
      ]
    })
    .then((res) => {
      const d = res.data
      if (!d || d.code !== 200) {
        return Promise.reject(new Error((d && d.msg) || '请求失败'))
      }
      return d
    })
}

/** 导入跟团返现 Excel（multipart，单文件） */
export function importGroupRebateExcel(formData) {
  return postGroupRebateMultipart('/system/jdorder/importGroupRebateExcel', formData)
}

/** 批量导入后返表（multipart，多个 files 字段） */
export function importGroupRebateExcelBatch(formData) {
  return postGroupRebateMultipart('/system/jdorder/importGroupRebateExcelBatch', formData)
}

// 手动获取物流信息（用于调试）
export function fetchLogisticsManually(data) {
  return request({
    url: '/jarvis/jdorder/fetchLogisticsManually',
    method: 'post',
    data
  })
}

// 订单搜索工具接口（返回简易字段）
export function searchOrders(query) {
  return request({
    url: '/system/jdorder/tools/search',
    method: 'get',
    params: query
  })
}

// 批量标记后返到账（赔付金额>0的订单）
export function batchMarkRebateReceived() {
  return request({
    url: '/system/jdorder/tools/batch-mark-rebate-received',
    method: 'post'
  })
}

/** 按订单 id 批量重算售价（从型号配置回填）与利润 */
export function recalcProfitBatch(ids) {
  return request({
    url: '/system/jdorder/tools/recalc-profit',
    method: 'post',
    data: { ids }
  })
}

/** 本页订单：利润未手动的按规则重算，仅变化时落库（刷新列表后调用） */
export function syncAutoProfitBatch(ids) {
  return request({
    url: '/system/jdorder/tools/sync-auto-profit',
    method: 'post',
    data: { ids }
  })
}

// 生成录单格式文本（Excel可粘贴格式）
export function generateExcelText(query) {
  return request({
    url: '/system/jdorder/generateExcelText',
    method: 'get',
    params: query
  })
}