<template>
  <view class="app-container">
    <HeaderBar :title="id ? '编辑地址' : '新增地址'" text-align="center" enable-back />

    <view class="form-box">
      <!-- <view class="form-item">
        <view class="label">姓名</view>
        <input
          class="input"
          v-model="form.name"
          placeholder="请输入姓名"
          placeholder-class="placeholder"
        />
      </view>

      <view class="form-item">
        <view class="label">手机号码</view>
        <input
          class="input"
          v-model="form.mobile"
          type="number"
          placeholder="请输入手机号码"
          placeholder-class="placeholder"
        />
      </view> -->

      <view class="form-item" @click="chooseLocation">
        <view class="label">定位</view>
        <view class="input">
          <text :class="{'placeholder': !form.regionMergerName}">{{ form.regionMergerName || '请选择定位' }}</text>
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>

      <view class="form-item">
        <view class="label">详细地址</view>
        <textarea
          class="textarea"
          v-model="form.address"
          placeholder="请输入详细地址"
          placeholder-class="placeholder"
        />
      </view>

      <!-- <view class="form-item">
        <view class="label">设为默认地址</view>
        <switch
          :checked="form.isDefault"
          @change="(e) => form.isDefault = e.detail.value"
          color="#6a8cff"
        />
      </view> -->
    </view>

    <button class="submit-btn" @click="handleSubmit">保存</button>

    <uni-popup ref="regionPopup" type="bottom">
      <RegionPicker
        :region-data="regionList"
        :value="selectedRegionIds"
        @change="onRegionChange"
        @close="closeRegionPicker"
      />
    </uni-popup>
  </view>
</template>

<script>
import { appGetAddressDetail, appAddAddress, appUpdateAddress } from '@/api/app/address'
import HeaderBar from '@/components/HeaderBar.vue'
import RegionPicker from '@/components/RegionPicker.vue'
import { getAllRegions, appGetRegionByLocation } from '@/api/app/region'
import {parseLocation} from '@/utils/index'

export default {
  components: {
    HeaderBar,
    RegionPicker
  },
  data() {
    return {
      form: {
        name: null,
        mobile: null,
        address: null,
        isDefault: false,
        regionId: null,
        lon: null,
        lat: null
      },
      locatioName: null,
      regionName: null,
      id: null,
      regionList: [],
      selectedRegionIds: []
    }
  },
  onLoad(options) {
    if (options.id) {
      this.id = options.id
      this.getDetail()
    }
    this.getRegionList()
  },
  methods: {
    getDetail() {
      this.$modal.loading('加载中...')
      appGetAddressDetail(this.id).then(res => {
        this.form = res.data
        if (this.form.regionId) {
          this.selectedRegionIds = [this.form.regionId]
          this.regionName = this.getRegionNameById(this.form.regionId)
        }
      }).finally(() => {
        this.$modal.closeLoading()
      })
    },
    getRegionList() {
      getAllRegions().then(res => {
        this.regionList = res.data
      })
    },
    getRegionNameById(id) {
      const findRegion = (regions, targetId) => {
        for (const region of regions) {
          if (region.id === targetId) {
            return region.name
          }
          if (region.children) {
            const result = findRegion(region.children, targetId)
            if (result) return result
          }
        }
        return null
      }
      return findRegion(this.regionList, id)
    },
    showRegionPicker() {
      this.$refs.regionPopup.open()
    },
    closeRegionPicker() {
      this.$refs.regionPopup.close()
    },
    onRegionChange(e) {
      this.selectedRegionIds = e.ids
      this.regionName = e.names.join(' ')
      this.form.regionId = e.ids[e.ids.length - 1]
      this.closeRegionPicker()
    },
    chooseLocation() {
      wx.chooseLocation({
        success: (res) => {
          console.log('res', res);
          let location = parseLocation(res);
          console.log("location", location);
          this.form.lon = res.longitude
          this.form.lat = res.latitude
          this.form.address = location.address;

          // 获取匹配的地区ID
          appGetRegionByLocation(this.form.lon, this.form.lat).then(regionRes => {
            if (regionRes.data != null) {
              this.form.regionId = regionRes.data.id;
              this.form.regionMergerName = regionRes.data.mergerName;
            }
          })
        },
        fail: (err) => {
          console.error('选择位置失败：', err)
          this.$modal.msgError('选择位置失败，请重试')
        }
      })
    },
    handleSubmit() {
      this.$modal.loading("提交中");
      const api = this.id ? appUpdateAddress : appAddAddress
      api(this.form).then(() => {
        this.$modal.msgSuccess('保存成功')
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }).finally(() => {
        this.$modal.closeLoading()
      })
    }
  }
}
</script>

<style lang="scss" scoped>

.form-box {
  background: #fff;
  border-radius: 24rpx;
  padding: 30rpx 20rpx;
  margin-top: 30rpx;
  margin-left: 20rpx;
  margin-right: 20rpx;
  box-shadow: 0 4rpx 24rpx rgba(106, 140, 255, 0.06);
}

.form-item {
  margin-bottom: 30rpx;
  .label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
    font-weight: 500;
  }
  .input {
    background: #f7f8fa;
    border-radius: 12rpx;
    padding: 24rpx 20rpx;
    font-size: 28rpx;
    color: #333;
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 80rpx;
    box-sizing: border-box;
  }
  .textarea {
    width: 100%;
    min-height: 120rpx;
    background: #f7f8fa;
    border-radius: 12rpx;
    padding: 20rpx;
    font-size: 28rpx;
    color: #333;
    resize: none;
    border: none;
  }
}

.placeholder {
  color: #999;
}

.submit-btn {
  width: 90%;
  margin: 40rpx auto 0;
  display: block;
  background: linear-gradient(180deg, #6a8cff 0%, #4a6cff 100%);
  color: #fff;
  border-radius: 50rpx;
  font-size: 32rpx;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
  border: none;
  box-shadow: 0 4rpx 12rpx rgba(106, 140, 255, 0.3);
}
</style>