<template>
  <van-action-sheet v-model:show="show" title="选择收货地址" z-index="100000" style="height: 80vh;">

    <div class="address-list">
      <van-swipe-cell v-for="item in list" :key="item.id">
        <van-cell clickable @click="selectAddress(item)">
          <template #title>
            <div class="address-item">
              <div class="address-info">
                <span class="name">{{ item.name }}</span>
                <span class="tel">{{ item.tel }}</span>
                <van-tag v-if="item.isDefault" type="success" size="small" style="margin-left: 8px;">默认</van-tag>
              </div>
              <div class="address-detail">{{ item.address }}</div>
            </div>
          </template>
          <template #right-icon>
            <van-icon name="edit" @click.stop="onEdit(item)" />
          </template>
        </van-cell>
        <template #right>
          <van-button square type="danger" height="100%" @click="deleteAddress(item)">删除</van-button>
        </template>
      </van-swipe-cell>

      <div v-if="list.length === 0" class="empty">暂无地址</div>
    </div>

    <van-action-sheet v-model:show="showEditor" :title="tempAddress.id ? '编辑地址' : '新增地址'">
      <div class="address-edit">
        <van-form @submit="save">
          <van-cell-group inset>
            <van-field v-model="tempAddress.name" label="收货人" placeholder="请输入收货人" size="small"
              :rules="[{ required: true, message: '请填写收货人' }]" clearable required />
            <van-field v-model="tempAddress.phone" label="手机号" type="tel" placeholder="请输入手机号" size="small"
              :rules="[{ required: true, message: '请填写手机号' }]" clearable required />
            <van-field is-link type="textarea" autosize v-model="tempAddress.region" label="地区" placeholder="请选择地区"
              size="small" @click="showRegion = true;" readonly :rules="[{ required: true, message: '请选择地区' }]"
              required />
            <van-field v-model="tempAddress.address" label="详细地址" placeholder="请输入详细地址" size="small" type="textarea"
              autosize :rules="[{ required: true, message: '请填写详细地址' }]" clearable required />
            <van-cell size="small">
              <template #title>
                <span>是否设为默认地址</span>
              </template>
              <template #right-icon>
                <van-switch v-model="tempAddress.defaulted" />
              </template>
            </van-cell>
            <van-cell size="small">
              <template #title>
                <van-button round type="primary" color="#ca2904" size="large" native-type="save"
                  :loading="isSaving">保存</van-button>
              </template>
            </van-cell>
          </van-cell-group>
        </van-form>
      </div>
    </van-action-sheet>

    <van-popup v-model:show="showRegion" round position="bottom">
      <van-cascader v-model="region" title="请选择地区" :options="options" @finish="onFinish" @close="showRegion = false" />
    </van-popup>
    <van-action-bar>
      <van-action-bar-button color="#ca2904" type="primary" text="新增地址" @click="beforeAdd()" />
    </van-action-bar>
  </van-action-sheet>
</template>

<script>
import { useCascaderAreaData } from '@vant/area-data';

export default {
  emits: ['confirm'],
  data() {
    return {
      show: false,
      showEditor: false,
      tempAddress: {},
      isSaving: false,
      showRegion: false,
      region: '',
      list: [],
      options: useCascaderAreaData(),
    }
  },
  methods: {
    loadData() {
      this.$get('/v1/client/DUseraddressClient').then(res => {
        this.list = (res.data || []).map(item => ({
          id: item.id,
          name: item.name,
          tel: item.phone,
          province: item.province,
          city: item.city,
          county: item.county,
          address: item.province + item.city + item.county + ' ' + item.address,
          isDefault: item.defaulted,
        }));
      });
    },
    beforeAdd() {
      this.region = '';
      this.tempAddress = { defaulted: Boolean(this.list.length == 0) };
      this.showEditor = true;
    },
    onEdit(item) {
      event.stopPropagation();
      this.region = '';
      this.tempAddress = {
        id: item.id,
        name: item.name,
        phone: item.tel,
        region: item.province + item.city + item.county,
        address: item.address.split(' ').slice(1).join(' '),
        province: item.province,
        city: item.city,
        county: item.county,
        defaulted: Boolean(item.isDefault),
      };
      this.showEditor = true;
    },
    save() {
      this.isSaving = true;
      let api = '/v1/client/DUseraddressClient';
      let method = 'POST';
      if (this.tempAddress.id) {
        api = `/v1/client/DUseraddressClient/${this.tempAddress.id}`;
        method = 'PUT';
      }
      this.$request(api, this.tempAddress, method).then(() => {
        this.loadData();
        this.showEditor = false;
        this.$showSuccessToast('保存成功');
      }).finally(() => {
        this.isSaving = false;
      });
    },
    selectAddress(item) {
      this.show = false;
      this.$emit('confirm', {
        ReceiveName: item.name,
        ReceivePhone: item.tel,
        ReceiveRegionName: item.province + item.city + item.county,
        ReceiveAddress: item.address.split(' ').slice(1).join(' '),
        province: item.province,
        city: item.city,
        county: item.county,
      });
    },
    deleteAddress(item) {
      this.$del(`/v1/client/DUseraddressClient/${item.id}`).then(() => {
        this.loadData();
        this.$showSuccessToast('删除成功');
      });
    },
    onFinish(e) {
      this.showRegion = false;
      this.tempAddress.region = e.selectedOptions.map(x => x.text).join('');
      this.tempAddress.province = e.selectedOptions[0]?.text || '';
      this.tempAddress.city = e.selectedOptions[1]?.text || '';
      this.tempAddress.county = e.selectedOptions[2]?.text || '';
    },
    showSelector() {
      this.show = true;
      this.loadData();
    },
  }
}
</script>

<style scoped>
.address-list {
  max-height: 60vh;
  overflow-y: auto;
}

.van-switch--on {
  background: #ca2904;
}

.address-item {
  padding: 1.067vw 0;
}

.address-info {
  display: flex;
  align-items: center;
  gap: 2.133vw;
}

.address-info .name {
  font-weight: bold;
}

.address-info .tel {
  color: #999;
}

.address-detail {
  margin-top: 1.067vw;
  color: #666;
  font-size: 3.467vw;
}

.empty {
  text-align: center;
  padding: 10.667vw 0;
  color: #999;
}

.van-swipe-cell__right button {
  height: 100%;
}
</style>