import Vue from 'vue'
import Vuex from 'vuex'
import request from '@/utils/request'  // 导入请求工具

Vue.use(Vuex)

// 从本地存储获取初始状态
const getInitialState = () => {
  return {
    userInfo: null,
    token: '',
    isLogin: false,
    priceMode: parseInt(uni.getStorageSync('current1') || '1'), // 从本地存储获取价格模式
    priceType: parseInt(uni.getStorageSync('current2') || '1'), // 从本地存储获取价格类型
    averageRange: parseInt(uni.getStorageSync('averageRange') || '3'), // 从本地存储获取均价范围
    selectedPosition: parseInt(uni.getStorageSync('selectedPositionIndex') || '0'), // 从本地存储获取选择的位置
    freight: parseFloat(uni.getStorageSync('value3') || '0'), // 从本地存储获取运费
    minValue: parseFloat(uni.getStorageSync('value4') || '0.01') // 从本地存储获取最低值
  }
}

const store = new Vuex.Store({
  state: getInitialState(),
  mutations: {
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
    },
    SET_TOKEN(state, token) {
      state.token = token
    },
    SET_LOGIN_STATUS(state, status) {
      state.isLogin = status
    },
    updatePriceMode(state, mode) {
      state.priceMode = mode 
      uni.setStorageSync('current1', mode) // 保存到本地存储
    },
    updatePriceType(state, type) {
      state.priceType = type
      uni.setStorageSync('current2', type) // 保存到本地存储
    },
    updateAverageRange(state, range) {
      state.averageRange = range
      uni.setStorageSync('averageRange', range) // 保存到本地存储
    },
    updateSelectedPosition(state, position) {
      state.selectedPosition = position
      uni.setStorageSync('selectedPositionIndex', position) // 保存到本地存储
    },
    updateFreight(state, value) {
      state.freight = value
      uni.setStorageSync('value3', value) // 保存到本地存储
    },
    updateMinValue(state, value) {
      state.minValue = value
      uni.setStorageSync('value4', value) // 保存到本地存储
    }
  },
  actions: {
    // 检查登录状态
    checkLogin({ commit }) {
      return new Promise((resolve) => {
        const token = uni.getStorageSync('token')
        if (token) {
          commit('SET_TOKEN', token)
          commit('SET_LOGIN_STATUS', true)
          // 这里可以添加获取用户信息的请求
          resolve(true)
        } else {
          resolve(false)
        }
      })
    },
    // 修改后的微信登录Action
    async wechatLogin({ commit }, code) {
      try {
        // 使用封装的request方法
        const res = await request({
          url: '/api/wechat/login',
          method: 'POST',
          data: { code }
        })

        // 处理响应数据
        commit('SET_USER_INFO', res.data.userInfo)
        commit('SET_TOKEN', res.data.token)
        commit('SET_LOGIN_STATUS', true)
        uni.setStorageSync('token', res.data.token)
        
        return res.data
      } catch (error) {
        console.error('登录失败:', error)
        throw new Error('登录请求失败')
      }
    },
    // 退出登录
    logout({ commit }) {
      commit('SET_USER_INFO', null)
      commit('SET_TOKEN', '')
      commit('SET_LOGIN_STATUS', false)
      uni.removeStorageSync('token')
    }
  }
})

export default store