<template>
  <view class="location-container">
    <view class="fenge"></view>
    <view class="location-list">
      <!-- 地址项 -->
      <view class="location-item" v-for="(item, index) in locationList" :key="index"
        @click="selectLocation(item, index)">
        <view class="location-info">
          <text :class="['location-address', { 'active': index === selectedIndex }]">{{ item.address }}</text>
        </view>
        <view class="location-select">
          <image v-if="index !== selectedIndex"
            src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_check1.png" mode="aspectFit"
            style="width: 40rpx; height: 40rpx;"></image>
          <image v-if="index === selectedIndex"
            src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_check2.png" mode="aspectFit"
            style="width: 40rpx; height: 40rpx;"></image>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { picUrl, menuButtonInfo, request, NavgateTo } from "../../../utils";
import { apiArr } from '../../../api/groupPurchase';

export default {
  data() {
    return {
      locationList: [],
      selectedIndex: -1
    };
  },
  onLoad(options) {
    const item = JSON.parse(options.item)
    this.getLocationList(item.goods_id)
  },
  methods: {
    async getLocationList(id) {
      const params = {
        goods_ids: id,
      }
      const res = await request(apiArr.groupBuyAddress, 'POST', params)
      // 遍历地址数组并正确赋值
      res.self_pickup_address_list[0].address.forEach(item => {
        const [address, phone, name] = item.split(' ');
        this.locationList.push({
          id: id,
          name: name || '',
          phone: phone || '',
          address: address || ''
        });
      });
    },
    selectLocation(item, index) {
      // 更新选中项的索引
      this.selectedIndex = index;
      
      // 从本地存储获取已有的地址数据
      let addressList = uni.getStorageSync('changeZTAddress') || [];
      
      // 检查id是否已存在
      const existingIndex = addressList.findIndex(addr => addr.id === item.id);
      
      if (existingIndex > -1) {
        // 如果id存在，则覆盖原来的数据
        addressList[existingIndex] = item;
      } else {
        // 如果id不存在，则新增
        addressList.push(item);
      }
      
      // 存储更新后的地址列表
      uni.setStorageSync('changeZTAddress', addressList);
      
      NavgateTo("1")
    }
  }
};
</script>

<style>
@import url('./index.css');
</style>