<template>
  <zj-page-layout :hasFooter="true">
    <view class="form-container">
      <view class="clipboard">
        <view class="box">
          <u--textarea
            v-model="clipboard"
            border="none"
            placeholder="试试粘贴“收件人姓名，手机号，详细地址”，可快速识别您的用户及地址信息"
          ></u--textarea>
          <view class="btns">
            <u-button text="清空" size="small" @click="clipboard = ''"></u-button>
            <u-button type="primary" text="识别" size="small" @click="shibie"></u-button>
          </view>
        </view>
      </view>
      <view class="row">
        <view class="title">联系人</view>
        <view class="right input"><input type="text" placeholder="请输入联系人" v-model="formData.name" /></view>
      </view>
      <view class="row">
        <view class="title">手机号码</view>
        <view class="right input"><input type="number" placeholder="请输入手机号码" v-model="formData.phone" /></view>
      </view>
      <view class="row">
        <view class="title">所在地区</view>
        <view class="right">
          <view class="picker" @tap="selectCity">
            <view v-if="formData.province">{{
              `${formData.province}/${formData.city}/${formData.area}/${formData.street}`
            }}</view>
            <view v-else style="color: #666666">请选择省/市/区/街道</view>
            <text class="iconfont icon-jinru"></text>
          </view>
        </view>
      </view>

      <view class="row">
        <view class="title">详细地址</view>
        <view class="right textarea">
          <textarea placeholder="请输入详细地址" auto-height v-model="formData.address"></textarea>
          <view class="r" @tap="getLocation"><text class="iconfont icon-dingwei1"></text>定位</view>
        </view>
      </view>
      <view class="row">
        <view class="title">门牌号</view>
        <view class="right input"
          ><input type="text" placeholder="请输入门牌号" maxlength="15" v-model="formData.houseNo"
        /></view>
      </view>
      <view class="row mt20">
        <view class="title">设为默认</view>
        <view class="right default"
          ><switch
            @change="switchChange"
            color="#3D8FFD"
            v-model="formData.defaultAddr"
            :checked="formData.defaultAddr"
            style="transform: scale(0.7)"
        /></view>
      </view>
    </view>

    <template slot="footer">
      <view class="footer-btn-group">
        <u-button text="删除" @click="handleDelete" v-if="editId"></u-button>
        <u-button text="保存" type="primary" @click="submitForm"></u-button>
      </view>
    </template>

    <city-picker
      v-if="isShow"
      :isShow="isShow"
      :level="4"
      :dataList="regionList"
      @getCityData="getCityData"
      @isClose_city="isClose_city"
      @confim_city="confim_city"
    ></city-picker>
  </zj-page-layout>
</template>

<script>
import { getArea } from '@/common/utils/util.js'
import cityPicker from '@/components/cityPicker.vue'

export default {
  components: {
    cityPicker
  },
  data() {
    return {
      editId: null, // 编辑的id
      formData: {
        // 表单数据
        name: '',
        phone: '',
        province: '',
        city: '',
        area: '',
        street: '',
        address: '',
        houseNo: '',
        defaultAddr: false
      },
      canClickSave: true, // 能否点击提交
      clipboard: '',

      isShow: false,
      regionList: []
    }
  },

  onLoad({ id, addressData }) {
    this.editId = id
    if (id) {
      uni.setNavigationBarTitle({
        title: '编辑地址'
      })
      this.getAddressData()
    }
    if (addressData) {
      addressData = JSON.parse(addressData)
      this.formData = {
        name: addressData.name,
        phone: addressData.phone,
        province: addressData.province,
        city: addressData.city,
        area: addressData.area,
        address: addressData.address,
        houseNo: addressData.houseNo,
        defaultAddr: addressData.defaultAddr
      }
    }
  },
  methods: {
    async getRegionByAddress(address) {
      const result = new Promise((resolve, reject) => {
        this.$api
          .post('/lbs/amap/region/query2', {
            address
          })
          .then(res => {
            resolve(res.data)
          })
      })
      return result
    },

    async getRegionByLatLng(lat, lng) {
      const result = new Promise((resolve, reject) => {
        this.$api
          .post('/lbs/amap/region/query', {
            lat,
            lng
          })
          .then(res => {
            resolve(res.data)
          })
      })
      return result
    },

    async shibie() {
      // 莫阿宝，13686123158，广东省广州市天河区棠下街道天河软件园
      // console.log(this.smart(this.clipboard));
      const data = this.smart(this.clipboard)

      this.formData.name = data.name || ''
      this.formData.phone = data.phone || ''

      if (data.address) {
        let addressData = await this.getRegionByAddress(data.address)
        this.formData.province = addressData.provinceName || ''
        this.formData.city = addressData.cityName || ''
        this.formData.area = addressData.areaName || ''
        this.formData.street = addressData.name || ''
        this.formData.address =
          data.address.replace(
            `${addressData.provinceName || ''}${addressData.cityName || ''}${addressData.areaName || ''}${
              addressData.name || ''
            }`,
            ''
          ) || ''
      }
    },

    smart(data) {
      data = this.stripscript(data) //过滤特殊字符

      let obj = {}
      let copyData = JSON.parse(JSON.stringify(data)).split(' ')

      copyData.forEach((item, index) => {
        if (item) {
          let addressObj = this.smartData(item)
          console.log(addressObj)

          obj = Object.assign(obj, addressObj)
        }
      })
      return obj
    },

    smartData(data) {
      let smartObj = {}
      //address=  data.replace(/\s/g, ''); //去除空格

      // 手机号匹配（提取出手机号）
      let phone = data.match(/(86-[1][0-9]{10}) | (86[1][0-9]{10})|([1][0-9]{10})/g)

      // 如果存在手机号
      if (phone) {
        smartObj.phone = phone[0]

        if (data != phone[0]) {
          // 如果手机号是开头或结尾
          if (data.startsWith(phone[0]) || data.endsWith(phone[0])) {
            let remainData = data.replace(phone[0], '') // 除了手机号，剩下的内容
            // 如果还有剩下的内容
            if (remainData) {
              if (new RegExp(/省|市|区/).test(remainData)) {
                smartObj.address = remainData
              } else {
                smartObj.name = remainData
              }
            }
          }

          // 如果手机号在中间
          else {
            let remainDatas = data.replace(phone[0], '&&').split('&&') // 除了手机号，剩下的内容
            for (let i = 0; i < remainDatas.length; i++) {
              if (new RegExp(/省|市|区/).test(remainDatas[i])) {
                smartObj.address = remainDatas[i]
              } else {
                smartObj.name = remainDatas[i]
              }
            }
          }
        }
      }

      // 如果不存在手机号
      else {
        if (new RegExp(/省|市|区/).test(data)) {
          smartObj.address = data
        } else {
          smartObj.name = data
        }
      }

      return smartObj
    },

    // 过滤特殊字符
    stripscript(s) {
      s = s.replace(/(\d{3})-(\d{4})-(\d{4})/g, '$1$2$3')
      s = s.replace(/(\d{3}) (\d{4}) (\d{4})/g, '$1$2$3')
      var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“’。，、？-]")
      var rs = ''
      for (var i = 0; i < s.length; i++) {
        rs = rs + s.substr(i, 1).replace(pattern, ' ')
      }
      rs = rs.replace(/[\r\n]/g, '')
      return rs
    },

    // 获取地址信息
    getAddressData() {
      this.$api
        .get('/user/address/detail', {
          userAddressId: this.editId
        })
        .then(res => {
          this.formData = {
            name: res.data.name,
            phone: res.data.phone,
            province: res.data.province,
            city: res.data.city,
            area: res.data.area,
            street: res.data.street,
            address: res.data.address,
            houseNo: res.data.houseNo,
            defaultAddr: res.data.defaultAddr
          }
        })
    },

    // 地图选点
    getLocation() {
      let that = this
      uni.chooseLocation({
        success: async res => {
          console.log(res)
          let addressData = await this.getRegionByLatLng(res.latitude, res.longitude)
          that.formData.province = addressData.provinceName
          that.formData.city = addressData.cityName
          that.formData.area = addressData.areaName
          that.formData.street = addressData.name
          that.formData.address = res.address
          that.formData.houseNo = ''
        },
        fail: function (res) {
          uni.getSetting({
            success: function (res) {
              if (!res.authSetting['scope.userLocation']) {
                uni.showModal({
                  title: '是否授权当前位置',
                  content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
                  success(tip) {
                    if (tip.confirm) {
                      uni.openSetting({
                        success: function (data) {
                          if (data.authSetting['scope.userLocation'] === true) {
                            that.$successToast('授权成功')
                            setTimeout(() => {
                              that.getLocation()
                            }, 1000)
                          }
                        }
                      })
                    }
                  }
                })
              }
            }
          })
        }
      })
    },

    selectCity() {
      this.getCityData('') // 默认广东省
      this.isShow = true
    },
    getCityData(id) {
      const that = this
      this.$api
        .post(
          '/common/region',
          {
            parentId: id
          },
          false
        )
        .then(res => {
          this.regionList = res.data
        })
        .catch(() => {})
    },
    isClose_city(msg) {
      this.isShow = msg
    },
    confim_city(obj) {
      console.log(obj)
      this.formData.province = obj.province
      this.formData.city = obj.city
      this.formData.area = obj.area
      this.formData.street = obj.street
      this.isShow = false
    },

    switchChange(e) {
      this.formData.defaultAddr = e.detail.value
    },

    // 提交表单
    submitForm() {
      if (!this.canClickSave) return false
      this.canClickSave = false
      setTimeout(() => {
        this.canClickSave = true
      }, 3000)

      if (!this.formData.name) {
        return this.$toast('请填写姓名')
      }
      if (!this.formData.phone) {
        return this.$toast('请填写手机号码')
      }
      if (!/^1[3456789]\d{9}$/.test(this.formData.phone) || this.formData.phone.length != 11) {
        return this.$toast('请填写正确的手机号码')
      }
      if (!this.formData.province) {
        return this.$toast('请选择所在地区')
      }
      if (!this.formData.address) {
        return this.$toast('请填写详细地址')
      }

      let params = this.formData
      params.userId = this.$store.state.user.userId
      let url = ''
      if (this.editId) {
        params.userAddressId = this.editId
        url = '/user/address/update'
      } else {
        url = '/user/address/save'
      }
      this.$api
        .postJson(url, {
          ...params
        })
        .then(res => {
          this.crossPage.$emit('refreshAddressList', res.data)
          this.$successToast(this.editId ? '编辑成功' : '添加成功')
          this.$navToPage(
            {
              delta: 1
            },
            'navigateBack'
          )
        })
    },

    // 删除
    handleDelete() {
      this.$modal({
        content: '确定要删除该地址吗？'
      })
        .then(() => {
          this.$api
            .post('/user/address/del', {
              userAddressId: this.editId
            })
            .then(res => {
              this.crossPage.$emit('refreshAddressList', false)
              this.$successToast('删除成功')
              this.$navToPage(
                {
                  delta: 1
                },
                'navigateBack'
              )
            })
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang="scss">
.form-container {
  .clipboard {
    padding: 20rpx;
    background: #ffffff;
    .box {
      background: #f5f5f5;
      ::v-deep .u-textarea {
        background: none !important;
      }
      .btns {
        padding: 20rpx;
        display: flex;
        justify-content: flex-end;
        ::v-deep .u-button {
          width: 100rpx;
          margin-left: 30rpx;
          margin-right: 0;
        }
      }
    }
  }
  .row {
    background: #ffffff;
    min-height: 88rpx;
    padding: 0 20rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f5f5f5;
    .title {
      flex-shrink: 0;
      width: 160rpx;
      font-size: 28rpx;
      color: #333333;
    }
    .right {
      flex: 1;
      width: 0;
      input {
        font-size: 28rpx;
      }
      .picker {
        display: flex;
        align-items: center;
        justify-content: space-between;
        view {
          font-size: 28rpx;
        }
        .iconfont {
          font-size: 28rpx;
          color: $sec-font;
        }
      }
    }
    .textarea {
      display: flex;
      justify-content: space-between;
      align-items: center;
      textarea {
        padding: 16rpx 0;
        font-size: 28rpx !important;
      }
      .r {
        display: flex;
        align-items: center;
        flex-shrink: 0;
        font-size: 24rpx;
        color: #666666;
        margin-left: 15rpx;
        .iconfont {
          font-size: 36rpx;
          color: #999999;
          margin-right: 4rpx;
        }
      }
    }
    .default {
      display: flex;
      justify-content: flex-end;
      switch {
        margin-right: -20rpx;
      }
    }
  }
}
</style>
