// 这个既是组件，也是页面
<template>
  <view>
    <van-sticky>
      <view class="top-bar justify-center bg-white sh">
        <van-icon class="top-left" name="arrow-left" @tap="goBack" />
        <view class="top-center">{{ state.title }}</view>
        <view class="top-right">
          <view class="text-m" @tap="onAdd">新增地址</view>
        </view>
      </view>
    </van-sticky>
    <van-list :loading="state.loading" :finished="state.finished" finished-text="" offset="10" @load="receiveList">
      <van-pull-refresh v-model="state.refresh" @refresh="onReflesh">
        <van-radio-group v-if="state.list.length > 0" v-model="state.selected" style="min-height: calc(100vh - 100px)">
          <van-cell-group v-for="item in state.list">
            <van-cell class="pd-l-0">
              <template #title>
                <view class="flex" style="width: 80vw">
                  <view class="justify-center" style="width: 40px">
                    <van-radio v-if="state.switch.isComponent" icon-size="17px" :name="item.addrId"
                      @tap="onAddressChange(item)" />
                  </view>
                  <view>
                    <view class="text-gray justify-middle">
                      <van-tag class="mg-r-10" type="primary" v-if="item.isDefault == 1">默认</van-tag>
                      {{ item.region }}
                    </view>
                    <view class="text-bold text-l">{{ item.detailAddress }}</view>
                    <view class="text-darkGray">
                      <text class="pd-r-20">{{ item.receiverName }}</text>
                      <text>{{ item.phone }}</text>
                    </view>
                  </view>
                </view>
              </template>
              <template #right-icon>
                <view class="justify-middle text-darkGray text-xl">
                  <van-icon class="pd-r-40" name="delete-o" @tap="receiveDel(item.addrId)" />
                  <van-icon name="edit" @tap="onEdit(item)" />
                </view>
              </template>

            </van-cell>
          </van-cell-group>
        </van-radio-group>
        <view v-else class="justify-center" style="min-height: calc(100vh - 180px)">
          <van-empty description="您当前还没有收货地址" />
          <van-button class="text-l" color="linear-gradient(315deg, #FE521F 0%, #FE7902 100%)" round block
            style="width: 240rpx" @tap="onAdd">
            新增地址
          </van-button>
        </view>
      </van-pull-refresh>
    </van-list>
    <view v-if="state.fail && state.list > 0" class="text-ss text-gray pd-50 text-center" @tap="failReset">请求失败，点击重试
      <van-icon name="replay" />
    </view>
    <to-top />
    <!-- 因为只有这里用到，就不抽组件了 -->
    <van-popup v-model:show="state.edit.show" position="right" class="bg-gray"
      :style="{ width: '100%', height: '100%' }">
      <van-sticky>
        <view class="top-bar justify-center bg-white sh mg-b-20">
          <van-icon class="top-left" name="arrow-left" @tap="state.edit.show = false" />
          <view class="top-center">{{ state.edit.params.addrId ? '修改地址' : '新增地址' }}</view>
        </view>
      </van-sticky>
      <van-form>
        <van-cell-group class="pd-h-5 mg-b-15">
          <van-field ref="nameField" v-model="state.edit.params.receiverName" maxlength="100" label="收货人" name="name"
            placeholder="收货人姓名" />
          <van-field v-model="state.edit.params.phone" type="digit" label="手机号码" name="phone" placeholder="手机号码"
            clear-trigger="always" clearable>
            <template #right-icon>
              <van-icon v-if="validPhone" color="#39b54a" name="checked" />
              <van-icon v-else-if="state.edit.params.phone.length == 11" color="#e54d42" name="clear" />
              <van-icon v-else-if="state.edit.params.phone.length > 0" color="#e54d42" name="warning" />
            </template>
          </van-field>
          <van-field v-model="state.edit.params.region" right-icon="arrow" placeholder="所在省市区" @tap="onAddress"
            disabled>
            <template #label>
              <view class="text-darkGray">所在地区</view>
            </template>
          </van-field>
          <van-field v-model="state.edit.params.detailAddress" maxlength="255" label="详细地址" name="address"
            placeholder="街道门牌等详细信息" enterkeyhint="done" />
        </van-cell-group>
        <van-cell-group class="pd-h-5 mg-b-15">
          <van-cell center title="设置为默认地址">
            <template #right-icon>
              <van-switch v-model="state.edit.params.isDefault" size="18" :active-value="1" :inactive-value="0" />
            </template>
          </van-cell>
        </van-cell-group>
        <div class="pd-50">
          <!-- 因为最后一个是switch，所以我不想native-type="submit" -->
          <van-button :disabled="!checkSaveOn" @tap="onSave" :loading="state.loading" class="text-l"
            :color="checkSaveOn ? 'linear-gradient(315deg, #FE521F 0%, #FE7902 100%)' : '#cccccc'" round block>
            保存
          </van-button>
        </div>
      </van-form>
      <van-popup v-model:show="state.popup.region.show" round position="bottom">
        <van-picker title="所在地区" :columns="state.popup.region.options" :columns-field-names="state.popup.region.struct"
          @confirm="onRegionChange" @cancel="state.popup.region.show = false" />
      </van-popup>
    </van-popup>
  </view>
</template>

<script setup lang="ts">
import api from '@/api'
import { computed, onBeforeMount, reactive, ref } from 'vue';
import toTop from '@/components/tool/toTop.vue';
import { PageUtils } from '@/utils/utils';
import { Dialog, Toast } from 'vant';

interface Props {
  addrId?: string;
}
const props = withDefaults(defineProps<Props>(), {
  addrId: '',
});
const state = reactive({
  title: PageUtils.getTitle(),
  list: [] as any,
  selected: '',
  edit: {
    show: false,
    params: {
      addrId: undefined,
      receiverName: '',
      phone: '',
      regionNo: '',
      region: '',
      detailAddress: '',
      isDefault: 0
    }
  },
  refresh: false,
  loading: false,
  fail: false,
  finished: false,
  loadingSon: {
    edit: false
  },
  receive: {
    page: 0
  },
  popup: {
    region: {
      show: false,
      options: [] as any,
      struct: { text: 'name', values: 'id', children: 'arealist' }
    }
  },
  switch: {
    isComponent: false
  }
})
const nameField: any = ref()
const emit = defineEmits(["change", "cancel"]);
const validPhone = computed(() => {
  return state.edit.params.phone.length == 11 && /^1[3456789]\d{9}$/.test(state.edit.params.phone)
})
const checkSaveOn = computed(() => {
  return validPhone.value && state.edit.params.receiverName && state.edit.params.region && state.edit.params.detailAddress
})

onBeforeMount(() => {
  if (PageUtils.getTitle(true) != '收货地址') {
    state.switch.isComponent = true
  }
  receiveArea()
  receiveList()
})

function receiveList() {
  if (state.loading || state.fail) return
  state.loading = true
  state.receive.page += 1
  api.receiveList({ pageNum: state.receive.page }).then((data: any) => {
    if (!data||!data.hasNextPage){
      state.finished = true
    }
    state.list.push(...data.list)
  })
    .catch(() => {
      state.fail = true
    }).finally(() => {
      state.refresh = false
      state.loading = false
    })
}
function onAddressChange(item: any) {
  emit("change", item);
}
function goBack() {
  if (state.switch.isComponent) {
    emit("cancel");
      PageUtils.goBack()
  } else {
    PageUtils.goBack()
  }
}
function onAdd() {
  state.edit.params = {
    addrId: undefined,
    receiverName: '',
    phone: '',
    regionNo: '',
    region: '',
    detailAddress: '',
    isDefault: 0
  }
  state.edit.show = true
  // 只有新增地址时才自动弹起，因为编辑不一定重头全改
  setTimeout(() => {
    nameField.value && nameField.value.focus()
  })
}
function onAddress() {
  state.popup.region.show = true
}
function onRegionChange(list: any) {
  state.edit.params.regionNo = list.map((item: any) => item.id).join(',')
  state.edit.params.region = list.map((item: any) => item.name).join(' ')
  state.popup.region.show = false
}
function receiveArea() {
  api.receiveArea().then((data: any) => {
    leavesAddProp(data, 'arealist')
    state.popup.region.options = data
  })
}
// vant-Bug-picker最后一层也需要"children"
function leavesAddProp(list: Array<any>, name: string) {
  list.forEach((item: any) => {
    if (item[name]) {
      leavesAddProp(item[name], name)
    } else {
      item[name] = null
    }
  })
}
function onSave() {
  if (state.loadingSon.edit) return
  state.loadingSon.edit = true
  if (state.edit.params.addrId) {
    api.receiveEdit(state.edit.params).then(() => {
      Toast.success('修改成功')
      state.edit.show = false
      onReflesh()
    }).finally(() => {
      state.loadingSon.edit = false
    })
  } else {
    api.receiveAdd(state.edit.params).then(() => {
      Toast.success('新增成功')
      state.edit.show = false
      onReflesh()
    }).finally(() => {
      state.loadingSon.edit = false
    })
  }
}
function receiveDel(addrId: string) {
  Dialog.confirm({
    message: '是否删除该地址',
    title: "提示",
  }).then(() => {
    if (state.loading) return
    state.loading = true
    api.receiveDel({ addrId }).then(() => {
      state.loading = false
      onReflesh()
    }).catch(() => {
      state.loading = false
    })
  });
}
function onEdit(item: any) {
  state.edit.params = {
    addrId: item.addrId,
    receiverName: item.receiverName,
    phone: item.phone,
    regionNo: item.regionNo,
    region: item.region,
    detailAddress: item.detailAddress,
    isDefault: item.isDefault
  }
  state.edit.show = true
}
function onReflesh() {
  state.list = []
  state.receive.page = 0
  state.finished = false
  receiveList()
}
function failReset() {
  state.receive.page -= 1
  state.fail = false
  receiveList()
}
</script>

<style lang="scss" scoped>
</style>
