<template>
  <div>
    <div class="address">
      <cr-form>
        <cr-field
          v-model.trim="address.receiverName"
          class="address-input"
          name="收货人"
          label="收货人"
          :max-length="20"
          placeholder="请输入收货人姓名,最多20个字"
          @input="stripscript"
        />
        <cr-field
          v-model.trim="address.receiverPhoneNo"
          class="address-input"
          name="手机号码"
          label="手机号码"
          :max-length="11"
          placeholder="请输入收货人手机号码"
        />
        <cr-field class="address-input area" name="所在地区" label="所在地区">
          <template #input>
            <popup-area-tab-picker
              ref="areaPicker"
              v-model.trim="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.trim="address.detail"
              class="address-input-textarea"
              placeholder="如道路、门牌号、小区、楼栋号、单元室等"
              :autosize="{ minRows: 3, maxRows: 10 }"
              :maxlength="50"
              @change="detailScript"
            />
          </template>
        </cr-field>
        <cr-cell title="设置默认地址" class="address-input">
          <cr-switch
            v-model.trim="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';
import { isPhone } from '@/service/validation.service';
const ADDRESS_ADD = 'addressAdd';
function replaceAddrStr(str = '', length) {
  return str.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5-]/g, '').substr(0, length);
}
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.params.order || false;
    if (this.type === 'edit') {
      const data = { ...this.$route.params.editAddress };
      if (data) {
        data.addrFullName = data.addrFullName
          ?.substring(0, data.addrFullName.length - data.detail.length)
          .replace(/(，)/g, '');
        this.address = data;
      }
    }
  },
  methods: {
    stripscript(s) {
      this.$nextTick(() => {
        this.address.receiverName = replaceAddrStr(s, 20);
      });
    },
    detailScript(s) {
      const v = s?.target?.value;
      this.$nextTick(() => {
        this.address.detail = replaceAddrStr(v, 50);
      });
    },
    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;
      }
      const phoneLen = 11;
      if (data.receiverPhoneNo.length !== phoneLen || !isPhone(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' ? '修改' : '添加'}成功`);
        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;
  }
}
.address-input {
  overflow: hidden;
}
.area {
  height: 46px;
  overflow: hidden;
}
</style>
