/**
 * 合同管理相关接口
 * 使用独立的 axios 实例，端口为 33333
 */
import axios from "axios";
import { ResultEnum } from "@/enums/httpEnum";
import { useUserStore } from "@/stores/modules/user";
import { ElMessage } from "element-plus";
import { LOGIN_URL } from "@/config";
import router from "@/routers";

// 合同接口专用配置 - 使用不同的端口
const CONTRACT_BASE_URL = "https://120.26.186.130";

// 创建专门用于合同接口的 axios 实例
// 注意：不使用 withCredentials，因为认证通过 Authorization header 传递，且服务器 CORS 配置为通配符
const contractAxios = axios.create({
  baseURL: CONTRACT_BASE_URL,
  timeout: ResultEnum.TIMEOUT as number,
  withCredentials: false
});

// 请求拦截：补充 token
contractAxios.interceptors.request.use(
  config => {
    const userStore = useUserStore();
    if (config.headers) {
      (config.headers as any).Authorization = userStore.token;
    }
    return config;
  },
  error => Promise.reject(error)
);

// 响应拦截：直接返回响应数据
contractAxios.interceptors.response.use(
  response => {
    const data = response.data;
    return data;
  },
  error => {
    ElMessage.error("请求失败，请稍后重试");
    return Promise.reject(error);
  }
);

/**
 * 获取合同列表
 * @param {string} storeId - 店铺ID
 * @param {object} params - 请求参数 { page, page_size, status, file_name }
 * @returns {Promise}
 */
export const getContractList = (storeId: string | number, params: any = {}) => {
  return contractAxios.get(`/api/store/contracts/${storeId}`, { params });
};

/**
 * 获取合同详情
 * @param {string} storeId - 店铺ID
 * @param {string} contractId - 合同ID
 * @returns {Promise}
 */
export const getContractDetail = (storeId: string | number, contractId: string | number) => {
  return contractAxios.get(`/api/store/contarcts/${storeId}/${contractId}`);
};

/**
 * 签署合同
 * @param {string} storeId - 店铺ID
 * @param {string} contractId - 合同ID
 * @param {object} data - 签署数据
 * @returns {Promise}
 */
export const signContract = (storeId: string | number, contractId: string | number, data: any = {}) => {
  return contractAxios.post(`/api/store/contarcts/${storeId}/${contractId}/sign`, data);
};

/**
 * 获取合同签署链接（查看合同）
 * @param {object} data - 请求参数 { sign_flow_id, contact_phone }
 * @returns {Promise}
 */
export const getContractSignUrl = (data: any = {}) => {
  return contractAxios.post(`/api/store/esign/signurl`, data);
};

/**
 * 获取合同详情（新接口）
 * @param {string} id - 合同ID（sign_flow_id）
 * @returns {Promise} 返回 { contract_url, sign_url, sign_flow_id, status }
 */
export const getContractDetailById = (id: string | number) => {
  return contractAxios.get(`/api/store/contracts/detail/${id}`);
};
