<template>
  <div class="apply-form-wrap">
    <nav-bar title="申请预定"/>
    <div class="wrap">
      <div class="form" v-if="!isDone">
        <div
          class="items goods" v-if="item">
          <div class="img pr">
            <img v-if="item.img" :src='item.img'>
            <img v-else src="../assets/imgs/buildings-img@2x.png" alt="">
          </div>
          <div class="info">
            <h4 class="lineTwoHidden">{{item.houseName}}</h4>
            <p class="lineHidden" v-show="item.rentTime">起租时间：{{item.rentTime}}</p>
            <p class="lineHidden" v-show="item.rentNum">最短租期：{{item.rentNum}}</p>
            <div class="price">
              <i>{{item.moneyUnit}}</i>
              <p>{{item.priceText}}</p>
              <span v-show="item.rentTimeUnit">/{{item.rentTimeUnit}}</span>
            </div>
          </div>
        </div>
        <div class="phone common allLine">
          <div>
            <input type="text" placeholder="手机号" disabled>
            <p class="areaCode" @click="getAreaCode">
              <span>{{areaCodeItem.code}}</span>
              <i class="icon icon-jiantou-xia"></i>
            </p>
          </div>
          <input type="number" class="text-r" v-model="form.mobile">
        </div>
        <div class="code common">
          <div class="allLine">
            <input type="text" placeholder="验证码" disabled>
            <input type="number" class="text-r" v-model="form.verfyCode">
          </div>
          <div class="flex_c align-c">
            <p class="getCode active" @click="getVerfyCode" v-if="number == 0">获取验证码</p>
            <p class="getCode" v-else>重新发送（{{number}}）</p>
          </div>
        </div>
        <div class="line"></div>
        <div class="date common allLine city" @click="getCity" v-if="isService">
          <input type="text" placeholder="选择城市" disabled>
          <div class="flex text-r">
            <p class="lineHidden" v-if="serviceCityItem">{{serviceCityItem.countryName}} {{serviceCityItem.cityName}}</p>
            <i class="icon icon-jiantou-you"></i>
          </div>
        </div>
        <div class="date common allLine" @click="showDate = true">
          <input type="text" placeholder="入住日期" disabled>
          <div class="flex text-r">
            <p class="lineHidden">{{form.liveTime}}</p>
            <i class="icon icon-jiantou-you"></i>
          </div>
        </div>
        <div class="name common">
          <div class="common allLine">
            <input type="text" placeholder="姓" disabled>
            <input type="text" class="text-r" v-model="form.firstName">
          </div>
          <div class="common allLine">
            <input type="text" placeholder="名" disabled>
            <input type="text" class="text-r" v-model="form.lastName">
          </div>
        </div>
        <div class="mail common allLine">
          <input type="text" placeholder="邮箱" disabled>
          <input type="mail" class="text-r" v-model="form.email">
        </div>
        <div class="mail common allLine">
          <input type="text" placeholder="微信" disabled>
          <input type="text" class="text-r" v-model="form.wechatId">
        </div>
        <div class="remark">
          <p>备注（选填）</p>
          <textarea v-model="extRemarks"></textarea>
        </div>
        <div class="btn">
          <van-button
            type="default"
            @click="saveData"
            :class="{disabled: disabled}"
          >提交申请</van-button>
        </div>
      </div>
      <div class="done" v-else>
        <img src="../assets/imgs/done@2x.png" alt="">
        <h5>提交申请成功！</h5>
        <p>小狸会迅速安排私人顾问联系您</p>
        <div class="btn">
          <van-button type="default" @click="back">确定</van-button>
        </div>
      </div>
    </div>
    <van-popup v-model="showDate" position="bottom">
      <van-datetime-picker
        v-model="liveTime"
        type="date"
        @confirm="setDate"
        :min-date="minDate"
      />
    </van-popup>
  </div>
</template>

<script>
import NavBar from "@/components/common/NavBar";

export default {
  name: "ApplyForm",
  components: {
    NavBar
  },
  data() {
    return {
      form: {
        mobile: null,
        mobileCountryId: "317",
        mobilePrefix: "+86",
        verfyCode: null,
        liveTime: null,
        firstName: null,
        lastName: null,
        email: null,
        wechatId: null
      },
      areaCodeItem: {
        id: "317",
        name: "中国",
        code: "+86"
      },
      cityItem: this.$util.storage.fetch("CityItem"),
      lang: this.$store.state.langStr,
      number: 0,
      item: null,
      extRemarks: null,
      liveTime: null,
      minDate: new Date(),
      disabled: true,
      disabledSend: false,
      showDate: false,
      isDone: false,
      serviceCityItem: {
        countryName: null,
        cityName: null,
        countryId: null,
        cityId: null
      },
      isService: false
    };
  },
  created() {
    // 获取国家区号
    let areaCodeItem = this.$util.storage.fetch("areaCodeItem");
    if (areaCodeItem) this.areaCodeItem = areaCodeItem;
    if (this.$route.query.houseId)
      this.item = this.$util.sessionStorage.fetch("buildingInfo");
    // 判断页面来源
    if (this.$util.sessionStorage.fetch("isService")) {
      this.isService = true;
      // 获取真实国家城市数据
      this.serviceCityItem = JSON.parse(
        this.$util.sessionStorage.fetch("serviceCityItem")
      );
    } else {
      this.isService = false;
    }
    let form = JSON.parse(
      decodeURIComponent(this.$util.sessionStorage.fetch("applyForm"))
    );
    if (form) {
      this.form = form;
    } else {
      if (this.$util.getLoginUserInfo()) {
        let data = JSON.parse(
          decodeURIComponent(this.$util.getLoginUserInfo())
        );
        for (const i in data) {
          if (data.hasOwnProperty(i)) {
            const element = data[i];
            if (i in this.form) {
              this.form[i] = element;
            }
          }
        }
      }
    }
  },
  beforeRouteLeave(to, from, next) {
    if (to.name !== "guide") {
      this.$util.sessionStorage.remove("isService");
      this.$util.sessionStorage.remove("serviceCityItem");
    }
    next();
  },
  watch: {
    form: {
      handler: function(val) {
        let n = 0;
        let form = encodeURIComponent(JSON.stringify(this.form));
        this.$util.sessionStorage.save("applyForm", form);
        for (const key in val) {
          if (val.hasOwnProperty(key)) {
            const element = val[key];
            if (!element) n++;
          }
        }
        if (this.isService) {
          if (!this.serviceCityItem.countryId || !this.serviceCityItem.cityId) {
            n++;
          }
        }
        n ? (this.disabled = true) : (this.disabled = false);
      },
      deep: true
    }
  },
  methods: {
    // 跳转选择国家城市
    getCity() {
      this.$router.push({
        path: `/${this.lang}/guide`
      });
    },
    // 发送验证码
    getVerfyCode() {
      if (this.disabledSend) {
        return;
      }
      this.disabledSend = true;
      let regMobile = /^[0-9]*$/;
      let params = {};
      params.url = this.$apis.api_user_verification;
      params.data = {
        mobile: this.form.mobile,
        countryId: this.areaCodeItem.id,
        status: "8"
      };
      if (!regMobile.test(this.form.mobile)) {
        this.$Toast("手机格式不正确");
        setTimeout(() => {
          this.disabledSend = false;
        }, 1000);
        return false;
      }
      this.$net.req(params, this).then(
        res => {
          if (Number(res.code) === 0) {
            this.time();
          }
          setTimeout(() => {
            this.disabledSend = false;
          }, 1000);
        },
        e => {
          setTimeout(() => {
            this.disabledSend = false;
          }, 1000);
          this.$Toast(e.msg);
        }
      );
    },
    // 倒计时
    time() {
      var num = 60;
      let name = setInterval(() => {
        num--;
        this.number = num;
        if (num === 0) {
          this.disabledSend = false;
          clearInterval(name);
        }
      }, 1000);
    },
    // 保存数据
    saveData() {
      if (!this.cityItem) {
        this.$Toast("请选择城市");
        setTimeout(() => {
          this.$router.push({
            path: `/${this.lang}/guide`
          });
        }, 1000);
        return;
      }
      if (!this.disabled) {
        // 获取国家ID
        let countryArr = this.$store.state.countryArr;
        let cityName = this.cityItem.name;
        let cityId = this.cityItem.id;
        let countryId = null;
        countryArr.some(el => {
          el.son.some(element => {
            if (
              cityName === element.name &&
              Number(cityId) === Number(element.id)
            ) {
              countryId = el.id;
              return true;
            }
          });
        });
        let reg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
        if (this.form.verfyCode.trim().length != 6) {
          this.$Toast("请输入正确的验证码");
          return;
        }
        if (!reg.test(this.form.email.trim())) {
          this.$Toast("请输入正确的邮箱地址");
          return;
        }
        if (this.form.firstName.trim().length > 15) {
          this.$Toast("姓最多输入15个字符");
          return;
        }
        if (this.form.lastName.trim().length > 30) {
          this.$Toast("名最多输入30个字符");
          return;
        }
        if (this.extRemarks && this.extRemarks.trim().length > 200) {
          this.$Toast("备注最多输入200个字符");
          return;
        }
        if (this.isService) {
          if (!this.serviceCityItem.countryId || !this.serviceCityItem.cityId) {
            this.$Toast("请选择国家城市");
            return;
          }
        }
        // 保存数据
        if (this.form.mobile && this.form.verfyCode) {
          if (this.disabled) return;
          this.disabled = true;
          let params = {};
          params.url = this.$apis.api_order_apply;
          params.data = Object.assign({}, this.form);
          params.data.mobileCountryId = this.areaCodeItem.id;
          params.data.mobilePrefix = this.areaCodeItem.code;
          params.data.roomAttrId = 0;
          if (this.$route.query.houseId) {
            params.data.houseId = this.$route.query.houseId;
          }
          if (this.$route.query.roomId) {
            params.data.roomId = this.$route.query.roomId;
          }
          if (this.extRemarks) {
            params.data.extRemarks = this.extRemarks;
          }
          if (this.isService) {
            params.data.countryId = this.serviceCityItem.countryId;
            params.data.cityId = this.serviceCityItem.cityId;
          } else {
            params.data.countryId = countryId;
            params.data.cityId = cityId;
          }
          this.$net.req(params, this).then(
            res => {
              if (Number(res.code) === 0) {
                this.$Toast(res.msg);
                this.$util.sessionStorage.remove("buildingInfo");
                this.$util.sessionStorage.remove("isService");
                this.$util.sessionStorage.remove("serviceCityItem");
                this.$util.sessionStorage.remove("applyForm");
                this.isDone = true;
              } else {
                this.$Toast(res.err);
              }
            },
            e => {
              this.$Toast(e.msg);
              setTimeout(() => {
                this.disabled = false;
              }, 1000);
            }
          );
        } else {
          return;
        }
      }
    },
    // 跳转国家区号选择
    getAreaCode() {
      this.$router.push({
        path: "/" + this.lang + "/areaCode"
      });
    },
    // 选择日期
    setDate(val) {
      this.form.liveTime = this.$util.timestampToDate(Date.parse(val));
      this.showDate = false;
    },
    // 返回
    back() {
      window.history.length > 1 ? this.$router.go(-1) : this.$router.push("/");
    }
  }
};
</script>

<style scoped lang='less'>
.apply-form-wrap {
  background: #fff;
  min-height: 100vh;
  .wrap {
    padding: 15px 20px;
    .items.goods {
      padding: 0 0 10px;
      img {
        width: 132px;
        height: 100px;
        border-radius: 4px;
      }
      .info {
        h4 {
          font-size: 17px;
          color: #222;
        }
        > p {
          font-size: 14px;
          margin-bottom: 2px;
        }
      }
      .price {
        margin-top: 5px;
      }
    }
    .items.goods:after {
      height: 0;
    }
    .form {
      .common {
        width: 100%;
        height: 60px;
        display: flex;
        align-items: center;
        margin-bottom: 10px;
      }
      input {
        border: 0;
        height: 60px;
        padding: 10px 15px;
        background: transparent;
      }
      .text-r {
        text-align: right;
        width: 100%;
        padding-left: 0;
      }
      .allLine {
        background: rgba(249, 249, 249, 1);
        border-radius: 4px;
      }
      .city {
        > input {
          width: 40%;
        }
      }
      .phone {
        div {
          display: flex;
          width: 40%;
          align-items: center;
          input {
            color: #222;
            font-size: 16px;
            width: 75px;
            padding-right: 10px;
          }
          .areaCode {
            height: 30px;
            border-radius: 4px;
            border: 1px solid #999;
            display: flex;
            align-items: center;
            padding: 0 4px;
            margin: 0 -10px 0 -2px;
            span {
              color: #444;
              font-size: 13px;
              flex-shrink: 0;
            }
            i {
              font-size: 10px;
              margin-left: 5px;
              flex-shrink: 0;
              width: auto;
              height: auto;
              color: #444;
            }
          }
        }
        > input {
          width: 60%;
          color: #222;
          font-size: 16px;
        }
      }
      .code {
        > div {
          width: 100%;
          height: 100%;
          input {
            width: 60%;
            padding: 0 15px 0 0;
          }
          input:first-child {
            width: 40%;
            padding: 0 0 0 15px;
          }
          .getCode {
            color: #ddd;
            font-size: 16px;
          }
          .active {
            color: #ff523d;
          }
        }
        > div:first-child {
          width: 180px;
          flex-shrink: 0;
        }
      }
      .name {
        > div:first-child {
          width: 40%;
          margin-right: 10px;
          input {
            width: 70%;
            padding-left: 0;
          }
          > input:first-child {
            width: 30%;
            padding: 0 0 0 15px;
          }
        }
        > div:last-child {
          width: 60%;
          input {
            width: 70%;
            padding-left: 0;
          }
          > input:first-child {
            width: 30%;
            padding: 0 0 0 15px;
          }
        }
      }
      .date {
        > div {
          width: 100%;
          justify-content: flex-end;
          padding-right: 15px;
        }
        p {
          color: #222;
          font-size: 16px;
        }
        i {
          color: #bbb;
          margin-left: 10px;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
      .mail {
        input:first-child {
          width: 30%;
          padding-right: 0;
        }
      }
      .line {
        height: 1px;
        background: #ddd;
        width: 100%;
        margin: 20px 0;
      }
      .remark {
        background: #f9f9f9;
        border-radius: 4px;
        padding: 15px;
        height: 150px;
        width: 100%;
        margin-bottom: 10px;
        p {
          font-size: 16px;
          font-weight: 500;
          color: rgba(187, 187, 187, 1);
          line-height: 23px;
        }
        textarea {
          resize: none;
          height: 90px;
          font-size: 16px;
          color: #333;
          line-height: 23px;
          background: transparent;
          border: 0;
          font-weight: 500;
          width: 100%;
        }
      }
      ::-webkit-input-placeholder {
        color: #bbb;
      }
      ::-moz-placeholder {
        color: #bbb;
      }
      ::-moz-placeholder {
        color: #bbb;
      }
      :-ms-input-placeholder {
        color: #bbb;
      }
      .btn {
        button {
          width: 100%;
          height: 45px;
          font-size: 18px;
          border-radius: 25px;
          color: #fff;
          font-weight: 500;
          border: 0;
          background: #ff523d;
        }
        .disabled {
          background: #ffbfab;
        }
      }
    }
    .done {
      text-align: center;
      padding: 90px 0 0;
      img {
        width: 75px;
        height: 75px;
      }
      h5 {
        font-size: 18px;
        color: #333;
        line-height: 30px;
        margin: 20px 0 0;
        font-weight: 400;
      }
      p {
        font-size: 13px;
        color: #999;
        line-height: 30px;
        margin: 0 0 30px;
        font-weight: 400;
      }
      .btn {
        button {
          width: 200px;
          height: 45px;
          font-size: 18px;
          background: #fff;
          border-radius: 23px;
          color: #ff523d;
          font-weight: 400;
          border-color: #ff523d;
        }
      }
    }
  }
}
</style>
