<template>
  <view class="content">
    <uni-nav-bar left-icon="back" @clickLeft="back" statusBar fixed title="我的地址"></uni-nav-bar>
    <view class="flex-col group_5">
      <view class="flex-col list" v-if="list.length > 0">
        <view class="list-item flex-col" :key="item.id" v-for="item in list">
          <view class="top-group flex-col" @click="selectAddress(item)">
            <view class="justify-between">
              <text class="text_4">{{ item.receiver }} {{ item.receiverMobile }}</text>
              <view class="select-button" v-show="showSelectedTip">选择</view>
            </view>
            <text class="text_6">{{ item.provinceName || '' }}{{ item.cityName || '' }}{{ item.districtName || '' }}{{ item.detail || '' }}</text>
          </view>
          <view class="bottom-group justify-between">
            <view class="left-group flex-row view_4" :class="{ selected: item.isDefault }" @click="setDefault(item)">
              <image class="icon" :src="item.isDefault ? '/static/imgs/general/selected-icon.png' : '/static/imgs/general/select-icon.png'"></image>
              <text class="text_8">设为默认</text>
            </view>
            <text class="text_10 text_11" @click="remove(item)">删除</text>
          </view>
        </view>
      </view>
      <image v-else :src="imgStamp['empty-file']" class="image_6" />
      <view class="flex-col items-center fixed" @click="getAuth">
        <text>导入微信收货地址</text>
      </view>
    </view>
  </view>
</template>

<script>
  import { go2, back, setCache } from '@/utils/hook.js'
  import { getAddressList, changeAddress, deleteAddress } from '@/apis/addressApi'
  import { addressType, imgStamp, cacheKey } from '@/enums/index'
  export default {
    data() {
      return {
        prePage: 'mine',
        list: [],
        imgStamp: Object.freeze(imgStamp),
        hasAuth: false // 是否有授权
      }
    },
    onShow() {
      getAddressList().then((res) => {
        this.list = res
      })
    },
    onLoad(options) {
      if (options.from) {
        this.prePage = options.from
      }
      uni.getSetting({
        success: (res) => {
          if (res.authSetting['scope.address']) {
            console.log('已授权')
            this.hasAuth = true
          }
        },
        fail: (err) => {
          console.log(err)
        }
      })
    },
    computed: {
      showSelectedTip() {
        return ['print-pay'].includes(this.prePage)
      }
    },
    methods: {
      go2,
      back,
      selectAddress(item) {
        let reg_tel = /^(13\d|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18\d|19[0-35-9])\d{8}$/
        if (!reg_tel.test(item.receiverMobile)) {
          uni.showModal({
            content: '手机号码格式错误',
            title: '提示',
            duration: 1000
          })
          return
        }
        if (this.prePage == 'print-pay') {
          setCache(cacheKey.SELECT_ADDRESS, item)
          back()
        }
      },
      setDefault(item) {
        if (item.isDefault) {
          return
        }
        changeAddress({ ...item, isDefault: addressType.DEFAULT }).then(() => {
          getAddressList().then((res) => {
            this.list = res
          })
        })
      },
      // 获取授权
      getAuth() {
        uni.authorize({
          scope: 'scope.address',
          success: () => {
            this.hasAuth = true
            this.importAddress()
          },
          fail: () => {
            this.hasAuth = false
            uni.showModal({
              title: '提示',
              content: '您未授权微信地址，无法使用该功能。是否打开授权？',
              success: (res) => {
                if (res.confirm) {
                  uni.openSetting({
                    success: (result) => {
                      if (result.authSetting['scope.address']) {
                        this.hasAuth = true
                      }
                    }
                  })
                }
              }
            })
          }
        })
      },
      // 导入微信收货地址
      importAddress() {
        uni.chooseAddress({
          success: (res) => {
            if (!res.userName || res.userName.trim() == '') {
              uni.showModal({
                content: '导入的地址收货人名称不能为空',
                title: '提示'
              })
              return
            }
            if (!res.telNumber || res.telNumber.trim() == '') {
              uni.showModal({
                content: '导入的地址收货人电话不能为空',
                title: '提示'
              })
              return
            }
            let reg_tel = /^(13\d|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18\d|19[0-35-9])\d{8}$/
            if (!reg_tel.test(res.telNumber)) {
              uni.showModal({
                content: '手机号码格式错误',
                title: '提示',
                duration: 1000
              })
              return
            }
            let address = {
              cityName: res.cityName,
              detail: res.detailInfo,
              districtName: res.countyName,
              isDefault: addressType.DEFAULT,
              provinceName: res.provinceName,
              receiver: res.userName,
              receiverMobile: res.telNumber,
              postalCode: res.postalCode
            }
            changeAddress(address).then(() => {
              getAddressList().then((res) => {
                this.list = res
                if (this.list.length == 1 && this.prePage == 'print-pay') {
                  setCache(cacheKey.SELECT_ADDRESS, this.list[0])
                  back()
                }
              })
            })
          },
          fail: (err) => {
            console.error('err', err)
            uni.showModal({
              title: '提示',
              content: '导入地址失败，请同意授权或更新微信后再试'
            })
          }
        })
      },
      remove(item) {
        uni.showModal({
          title: '提示',
          content: '确定要删除该地址吗？',
          success: (res) => {
            if (res.confirm) {
              deleteAddress({ id: item.id }).then(() => {
                const addressObj = {
                  id: null,
                  receiver: '',
                  receiverMobile: '',
                  provinceName: '',
                  cityName: '',
                  districtName: '',
                  streetName: '',
                  detail: ''
                }
                setCache(cacheKey.SELECT_ADDRESS, addressObj)
                getAddressList().then((res) => {
                  this.list = res
                })
              })
            }
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .content {
    width: 750rpx;
  }
  .group_5 {
    padding: 0 0 84rpx;
    height: 100vh;
    overflow-y: auto;
    position: relative;
    .image_6 {
      position: absolute;
      top: 20%;
      left: 70rpx;
      right: 70rpx;
      width: 609rpx;
      height: 453rpx;
    }
    .list {
      margin: 0 32rpx;
      .list-item {
        padding: 0 24rpx;
        background-color: rgb(255, 255, 255);
        border-radius: 16rpx;
        margin-top: 20rpx;
        .top-group {
          padding: 27rpx 0 29rpx;
          .text_4 {
            color: rgb(51, 51, 51);
            font-size: 30rpx;
            font-weight: 500;
            line-height: 42rpx;
            white-space: nowrap;
          }
          .select-button {
            width: 100rpx;
            height: 42rpx;
            padding: 0rpx 8rpx;
            text-align: center;
            color: white;
            font-size: 26rpx;
            line-height: 42rpx;
            white-space: nowrap;
            background-color: #007aff;
            border-radius: 6rpx;
          }
          .text_6 {
            margin-right: 31rpx;
            margin-top: 16rpx;
            color: rgb(51, 51, 51);
            font-size: 28rpx;
            line-height: 40rpx;
            text-align: left;
          }
        }
        .bottom-group {
          padding: 20rpx 0;
          color: rgb(136, 136, 136);
          font-size: 28rpx;
          line-height: 40rpx;
          white-space: nowrap;
          border-top: solid 2rpx rgb(216, 216, 216);
          .icon {
            margin: 4rpx 0;
            border-radius: 50%;
            width: 32rpx;
            height: 32rpx;
          }
          .left-group {
            font-size: 28rpx;
            line-height: 40rpx;
            white-space: nowrap;
            .text_8 {
              margin-left: 12rpx;
            }
          }
          .selected {
            color: rgb(0, 122, 255);
          }
          .text_10 {
            color: rgb(136, 136, 136);
            font-size: 28rpx;
            line-height: 40rpx;
            white-space: nowrap;
          }
        }
      }
    }
    .fixed {
      padding: 20rpx 0;
      color: rgb(255, 255, 255);
      font-size: 32rpx;
      line-height: 45rpx;
      white-space: nowrap;
      background-color: rgb(0, 122, 255);
      border-radius: 20rpx;
      position: fixed;
      left: 32rpx;
      right: 32rpx;
      bottom: 90rpx;
    }
  }
</style>
