import { Address } from "@/types/tdt";
import { defineStore } from "pinia";

type RecvAddr = {
  fullAddress: string;
  name: string;
  phone: string;
  isDefault: boolean;
}

type UserState = {
  token: string;
  location: {
    address: string;
    longitude: string;
    latitude: string;
  };
  deviceLocation: Address;
  recvAddrList: RecvAddr[];
}

export const useUserStore = defineStore("user", {
  persist: true,
  state: ():UserState => ({
    token: "",
    location: {
      address: "",
      longitude: "",
      latitude: "",
    },
    deviceLocation: {
      province: "",
      province_code: "",
      city: "",
      city_code: "",
      county: "",
      county_code: "",
      address: "",
      longitude: "",
      latitude: "",
      road:"",
      town:"",
      nation:"",
      poi_position:"",
      address_position:"",
      poi:"",
      town_code:"",
      road_distance:0,
      address_distance:0,
      poi_distance:0,
    },
    recvAddrList:[]
  }),
  getters: {
    getToken(state) {
      return state.token;
    },
    getAddress(state) {
      return state.location.address;
    },
    getCoordinate(state) {
      return { longitude: state.location.longitude, latitude: state.location.latitude };
    },
  },
  actions: {
    setToken(token: string) {
      this.token = token;
    },
    setAddress(address: string) {
      this.location.address = address;
    },
    setCoordinate(lng: string, lat: string) {
      this.location.longitude = lng;
      this.location.latitude = lat;
    },
    setDeviceAddress(params: Address) {
      let _params = Object.assign(this.deviceLocation, params);
      this.deviceLocation = _params;
    },
    setDeviceCoordinate(lng: string, lat: string) {
      this.deviceLocation.longitude = lng;
      this.deviceLocation.latitude = lat;
    },
    setRecvAddrList(list: RecvAddr[]) {
      this.recvAddrList = list;
    },
    setDefaultAddress(item: RecvAddr) {
      this.recvAddrList.forEach((addr) => {
        addr.isDefault = false;
      });
      item.isDefault = true;
    }
  },
});
