<template>
  <div>
    <div class="address">
      <cr-form>
        <cr-field
          v-model="address.receiverName"
          class="address-input"
          name="收货人"
          label="收货人"
          placeholder="请输入收货人姓名"
        />
        <cr-field
          v-model="address.receiverPhoneNo"
          class="address-input"
          name="手机号码"
          label="手机号码"
          placeholder="请输入收货人手机号码"
        />
        <cr-field class="address-input" name="所在地区" label="所在地区">
          <template #input>
            <popup-area-tab-picker
              ref="areaPicker"
              v-model="address.addrFullName"
              :placeholder="address.addrFullName || '省市区县、乡镇等'"
              @finish="handleAreaSelect"
              @popup="handlePickerShow"
            />
          </template>
        </cr-field>
        <cr-field
          class="address-input"
          name="详细地址"
          label="详细地址"
          placeholder="如道路、门牌号、小区、楼栋号、单元室等"
        >
          <template #input>
            <textarea
              v-model="address.detail"
              class="address-input-textarea"
              placeholder="如道路、门牌号、小区、楼栋号、单元室等"
              :autosize="{ minRows: 3, maxRows: 10 }"
            />
          </template>
        </cr-field>
        <cr-cell title="设置默认地址" class="address-input">
          <cr-switch
            v-model="address.addrDefault"
            size="20px"
            :active-value="1"
            :inactive-value="0"
          />
        </cr-cell>
      </cr-form>
    </div>
    <div v-if="type === 'edit'" class="row actions">
      <span class="btn-delete" @click="onDelete">删除收货地址 </span>
    </div>
    <cr-button
      shape="circle"
      block
      type="danger"
      class="address-list__form-btn"
      @click="confirmBebounce"
      >保存</cr-button
    >
  </div>
</template>
<script>
import address from '@/api/address.api';
import { EventBus } from '@/service/utils.service';
import PopupAreaTabPicker from '@/components/popupAreaTabPicker';
const ADDRESS_ADD = 'addressAdd';
export default {
  components: {
    PopupAreaTabPicker
  },
  data() {
    return {
      type: '', // 是否是编辑
      addressCode: '',
      address: {
        receiverName: '',
        receiverPhoneNo: '',
        addrFullName: '',
        detail: '',
        addrDefault: 1,
        addrReceiverId: ''
      },
      pickerState: false,
      addressSource: [],
      backTimer: null,
      order: ''
    };
  },
  mounted() {
    this.type = this.$route.query.type || '';
    this.order = this.$route.query.type || false;
    console.log(this.order);
    if (this.type === 'edit') {
      const data = { ...this.$route.params.editAddress };
      data.addrFullName = data.addrFullName
        .substring(0, data.addrFullName.length - data.detail.length)
        .replace(/(，)/g, '');
      this.address = data;
    }
  },
  methods: {
    handlePickerShow(e) {
      this.pickerState = e;
    },
    handleAreaSelect(source) {
      // 监听弹出框子组件传出的地址
      this.addressSource = source.items;
    },
    confirmBebounce() {
      if (this.backTimer) clearTimeout(this.backTimer);
      this.backTimer = setTimeout(() => {
        this.confirm();
      }, 600);
    },
    async confirm() {
      const data = this.address;
      if (!data.receiverName) {
        this.$toast('请填写收货人姓名');
        return;
      }
      if (!/(^1[3|4|5|7|8][0-9]{9}$)/.test(data.receiverPhoneNo)) {
        this.$toast('请输入正确的手机号码');
        return;
      }
      if (!data.addrFullName) {
        this.$toast('请选择所在地区');
        return;
      }
      if (!data.detail) {
        this.$toast('请填写详细地址');
        return;
      }
      const param = Object.assign({}, this.address);
      if (this.setDef) {
        param.addrDefault = 1;
      }
      delete param.addrFullName;
      if (this.addressSource.length) {
        param.provinceId = this.addressSource[0].addrId;
        param.cityId = this.addressSource[1].addrId;
        param.countyId = this.addressSource[2].addrId;
        param.townId = (this.addressSource[3] && this.addressSource[3].addrId) || '';
      }
      const [res] = await address.saveAddress(param);
      if (res) {
        // 不是编辑状态则从
        this.type !== 'edit' && EventBus.$emit(ADDRESS_ADD, res); // 不是编辑状态，向详情页面派发事件到返回值
        const addressList = { ...param, addrReceiverId: res.addrReceiverId };
        this.$toast(`地址${this.type == 'edit' ? '修改' : '添加'}成功`);
        console.log(this.order);
        if (this.order) {
          this.$router.push({
            name: 'createOrder',
            params: { addressList, orderAdder: this.order }
          });
          return;
        }
        setTimeout(() => {
          // 返回之前页面
          this.$router.go(-1);
        }, 400);
      }
    },
    onDelete() {
      const _this = this;
      this.$dialog({
        title: '',
        message: '确认删除该地址?',
        onConfirm: function() {
          _this.deleteAddr();
        }
      });
    },
    async deleteAddr() {
      const [res] = await address.deleteAddress(this.address.addrReceiverId);
      if (res) {
        this.$toast('地址删除成功');
        setTimeout(() => {
          this.$router.go(-1);
        }, 400);
      }
    }
  }
};
</script>
<style lang="less" scoped>
.address {
  &-input {
    font-size: 15px;
    color: #666;
    &-textarea {
      border: 0;
      resize: none;
      min-height: 42px;
      width: 85%;
      font-size: 15px;
    }
  }
  &-list__form-btn {
    margin: 60px auto;
    width: 90%;
    background: @gradient-red;
  }
}
.actions {
  padding-left: 20px;
  .btn-delete {
    padding: 12px 0;
    font-size: 14px;
    color: @font-color-search;
  }
}
</style>
