import Taro from "@tarojs/taro";
import dayjs from "dayjs";
import { createSlice } from "@reduxjs/toolkit";

import { setStorageSync, getStorageSync } from "../../utils/traoAPI";

const userInfoReducer = createSlice({
  name: "userInfo", // store的名字
  initialState: {
    id: "", // 用户ID
    mobile: "",
    nickname: "",
    headimg: "",
    birthday: dayjs().format("YYYY-MM-DD"), // 生日
    province: "", // 省
    provinceId: "",
    city: "", // 市
    cityId: "",
    area: "", // 区
    areaId: "",
    token: "", // token
    credit: 0, // 积分
    expireCredit: 0, // 过期积分
    integralText: "",
  },
  reducers: {
    setMobile(state, { payload }) {
      state.mobile = payload;
    },
    setNickname(state, { payload }) {
      state.nickname = payload;
    },
    setHeadimg(state, { payload }) {
      state.headimg = payload;
    },

    userRefresh(state, { payload }) {
      state.id = payload.id || "001";
      state.mobile = payload.mobile || "";
      state.nickname = payload.nickname || "";
      state.headimg = payload.headimg || "";
      state.birthday = payload.birthday || "";
      state.province = payload.province || "";
      state.provinceId = payload.provinceId || "";
      state.city = payload.city || "";
      state.cityId = payload.cityId || "";
      state.area = payload.area || "";
      state.areaId = payload.areaId || "";
      state.token = payload.token || "";
      state.credit = payload.credit || 0;
      state.expireCredit = payload.expireCredit || 0;
      state.integralText = payload.integralText || "";

      Taro.setStorageSync("mobile", state.mobile);
      // Taro.setStorageSync("token", state.token);
    },
    tokenRefresh(state, { payload }) {
      state.id = payload.id || "001";
      state.mobile = payload.mobile || "";
      state.nickname = payload.nickname || "";
      state.headimg = payload.headimg || "";
      state.birthday = payload.birthday || "";
      state.province = payload.province || "";
      state.provinceId = payload.provinceId || "";
      state.city = payload.city || "";
      state.cityId = payload.cityId || "";
      state.area = payload.area || "";
      state.areaId = payload.areaId || "";
      state.token = payload.token || "";
      state.credit = payload.credit || 0;
      state.expireCredit = payload.expireCredit || 0;
      state.integralText = payload.integralText || "";

      Taro.setStorageSync("mobile", state.mobile);
      // 设置token和过期时间
      let expires = new Date().getTime() + 43200000;
      setStorageSync("token", state.token, expires);
    },
  },
});

export const { setMobile, setNickname, setHeadimg, userRefresh, tokenRefresh } =
  userInfoReducer.actions;
export default userInfoReducer.reducer;
