<template>
  <view class="address-edit-page">
    <view class="form-card">
      <view class="form-row" v-for="item in formList" :key="item.key">
        <text class="label">{{ item.label }}</text>
        <input
          v-if="item.key !== 'region'"
          class="input"
          :placeholder="item.placeholder"
          v-model="form[item.key]"
        />
        <view v-else class="input region-input" @click="openPicker()">
          <text :class="{ placeholder: !regionText }">
            {{ regionText || "请选择省/市/区" }}
          </text>
        </view>
      </view>
      <view class="form-row " style="display: flex;align-items: center; justify-content: space-between;">
        <text class="label">设为默认地址</text>
        <uv-switch activeColor="#acf934" inactiveColor="#eee" v-model="form.isDefault" size="28"></uv-switch>
      
      </view>
    </view>
    <view class="save-btn" @click="save">保存</view>
    <uv-picker
      ref="picker"
      :columns="addressList" 
      keyName="name" 
      @change="change"
      @confirm="confirm"
    />
  </view>
</template>
  
<script>
import addressData from "@/static/address/province.json";
export default {
  data() {
    return {
      isEdit: false,
      form: {
        name: "",
        mobile: "",
        region: "",
        detail: "",
        zipcode: "",
        isDefault: false,
      },
      formList: [
        { key: "name", label: "收货人", placeholder: "填写收货人姓名" },
        { key: "mobile", label: "手机号", placeholder: "填写手机号" },
        { key: "region", label: "所在地区", placeholder: "省/市/区" },
        {
          key: "detail",
          label: "详细地址",
          placeholder: "填写详细地址和门牌号",
        },
        { key: "zipcode", label: "邮政编码", placeholder: "填写邮政编码" },
      ], 
      pickerValue: [0, 0, 0],
      provinces: [],
      citys: [],
      areas: [],
      regionText: "", 
    };
  },
  computed: {
    addressList() {
      return [
        Array.isArray(this.provinces) ? this.provinces : [],
        Array.isArray(this.citys) ? this.citys : [],
        Array.isArray(this.areas) ? this.areas : []
      ];
    },
  },
  onLoad(options) {
    this.initAddressData();  
    
    if (options.id) {
      this.isEdit = true;
      uni.setNavigationBarTitle({ title: "编辑地址" }); 
    } else {
      uni.setNavigationBarTitle({ title: "添加新地址" });
    }
  },
  methods: {
    openPicker() {
      this.$refs.picker.open();
    },
    goBack() {
      uni.navigateBack();
    },
    initAddressData() {
      this.provinces = Array.isArray(addressData) ? addressData : [];
      this.citys = this.provinces[0]?.children || [];
      this.areas = this.citys[0]?.children || [];
    },
    change(e) {
      const { columnIndex, index, indexs } = e;
      if (columnIndex === 0) {
        this.citys = this.provinces[index]?.children || [];
        this.areas = this.citys[0]?.children || [];
        this.$refs.picker.setIndexs([index, 0, 0], true);
      } else if (columnIndex === 1) {
        this.areas = this.citys[index]?.children || [];
        this.$refs.picker.setIndexs(indexs, true);
      }
    },
    confirm(e) {
      this.regionText = `${e.value[0].name} ${e.value[1].name} ${e.value[2].name}`;
      this.form.region = this.regionText;
      // 自动填充邮编
      // let zipcode = '';
      // if (e.value[2] && (e.value[2].code || e.value[2].zipcode || e.value[2].postalCode)) {
      //   zipcode = e.value[2].code || e.value[2].zipcode || e.value[2].postalCode;
      // }
      // this.form.zipcode = zipcode;
      this.showPicker = false;
       
    },
    // 校验方法
    validateForm() {
      console.log(this.form ,"填写的数据");
      // 姓名
      if (!this.form.name.trim()) {
        uni.showToast({ title: "请填写收货人姓名", icon: "none" });
        return false;
      }
      // 手机号
      if (!/^1[3-9]\d{9}$/.test(this.form.mobile.trim())) {
        uni.showToast({ title: "请填写正确的手机号", icon: "none" });
        return false;
      }
      // 地区
      if (!this.form.region.trim()) {
        uni.showToast({ title: "请选择所在地区", icon: "none" });
        return false;
      }
      // 详细地址
      if (!this.form.detail.trim()) {
        uni.showToast({ title: "请填写详细地址", icon: "none" });
        return false;
      }
      // 邮编（可选，填写时校验）
      if (this.form.zipcode && !/^\d{6}$/.test(this.form.zipcode.trim())) {
        uni.showToast({ title: "请填写正确的邮政编码", icon: "none" });
        return false;
      }
      return true;
    },

    save() {
      if (!this.validateForm()) return;
      // 组装参数
      const params = {
        realname: this.form.name,
        mobile: this.form.mobile,
        area: this.form.region.trim(),
        address: this.form.detail.trim(),
        is_default: this.form.isDefault ? 'yes' : 'no',
        uuid: getApp().globalData.uuid,
					skey: getApp().globalData.skey,
      };
      // 保存逻辑
      uni.request({
        url: this.$apiHost + '/Address/submitaddress',
        method: 'GET',
        data: params,
        success: (res) => {
          if (res.data && res.data.success === 'yes') {
            uni.showToast({ title: this.isEdit ? '编辑成功' : '添加成功', icon: 'success' });
            setTimeout(() => {
              uni.navigateBack();
            }, 800);
          } else {
            uni.showToast({ title: res.data.str || '保存失败', icon: 'none' });
          }
        },
        fail: () => {
          uni.showToast({ title: '网络错误', icon: 'none' });
        }
      });
    },
  },
};
</script>
  
<style lang="scss">
page{
  background: #f2f6f2;
}
.address-edit-page {
  min-height: 100vh;
  background: #f2f6f2;
  ::v-deep .uni-input-placeholder{
    color: #bbb !important;
  }
 
  .form-card {
    background: #fff;
    border-radius: 18rpx;
    margin: 32rpx;
    padding: 32rpx 0; 
    .form-row {
      display: flex;
      align-items: center;
      border-bottom: 1rpx solid #f2f6f2;
      padding: 24rpx 32rpx;
      .label {
        width: 180rpx;
        font-size: 28rpx;
        color: #222;  
     
      }
      .input {
        flex: 1;
        font-size: 28rpx;
        color: #222;
        border: none;
        background: transparent;
      }
      switch {
        margin-left: auto;
      }
    }
    .form-row:last-child {
      border-bottom: none;
    }
  }
  .save-btn {
    width: 80vw;
    height: 88rpx;
    background: #1f1f1f;
    color: #acf934;
    border-radius: 44rpx;
    margin: 48rpx auto 0 auto;
    text-align: center;
    line-height: 88rpx;
    font-size: 32rpx;
    font-weight: bold;
  }
  .region-input {
    min-height: 48rpx;
    line-height: 48rpx;
    color: #222;
    border-bottom: 1rpx solid #eee;
    padding: 0 16rpx;
    .placeholder {
      color: #bbb;
    }
  }
}
</style>