import { TComponentItem } from "@/types/agent";
import { EComponentType } from "@/consts/enum";
import { useComponentStore } from "@/store/componentStore";
import Taro from "@tarojs/taro";
import { useAgentStore } from "@/store/agentStore";

// 编辑微官网地图组件

export const useAddress = () => {
  const { setCurrentComponent, setInsertIndex, saveComponent } =
    useComponentStore();
    const {agent, fetchAgent} = useAgentStore()

  const saveAddress = async (
    value: Taro.chooseLocation.SuccessCallbackResult,
    component: TComponentItem
  ) => {
    if (!component?.data?.id) {
      return;
    }
    if (!value.address.length) {
      return;
    }

    const c = {
      data: {
        address: value.address,
        name: value.name,
        latitude: value.latitude,
        longitude: value.longitude,
        id: component?.data?.id,
        index: component?.data?.index,
      },
      enabled: component?.enabled ?? true,
      type: EComponentType.address,
    };

    await saveComponent(c);
  };

  const handleChooseAddress = async (value: any, c: TComponentItem) => {
    setInsertIndex(-1);
    setCurrentComponent(c);

    const option = {
      address: value.address,
      latitude: value.latitude,
      longitude: value.longitude,
      async success(result: Taro.chooseLocation.SuccessCallbackResult) {
        console.log(result);

        await saveAddress(result, c);
        agent?.agentId && fetchAgent(agent?.agentId);
      },
    };
    Taro.chooseLocation(option);
  };

  // 唤起本地地图导航
  const openNavigation = (value:any) => {
    console.log(value,111)
    Taro.openLocation({
      latitude: value.latitude,
      longitude: value.longitude,
      name: value.name,
      address: value.address,
      scale: 18 // 缩放比例，范围5-18
    }).catch(err => {
      console.error('打开地图失败', err)
    })
  }

  return {
    openNavigation,
    handleChooseAddress,
  };
};
