import axios from 'axios';
import { useUserStore } from '@/store/modules/user';
import router from '@/router';

const baseApiUrl = import.meta.env.VITE_BASE_API_URL;

// 添加响应拦截器
axios.interceptors.response.use(
  (response) => {
    // 如果响应数据中 code 为 -1，清空登录状态并跳转到登录页
    if (response?.data?.code === -1) {
      const userStore = useUserStore();
      userStore.clearLoginStatus(); // 清空用户信息
      router.push('/login'); // 直接使用路由实例
      console.error('请求失败:', response.data.msg);
    }
    return response;
  },
  (error) => {
    return Promise.reject(error);
  },
);

export const userLogin = async (data: {
  code?: string;
  password?: string;
  phone?: string;
  type?: 0 | 1;
}) => {
  try {
    const response = await axios.post(baseApiUrl + 'boyanghu/iotree-service/platform/login', data, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    });
    return response.data;
  } catch (error) {
    console.error('登录请求失败:', error);
    throw error;
  }
};

export const sendVerificationCode = async (data: { phone: string }) => {
  try {
    const response = await axios.post(baseApiUrl + 'boyanghu/iotree-service/platform/send', data, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    });
    return response.data;
  } catch (error) {
    console.error('获取验证码请求失败:', error);
    throw error;
  }
};

export const addDevice = async (data: {
  brand?: string;
  deviceId?: number;
  id?: number;
  installPosition?: string;
  installTime?: string;
  maintainTime?: string;
  remarks?: string;
  type?: string;
  voltage?: string;
}) => {
  try {
    const userStore = useUserStore();
    const token = userStore.token;
    const response = await axios.post(
      baseApiUrl + 'boyanghu/iotree-service/platform/device/add',
      data,
      {
        headers: {
          'Content-Type': 'application/json',
          token: token,
        },
      },
    );
    return response.data;
  } catch (error) {
    console.error('新增设备请求失败:', error);
    throw error;
  }
};

export const getDeviceList = async (data?: {
  brand?: string;
  deviceId?: number;
  id?: number;
  installPosition?: string;
  installTime?: string;
  maintainTime?: string;
  remarks?: string;
  type?: string;
  voltage?: string;
}) => {
  try {
    const userStore = useUserStore();
    const token = userStore.token;
    const response = await axios.post(
      baseApiUrl + 'boyanghu/iotree-service/platform/device/list',
      data,
      {
        headers: {
          'Content-Type': 'application/json',
          token: token,
        },
      },
    );
    return response.data;
  } catch (error) {
    console.error('获取设备列表请求失败:', error);
    throw error;
  }
};

export const editDevice = async (data: {
  brand?: string;
  deviceId?: number;
  id: number;
  installPosition?: string;
  installTime?: string;
  maintainTime?: string;
  remarks?: string;
  type?: string;
  voltage?: string;
}) => {
  try {
    const userStore = useUserStore();
    const token = userStore.token;
    const response = await axios.post(
      baseApiUrl + 'boyanghu/iotree-service/platform/device/edit',
      data,
      {
        headers: {
          'Content-Type': 'application/json',
          token: token,
        },
      },
    );
    return response.data;
  } catch (error) {
    console.error('编辑设备请求失败:', error);
    throw error;
  }
};

export const getDeviceById = async (id: number) => {
  try {
    const userStore = useUserStore();
    const token = userStore.token;
    const response = await axios.post(
      baseApiUrl + 'boyanghu/iotree-service/platform/device/list',
      { id },
      {
        headers: {
          'Content-Type': 'application/json',
          token: token,
        },
      },
    );
    return response.data;
  } catch (error) {
    console.error('获取设备记录失败:', error);
    throw error;
  }
};

export const userLogout = async () => {
  try {
    const userStore = useUserStore();
    const token = userStore.token;
    const response = await axios.post(
      baseApiUrl + 'boyanghu/iotree-service/platform/outLogin',
      {},
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          token: token,
        },
      },
    );
    return response.data;
  } catch (error) {
    console.error('退出登录请求失败:', error);
    throw error;
  }
};

export const deleteDevice = async (data: { id: number }) => {
  try {
    const userStore = useUserStore();
    const token = userStore.token;
    const response = await axios.post(
      baseApiUrl + 'boyanghu/iotree-service/platform/device/delete',
      data,
      {
        headers: {
          'Content-Type': 'application/json',
          token: token,
        },
      },
    );
    return response.data;
  } catch (error) {
    console.error('删除设备请求失败:', error);
    throw error;
  }
};

export const addDeviceWarning = async (data: {
  branchId?: number;
  deviceId?: number;
  id?: number;
  installPosition?: string;
  threshold1?: number;
  threshold2?: number;
  threshold3?: number;
}) => {
  try {
    const userStore = useUserStore();
    const token = userStore.token;
    const response = await axios.post(
      baseApiUrl + 'boyanghu/iotree-service/platform/device/warning/add',
      data,
      {
        headers: {
          'Content-Type': 'application/json',
          token: token,
        },
      },
    );
    return response.data;
  } catch (error) {
    console.error('新增设备警告请求失败:', error);
    throw error;
  }
};

export const getDeviceWarningList = async (data: {
  branchId?: number;
  deviceId?: number;
  installPosition?: string;
  pageNum?: number;
  pageSize?: number;
}) => {
  try {
    const userStore = useUserStore();
    const token = userStore.token;
    const response = await axios.post(
      baseApiUrl + 'boyanghu/iotree-service/platform/device/warning/list',
      data,
      {
        headers: {
          'Content-Type': 'application/json',
          token: token,
        },
      },
    );
    return response.data;
  } catch (error) {
    console.error('获取设备警告列表请求失败:', error);
    throw error;
  }
};

export const getDeviceWarningById = async (id: number) => {
  try {
    const userStore = useUserStore();
    const token = userStore.token;
    const response = await axios.post(
      baseApiUrl + 'boyanghu/iotree-service/platform/device/warning/list',
      { id },
      {
        headers: {
          'Content-Type': 'application/json',
          token: token,
        },
      },
    );
    return response.data;
  } catch (error) {
    console.error('获取设备警告列表请求失败:', error);
    throw error;
  }
};

export const deleteDeviceWarning = async (data: { id: number }) => {
  try {
    const userStore = useUserStore();
    const token = userStore.token;
    const response = await axios.post(
      baseApiUrl + 'boyanghu/iotree-service/platform/device/warning/delete',
      data,
      {
        headers: {
          'Content-Type': 'application/json',
          token: token,
        },
      },
    );
    return response.data;
  } catch (error) {
    console.error('删除设备警告请求失败:', error);
    throw error;
  }
};

export const editDeviceWarning = async (data: {
  branchId?: number;
  deviceId?: number;
  id?: number;
  installPosition?: string;
  threshold1?: number;
  threshold2?: number;
  threshold3?: number;
}) => {
  try {
    const userStore = useUserStore();
    const token = userStore.token;
    const response = await axios.post(
      baseApiUrl + 'boyanghu/iotree-service/platform/device/warning/edit',
      data,
      {
        headers: {
          'Content-Type': 'application/json',
          token: token,
        },
      },
    );
    return response.data;
  } catch (error) {
    console.error('编辑设备警告请求失败:', error);
    throw error;
  }
};
