<template>
  <view class="container">
    <!--input列表 -->
    <view class="input-box">
      <view class="section" @tap="chooseLocation">
        <text>所在地区</text>
        <view class="pca"> {{ province }} {{ city }} {{ area }} </view>

        <view class="arrow">
          <image src="@/static/images/icon/more.png" />
        </view>
      </view>
      <view class="section">
        <text>详细地址</text>
        <input
          placeholder="如楼号/单元/门牌号"
          type="text"
          :value="addr"
          @input="onAddrInput"
        />
      </view>
    </view>
    <!-- end input列表 -->
    <!-- 功能按钮 -->
    <view class="btn-box">
      <view class="keep btn" @tap="onSaveAddr">
        <text>保存居住地址</text>
      </view>
    </view>
    <!-- end 功能按钮 -->
  </view>
</template>

<script setup>
import util from "@/utils/util.js";
import useUserStore from "@/stores/user/useUserStore";
const userStore = useUserStore();
// import { listByPid } from "@/api/submit-order/submit-order";
const city = ref("");
const area = ref("");
const addr = ref("");
const province = ref("");
onLoad( (options) => {
  province.value = userStore.userInfo.province;
  city.value = userStore.userInfo.city;
  area.value = userStore.userInfo.area;
  addr.value = userStore.userInfo.addr;
});

const chooseLocation = () => {
  // #ifdef MP-WEIXIN
  uni.chooseLocation({
    success: async (res) => {
      console.log(res);
      const { result } = await util.getDetailedAddress({
        latitude: res.latitude,
        longitude: res.longitude,
      });
      console.log("aaa",result);
      // {{ province }} {{ city }} {{ area }}

      province.value = result.ad_info.province;
      city.value = result.ad_info.city;
      area.value = result.ad_info.district;
      addr.value = res.name;
    },
  });
  // #endif
};

const onAddrInput = (e) => {
  addr.value = e.detail.value;
};

/**
 * 保存地址
 */
const onSaveAddr = async () => {
  if (!province.value || !city.value || !area.value || !addr.value) {
    uni.showToast({
      title: "请填写完整地址",
      icon: "none",
    });
    return;
  }
  const success = await userStore.setUserInfo({
    province: province.value,
    city: city.value,
    area: area.value,
    addr: addr.value,
  });

  if (success) {
    uni.showToast({
      title: "保存成功",
    });
    uni.navigateBack();
  } else {
    uni.showToast({
      title: "保存失败",
      icon: "none",
    });
  }
};
</script>

<style scoped lang="scss">
@import "./editAddress.scss";
</style>
