<template>
  <view class="body-background"></view>
  <u-navbar
      :title="title"
      :auto-back="true"
      left-icon-size="40rpx"
      :safe-area-inset-top="true"
      :placeholder="true"
      bgColor="#fff"
  ></u-navbar>
  <u-row :custom-style="{padding:'16rpx 26rpx'}">
    <u-col :custom-style="{backgroundColor:'#ffffff',borderRadius:'10rpx',padding:'30rpx 40rpx'}">
      <u-form
          errorType="toast"
          labelPosition="left"
          :model="model"
          :rules="rules"
          ref="addrForm"
          labelWidth="200rpx"
      >
        <u-form-item
            :custom-style="{
                  padding:'36rpx 0'
              }"
            label="姓名"
            prop="address.name"
            borderBottom
        >
          <u-input
              fontSize="28"
              placeholder="请填写您的真实姓名"
              v-model="model.address.name"
              border="none"
          ></u-input>
        </u-form-item>
        <u-form-item
            :custom-style="{
                  padding:'36rpx 0'
              }"
            label="手机号码"
            prop="address.phone"
            borderBottom
        >
          <u-input
              fontSize="28"
              placeholder="请输入"
              v-model="model.address.phone"
              border="none"
          ></u-input>
        </u-form-item>
        <u-form-item
            :custom-style="{
                  padding:'36rpx 0'
              }"
            label="地区"
            prop="address.area"
            borderBottom
        >
          <u-text
              suffixIcon="arrow-right"
              :icon-style="{color:'#AFB5BE'}"
              :text="(model.address.area)?model.address.area:'请选择地区'"
              size="28"
              :color="(model.address.area)?'#303133':'#AFB5BE'"
              @click="selectAddress"
          ></u-text>

        </u-form-item>
        <u-form-item
            :custom-style="{
                  padding:'36rpx 0'
              }"
            label="详细地址"
            prop="address.address"
            borderBottom
        >
          <u-input
              fontSize="28"
              placeholder="请输入详细收货地址"
              v-model="model.address.address"
              border="none"
          ></u-input>
        </u-form-item>
        <u-form-item
            :custom-style="{
                  padding:'36rpx 0'
              }"
            label="设为默认收货地址"
            prop="address.is_default"
            labelWidth="260rpx"
        >
          <u-switch
              size="32"
              :custom-style="{marginLeft:'auto'}"
              v-model="model.address.is_default"
              activeColor="#FF9545"
              inactiveColor="#DDDDDD"
              :inactiveValue="0"
              :activeValue="1"
          >

          </u-switch>
        </u-form-item>

      </u-form>
    </u-col>
  </u-row>
  <view class="foot-button border-box">
    <u-button
        type="primary"
        text="保存"
        shape="circle"
        :custom-style="{
              color:'#020B18',
              backgroundColor:'#FF9545',
              border:'none',
              fontSize:'36',
              fontWeight:'400',
              height:'80rpx'
            }"
        @click="submit"
    ></u-button>
  </view>
</template>

<script>
import {
  imghost
} from '@/config/host.js'
import MzSubsection from '@/components/MzSubsection/Index.vue';
import api from '@/utils/functions.js';
import {userAddrAdd, userAddrEdit, userDetail, userEdit} from "@/api/user";

export default {
  components: {
    MzSubsection
  },
  data() {
    return {
      switchValue:false,
      model: {
        address: {
          name:'',
          phone: '',
          area:'',
          address:'',
          is_default:0,
        },
      },
      rules: {
        'address.name': {
          type: 'string',
          required: true,
          message: '请填写姓名',
          trigger: ['blur', 'change']
        },
        'address.phone': {
          type: 'string',
          required: true,
          message: '请填写电话',
          trigger: ['blur', 'change']
        },
        'address.area': {
          type: 'string',
          required: true,
          message: '请填写地区',
          trigger: ['blur', 'change']
        },
        'address.address': {
          type: 'string',
          required: true,
          message: '请填写详细地址',
          trigger: ['blur', 'change']
        },
      },
      value:1,
      options: [
        {
          text: '删除',
          style: {
            backgroundColor: '#FC4956'
          }
        }
      ],
      title: '添加收货地址',
      loading: true,
      staticImage: {
        bg: imghost + '/BG.png',
        newIcon: imghost + '/new-icon.png',
      },
      isTop: false,
      lists: [],
      size: {
        height: 500,
      }
    }
  },
  onLoad(option) {
    if(option.type !== '' && option.type){
        this.type = option.type;
        if(option.type === 'create'){
          let user = uni.getStorageSync('user');
          this.model.address.name = user.name;
          this.model.address.phone = user.phone;
          this.model.address.address = user.community + user.street;
        }
    }
   if(option.detail !== '' && option.detail){

     this.model.address = JSON.parse(option.detail);
     console.log(this.model.address)
   }
  },
  computed: {
    api() {
      return api
    },
    sectionStyle() {
      const style = {};
      style.padding = '0 26rpx';
      style.position = 'sticky';
      style.zIndex = '9999';
      style.top = api.navHeight().systemBarHeight + 'px'
      return style;
    },
    listHeight() {
      let that = this;
      let height;
      let info = uni.createSelectorQuery().in(this).select('.subsection');
      info.boundingClientRect(function (data) {
        that.size.height = data.height;
      }).exec(function (res) {

      });
      // that.size.height = (api.navHeight().windowHeight - height);
    }
  },
  methods: {
    chatDetail(item) {
      wx.navigateTo({
        url: '/pages/ChatDetail/index?id=' + item.id
      });
    },
    checkSection(index) {
      this.current = index;
    },
    scrollToLower() {

    },
    getAddrDetail(id){

    },
    submit(){
      this.$refs.addrForm.validate().then(res => {
        let result;
        console.log(this.model)
        if(this.model.address.id !== '' && this.model.address.id !== undefined){
           result = userAddrEdit(this.model.address);
        }else{
           result = userAddrAdd(this.model.address);
        }

        result.then((res) => {
          if(res.code === 200){
            uni.$u.toast((this.model.address.id !== '')?'修改成功':'创建成功')
            let pages = getCurrentPages(); // 当前页面
            let beforePage = pages[pages.length - 2]; // 上一页
            uni.navigateBack({
              success: function() {
                beforePage.onLoad(); // 执行上一页的onLoad方法
              }
            });
          }else{
            uni.$u.toast(res.msg)
          }
        })


      }).catch(errors => {
        uni.$u.toast(errors[0].message)
      })
    },
    //选择地址
    selectAddress() {
      let that = this;
      uni.getLocation({
        type: 'gcj02',
        success: function (res1) {
          uni.chooseLocation({
            latitude:res1.latitude||'',
            longitude:res1.longitude||'',
            success: (res) => {
              that.lat = res.latitude;
              that.lng = res.longitude;
              that.model.address.area = res.address;
            },
            fail: (err) => {
              console.log(err)
            }
          });
        },
      });

    },
  },
  onPageScroll(res) {
    if (res.scrollTop <= 20) {
      uni.$emit('isTop', true);
    } else {
      uni.$emit('isTop', false);
    }
  },
  created() {
    this.listHeight();
    // this.pagePadding = (api.navHeight().navPaddingTop +
    // 	api.navHeight().navHeight + (api.navHeight().headerPadding * 2))
  }
}
</script>

<style lang="scss">
@import './components/edit.scss';
</style>