const { getHostApi } = require("@/server/utils/store");
import { Loading } from "element-ui";
const { pathMap } = require("@/config/index.js");

import { downloadImage, downloadOtherImage } from "@/server/utils";
import axios from "../utils/axios";
let loading;

function startLoading() {
  loading = Loading.service({
    lock: true,
    text: "拼命加载中...",
    spinner: "el-icon-loading",
    background: "rgba(0,0,0,.7)"
  });
}

function endLoading() {
  loading.close();
}

axios.defaults.timeout = 12600000;

// ===================== 订单查询相关 =====================
const QUERY_ORDER_API_MAP = {
  CN: {
    path: "factory/podJomallOrderProductCn/getProductCnByFactorySubOrderNumber",
    paramKey: "factorySubOrderNumber" // 参数名：工厂子订单号
  },
  US: {
    path: "factory/podJomallOrderProductUs/getProductUsByFactorySubOrderNumber",
    paramKey: "factorySubOrderNumber" // 参数名：工厂子订单号
  },
  GC: {
    path: "factory/podJomallOrderProduct/getSubOrderByThirdSubOrderNumber",
    paramKey: "thirdSubOrderNumber" // 参数名：第三方子订单号（老pod）
  }
};
/**
 * 通用查询订单接口
 * @param {string} type - 订单类型（CN/US/GC，GC代表老pod）
 * @param {string} orderNumber - 订单号（根据type自动匹配参数名：factorySubOrderNumber/thirdSubOrderNumber）
 * @returns {Promise} axios请求Promise对象
 * @throws {Error} 类型不支持/参数缺失时抛出异常
 */
export function findByPodProductionNoApi(orderNumber) {
  // 1. 前置参数校验
  if (!orderNumber.orderType) {
    throw new Error("查询订单失败：订单类型type为必传项（支持CN/US/GC）");
  }

  // 2. 校验订单类型是否支持
  const apiConfig = QUERY_ORDER_API_MAP[orderNumber.orderType];
  if (!apiConfig) {
    throw new Error(
      `查询订单失败：不支持的订单类型${orderNumber.orderType}，仅支持CN/US/GC`
    );
  }

  // 3. 构造请求参数（根据类型自动匹配参数名）
  const requestParams = {
    [apiConfig.paramKey]: orderNumber.thirdSubOrderNumber,
    resizable: orderNumber.resizable
  };

  // 4. 获取基地址并发送GET请求
  const env = getHostApi().apiApiHost;
  return axios.get(apiConfig.path, {
    baseURL: env,
    params: requestParams
  });
}
// ===================== 素材下载相关 =====================
const downloadDesignImagesBaseApi = (urlPath, params) => {
  const env = getHostApi().apiApiHost;
  // 空值校验：避免params.ids不存在导致的报错
  const requestData = Array.isArray(params?.ids) ? [...params.ids] : [];

  return axios.post(urlPath, requestData, { baseURL: env, skipLoading: true });
};

/**
 * 根据子订单号下载素材
 * @param {string} type - 订单类型（CN/US/GC/USHLC/CNHLC）
 * @param {object} params - 请求参数（包含ids数组）
 * @param {number} device - 设备类型（2/3）
 * @returns {Promise} 下载结果
 */
export async function downloadBySubOrderNumberApi(params) {
  try {
    startLoading();
    // 2. 处理设备类型为3时的订单类型映射（惠立彩）
    let targetType = params.orderType;
    if (params.device === 3) {
      targetType = params.orderType === "CN" ? "CNHLC" : "USHLC";
    }
    // 4. 发送请求获取下载链接
    const { data, message } = await downloadDesignImagesBaseApi(
      pathMap["downloadBySubOrderNumber"][targetType],
      params
    );
    // 建议明确获取响应data（根据实际axios响应结构调整）

    // 5. 处理响应数据
    // 转义中文
    let changeMessage;
    if (message) {
      changeMessage = encodeURIComponent(message);
    }

    let files = data || [changeMessage];

    // 6. 构建下载文件列表
    const fileEnv = getHostApi().fileApiUrl;

    files = files.map(el => ({ url: `${fileEnv}${el}` }));
    console.log(106, files);
    const downloadFunc =
      params.device === 2 ? downloadOtherImage : downloadImage;
    const downloadResult = await downloadFunc(files);

    return {
      code: 200,
      message: "下载成功",
      data: downloadResult
    };
  } catch (error) {
    // 统一错误处理：便于调试和用户提示
    console.error("下载素材失败：", error);
    // 可根据业务需求返回错误信息或重新抛出
    throw new Error(`下载失败：${error.message}`);
  } finally {
    endLoading();
  }
}

// ===================== 订单完成相关 =====================
/**
 * 通用完成订单接口
 * @param {string} type - 订单类型（CN/US/GC，GC代表老pod）
 * @param {object} params - 完成订单的请求参数
 * @returns {Promise} axios请求Promise对象
 * @throws {Error} 类型不支持/参数错误时抛出异常
 */
export function completeDeliveryApi(params) {
  const COMPLETE_DELIVERY_API_MAP = {
    CN: {
      data: {
        id: params.id,
        podJomallOrderCnId: params.podJomallOrderCnId || ""
      },
      url: "factory/podJomallOrderProductCn/completeDelivery"
    },
    US: {
      data: {
        id: params.id,
        podJomallOrderUsId: params.podJomallOrderUsId || ""
      },
      url: "factory/podJomallOrderProductUs/completeDelivery"
    },
    GC: {
      data: { id: params.id },
      url: "factory/podJomallOrderProduct/completeDelivery"
    }
  };

  // 2. 校验订单类型是否支持
  const apiPath = COMPLETE_DELIVERY_API_MAP[params.orderType];

  // 3. 获取基地址并发送请求
  const env = getHostApi().apiApiHost;
  return axios.post(apiPath.url, apiPath.data, { baseURL: env });
}

export function checkUpdate(version) {
  return axios.get(
    `https://admin.jomalls.com/api/manage/rest/app/checkUpdate`,
    {
      params: {
        businessType: "production_assistant",
        version
      }
    }
  );
}

export function getAllCountryApi(thirdSubOrderNumber) {
  return axios.get(`logisticsAddress/getAllCountry`, {
    params: {
      thirdSubOrderNumber
    }
  });
}
