<template>
  <view>
    <uni-list :border="false" class="address">
      <uni-list-item title="收货人">
        <view slot="footer" class="form-input">
          <input
            v-model="address.receiverName"
            class="uni-input"
            maxlength="20"
            placeholder-class="placeholder"
            placeholder="请填写收货人姓名"
          />
          <i
            v-if="address.receiverName"
            class="iconfont icon-close-plane"
            @click="clearInput('receiverName')"
          />
        </view>
      </uni-list-item>
      <uni-list-item title="手机号码">
        <view slot="footer" class="form-input">
          <input
            v-model="address.receiverPhoneNo"
            class="uni-input"
            type="number"
            maxlength="11"
            placeholder-class="placeholder"
            placeholder="请填写收货人手机号"
          />
          <i
            v-if="address.receiverPhoneNo"
            class="iconfont icon-close-plane"
            @click="clearInput('receiverPhoneNo')"
          />
        </view>
      </uni-list-item>
      <uni-list-item title="所在地区">
        <view slot="footer" class="form-input" style="padding-right: 0;">
          <view class="alipay-box" @click="showArea">
            <input
              v-model="address.addrFullName"
              :disabled="true"
              style="color: #333;"
              class="uni-input"
              placeholder-class="placeholder"
              placeholder="省市区县、乡镇等"
            />
            <!-- #ifdef MP-ALIPAY -->
            <view v-if="address.addrFullName" class="uni-input alipay-input">
              {{ address.addrFullName }}
            </view>
            <!-- #endif -->
          </view>
        </view>
      </uni-list-item>
      <uni-list-item title="详细地址">
        <view slot="footer" class="form-input">
          <textarea
            v-model="address.detail"
            style="color: #333;"
            :auto-height="isAutoHeight"
            :show-count="false"
            placeholder-class="placeholder"
            maxlength="50"
            :auto-blur="true"
            placeholder="如道路、门牌号、小区、楼栋号、单元室等"
            @blur="onTextAreaInput"
          />
          <i
            v-if="address.detail"
            class="iconfont icon-close-plane"
            @click="clearInput('detail')"
          />
        </view>
      </uni-list-item>
      <uni-list-item title="设为默认地址" class="switch-item">
        <view slot="footer">
          <switch
            :checked="address.addrDefault"
            color="#EC1500"
            style="transform: scale(0.7, 0.7);"
            @change="switchChange"
          />
        </view>
      </uni-list-item>
    </uni-list>

    <view v-if="type === 'edit'" class="row actions">
      <text class="btn-delete" @click="onDelete">删除收货地址 </text>
    </view>

    <view class="row">
      <button class="primary-btn" type="default" @click="confirmBebounce">保存</button>
    </view>

    <ActionSheet ref="popup" title="请选择所在地区" @close="onActionClose">
      <popup-area ref="area" @finish="changeArea" />
      <view class="safe-area" />
    </ActionSheet>
    <login-popup ref="login-popup" type="center" title="用户授权登录" @login="handleLogin" />
  </view>
</template>

<script>
// FIXME: 小程序输入框切换，会闪烁
import loginPopup from "@/components/loginPopup";
import popupArea from "@/components/popupArea";
import ActionSheet from "@/components/actionSheet";
import uniList from "@dcloudio/uni-ui/lib/uni-list/uni-list";
import uniListItem from "@dcloudio/uni-ui/lib/uni-list-item/uni-list-item";
import address from "@/api/address.api";
function replaceAddrStr(str, length) {
  return str.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5-]/g, "").substr(0, length);
}
export default {
  components: {
    uniList,
    uniListItem,
    popupArea,
    loginPopup,
    ActionSheet
  },
  data() {
    let isAutoHeight = true;
    /* #ifdef MP-BAIDU */
    isAutoHeight = false;
    /* #endif */
    return {
      isAutoHeight,
      type: "",
      address: {
        receiverName: "",
        receiverPhoneNo: "",
        addrFullName: "",
        detail: "",
        addrDefault: 1,
        addrReceiverId: ""
      },
      area: [],
      backTimer: null,
      setDef: false
    };
  },
  watch: {
    "address.detail": {
      handler(val) {
        this.$nextTick(() => {
          this.address.detail = this.detailScript(val);
        });
      }
    },
    "address.receiverName": {
      handler(val) {
        this.$nextTick(() => {
          console.log(val, "345");
          this.address.receiverName = this.stripscript(val);
        });
      }
    },
    immediate: true,
    deep: true
  },
  onLoad(option) {
    let title = "新增收货地址";
    this.setDef = option.from === "order";
    if (option.type === "edit") {
      title = "编辑收货地址";
      this.type = "edit";
      // 地址数据从列表带过来，不用查了
      const data = { ...this.$store.state.address };
      // 后端保存的fullname包含了detail和逗号，去掉
      data.addrFullName = data.addrFullName
        .substring(0, data.addrFullName.length - data.detail.length)
        .replace(/(，)/g, "");
      this.address = data;
    }
    // eslint-disable-next-line no-undef
    uni.setNavigationBarTitle({
      title
    });
    this.loginPopupFn();
  },
  methods: {
    stripscript(s) {
      return replaceAddrStr(s, 20);
    },
    detailScript(s) {
      return replaceAddrStr(s, 50);
    },
    loginPopupFn() {
      if (!uni.getStorageSync("token")) {
        this.$refs["login-popup"].open();
      }
    },
    switchChange(e) {
      this.address.addrDefault = e.target.value ? 1 : 0;
    },
    onActionClose() {
      // 关闭弹窗时重置area
      this.$refs.area.reset();
    },
    showArea() {
      this.$refs.popup.open();
    },
    changeArea(area) {
      this.area = area;
      this.address.addrFullName = area.map(item => item.name).join(",");
      this.$refs.popup.close();
    },
    onTextAreaInput(e) {
      this.address.detail = e.detail.value;
    },
    confirmBebounce() {
      if (this.backTimer) clearTimeout(this.backTimer);
      this.backTimer = setTimeout(() => {
        this.confirm();
      }, 600);
    },
    async confirm() {
      const data = this.address;
      console.log("data :>> ", data);

      if (!data.receiverName?.trim()) {
        this.$api.msg("请填写收货人姓名");
        return;
      }
      if (!/(^1[3|4|5|6|7|8][0-9]{9}$)/.test(data.receiverPhoneNo)) {
        this.$api.msg("请输入正确的手机号码");
        return;
      }
      if (!data.addrFullName?.trim()) {
        this.$api.msg("请选择所在地区");
        return;
      }
      if (!data.detail?.trim()) {
        this.$api.msg("请填写详细地址");
        return;
      }

      const param = Object.assign({}, this.address);
      if (this.setDef) {
        param.addrDefault = 1;
      }
      delete param.addrFullName;
      if (this.area.length) {
        param.provinceId = this.area[0].selectedId;
        param.cityId = this.area[1].selectedId;
        param.countyId = this.area[2].selectedId;
        param.townId = (this.area[3] && this.area[3].selectedId) || "";
      }

      const [res] = await address.saveAddress(param);
      if (res) {
        if (this.setDef) {
          uni.$emit("confirmPageUpdateAddress", res);
        }
        this.$api.msg(`地址${this.type == "edit" ? "修改" : "添加"}成功`);
        uni.$emit("addrAddInfo", { ...param, addrReceiverId: res.addrReceiverId });
        setTimeout(() => {
          uni.navigateBack();
        }, 400);
      }
    },
    onDelete() {
      // eslint-disable-next-line no-undef
      uni.showModal({
        content: "确认删除该地址?",
        confirmColor: "#EC1500",
        success: res => {
          if (res.confirm) {
            this.deleteAddr();
          }
        }
      });
    },
    clearInput(name) {
      this.$set(this.address, name, "");
    },
    async deleteAddr() {
      const [res] = await address.deleteAddress(this.address.addrReceiverId);
      if (res) {
        this.$api.msg("地址删除成功");
        setTimeout(() => {
          // eslint-disable-next-line no-undef
          uni.navigateBack();
        }, 400);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/style/var.scss";
@import "@/style/icon.scss";
::v-deep .uni-list {
  &--border::after {
    background-color: #ebebeb;
    height: 1rpx;
  }
  &-item {
    &__content-title {
      color: $gray-5 !important;
      @include text-size(28);
    }
    &__container {
      // align-items: center;
      padding: 36rpx 32rpx 30rpx !important;
    }
  }
}
::v-deep .placeholder {
  font-size: 28rpx;
  line-height: 40rpx;
  color: #999999;
}
.primary-btn {
  margin-top: 60px;
  @include primary-bg;
  color: white;
  font-size: $uni-font-size-base;
  font-weight: bold;
  border-radius: $uni-border-radius-xl;
  flex: 1;
}
.actions {
  margin-top: 24rpx;
  .btn-delete {
    padding: 24rpx 0;
    font-size: 28rpx;
    color: $font-color-search;
  }
}
.form-input {
  flex: 3;
  font-size: 28rpx;
  padding-right: 48rpx;
  position: relative;
}
.switch-item {
  ::v-deep .uni-list-item__container {
    align-items: center;
  }
}
::v-deep textarea {
  /* #ifdef MP-ALIPAY */
  font-size: 28rpx;
  color: #333;
  /* #endif */
  width: 100%;

  /* #ifndef MP-BAIDU */
  min-height: 128rpx;
  max-height: 300rpx;
  /* #endif */

  /* #ifdef MP-BAIDU */
  height: 158rpx;
  /* #endif */
}
.icon-close-plane {
  position: absolute;
  z-index: 3;
  right: 0;
  top: 0;
  padding: 10rpx;
  color: #c1c2c5;
  font-size: 28rpx;
  text-align: center;
}
::v-deep .uni-input {
  font-size: 28rpx;
  color: #333;
  width: 100%;
}
/* #ifdef MP-ALIPAY */
.alipay-box {
  position: relative;
  .alipay-input {
    position: absolute;
    height: 100%;
    top: 0;
    display: flex;
    align-items: center;
    background-color: #fff;
  }
}
::v-deep .uni-list-item__content-title {
  margin-top: 5rpx;
}
/* #endif */
</style>
