<script setup lang="ts">
import { getAddressByIdApi, postAddressApi, putAddressApi } from '@/api/address'
import { onShowRefreshData } from '@/utils/common'
import { useAddressStore } from '@/stores/modules/address'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { getAreaDataApi } from '@/api/common'

// 表单数据
const form = ref({
  name: '',
  phone: '',
  full_location: '',
  province: '',
  city: '',
  county: '',
  address: '',
  is_default: 0,
})

const localAreaData = ref()

//获取参数
const query = defineProps<{
  id?: string
}>()

//获取地址详情
const getAddressDetail = async () => {
  if (query.id) {
    const res = await getAddressByIdApi(query.id)
    Object.assign(form.value, res.result)
  }
}

//设置页面标题
uni.setNavigationBarTitle({ title: query.id ? '修改地址' : '新建地址' })

//获取地址
const getRegion: UniHelper.RegionPickerOnChange = (event) => {
  const selectArea = event.detail.value
  form.value.full_location = selectArea.map((item: any) => item.text).join(' ')
  const [province, city, county] = Object.values({
    ...selectArea.map((item: any) => String(item.value)),
  })
  Object.assign(form.value, { province, city, county })
}

//是否默认地址
const isDefaultChange: UniHelper.SwitchOnChange = (event) => {
  form.value.is_default = event.detail.value ? 1 : 0
}

//表单实例
const formRef = ref<UniHelper.UniFormsInstance>()
//表单规则
const formRules = {
  name: {
    rules: [{ required: true, errorMessage: '请填写收货人' }],
  },
  phone: {
    rules: [
      { required: true, errorMessage: '请填写手机号码' },
      { pattern: /^1[3-9]\d{9}$/, errorMessage: '请填写正确的手机号码' },
    ],
  },
  full_location: {
    rules: [{ required: true, errorMessage: '请选择所在地区' }],
  },
  address: {
    rules: [{ required: true, errorMessage: '请输入详细地址' }],
  },
}

//保存地址
const saveAddress = async () => {
  try {
    await formRef.value?.validate?.()
  } catch (error) {
    console.log(error)
    return
  }

  if (query.id) {
    const res = await putAddressApi(form.value)
    useAddressStore().selectedAddress = res.result
  } else {
    const res = await postAddressApi(form.value)
    useAddressStore().selectedAddress = res.result
  }

  uni.showToast({ icon: 'success', title: query.id ? '修改成功' : '添加成功' })
  setTimeout(() => {
    uni.navigateBack()
  }, 1000)
}

onLoad(() => {
  getAreaDataApi().then((res) => {
    localAreaData.value = res.result
  })
})

onShowRefreshData(() => {
  getAddressDetail()
})
</script>

<template>
  <view class="content">
    <uni-forms ref="formRef" :rules="formRules" :modelValue="form" label-position="left">
      <!-- 表单内容 -->
      <uni-forms-item name="name" class="form-item" required>
        <text class="label">收货人</text>
        <input class="input" placeholder="请填写收货人姓名" v-model="form.name" />
      </uni-forms-item>
      <uni-forms-item name="phone" class="form-item" required>
        <text class="label">手机号码</text>
        <input class="input" placeholder="请填写收货人手机号码" v-model="form.phone" />
      </uni-forms-item>

      <uni-forms-item class="form-item" name="full_location" required>
        <text class="label">所在地区</text>
        <view class="picker">
          <uni-data-picker
            :localdata="localAreaData"
            popup-title="选择地区"
            @change="getRegion"
            :map="{
              text: 'name',
              value: 'id',
            }"
            :value="Number(form.county)"
            :clear-icon="false"
          >
          </uni-data-picker>
        </view>
      </uni-forms-item>
      <uni-forms-item class="form-item" name="address" required>
        <text class="label">详细地址</text>
        <input class="input" placeholder="街道、楼牌号等信息" v-model="form.address" />
      </uni-forms-item>
      <view class="form-item">
        <label class="label">设为默认地址</label>
        <switch
          class="switch"
          @change="isDefaultChange"
          color="#ff5f3c"
          :checked="form.is_default === 1"
        />
      </view>
    </uni-forms>
  </view>
  <!-- 提交按钮 -->
  <shop-submit-button title="保存并使用" @tap="saveAddress" />
</template>

<style lang="scss">
body {
  height: 98%;
}
page {
  background-color: #f4f4f4;
}

.content {
  margin: 20rpx 20rpx 0;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .form-item,
  .uni-forms-item {
    display: flex;
    align-items: center;
    min-height: 96rpx;
    padding: 25rpx 10rpx 40rpx;
    background-color: #fff;
    font-size: 28rpx;
    border-bottom: 1rpx solid #ddd;
    position: relative;
    margin-bottom: 0;
    font-size: 24rpx;

    // 调整 uni-forms 样式
    .uni-forms-item__content {
      display: flex;
      align-items: center;
    }

    .uni-forms-item__error {
      margin-left: 160rpx;
    }

    &:last-child {
      border: none;
    }

    .label {
      width: 160rpx;
      color: #333;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .switch {
      position: absolute;
      right: 0rpx;
      transform: scale(0.8);
    }

    .placeholder {
      color: #808080;
      font-size: 24rpx;
    }

    .uni-input-placeholder {
      font-size: 24rpx;
      color: #808080;
    }
  }

  .picker {
    flex: 1;
  }

  // 调整 uni-data-picker 样式
  /* #ifdef MP-WEIXIN */
  .input-value-border {
    border: none;
    padding-left: 0rpx;
  }
  .arrow-area {
    display: none;
  }
  .selected-list {
    display: flex;
    flex-wrap: wrap;
  }
  /* #endif */

  /* #ifdef WEB */
  :deep(.input-value-border) {
    border: none;
    padding-left: 0rpx;
  }

  :deep(.input-arrow) {
    display: none;
  }

  :deep(.selected-list) {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
  }
  /* #endif */
}

swiper,
scroll-view {
  width: 100%;
}
</style>
