<template>
  <section class="page-container page-csp">
    <template v-if="showState===1">
    <div class="walk-conatiner">
        <img
        class="walk"
        src="//static.hoolihome.com/common/default/loading.gif"/>
    </div>
    </template>
    <template v-else-if="showState===2">
        <div v-if="isShowAreaCode && countryPreFixArr" class="guide-wrap">
      <van-nav-bar
        :title="csp.selectNumber"
        left-text=""
        left-arrow
        @click-left="
          () => {
            isShowAreaCode = false
          }
        "
      >
      </van-nav-bar>
      <div class="flex wrap pr">
        <div class="city">
          <div v-for="(item, index) in countryPreFixArr" :key="index">
            <span :id="item.name">{{ item.name }}</span>
            <div v-for="child in item.list" :key="child.id" class="line">
              <div @click="selectCountry(child)">
                <p>{{ child.name }}</p>
                <div class="title-line"></div>
                <p>{{ child.code }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-else class="main">
        <div class="header">
             <img src="//static.hoolihome.com/m/assets/img/csp.png" />
             <div class="text">
                 <h3>{{csp.title}}</h3>
                 <div class="title-line"></div>
                 <p>{{csp.brief1}}</p>
                 <p>{{csp.brief2}}</p>
             </div>
        </div>
      <form class="content">
        <div class="input-box" @click="dataTime">
          <span v-if="!form.liveTime" class="placeholder">{{csp.livingTime}}</span>
          <span v-else>{{ form.liveTime }}</span>
          <span class="icon icon-rili"></span>
        </div>
        <van-popup v-model="show" position="bottom">
          <van-datetime-picker
          :confirm-button-text="csp.confirmButton"
          :cancel-button-text="csp.cancelButton"
            v-model="currentDate"
            type="date"
            :min-date="minDate"
            @cancel="() => (show = false)"
            @confirm="confirm"
          />
        </van-popup>

        <div class="input-box">
          <input @blur="handleBlur" v-model="form.firstName" :placeholder="`${csp.firstName}`" value="" />
        </div>
        <div class="input-box">
          <input @blur="handleBlur" v-model="form.lastName" :placeholder="csp.lastName" value="" />
        </div>
        <div class="both-input" @click="() => (showCountry = true)">
          <div class="input-box left">
            <span v-if="!country" class="placeholder">{{csp.country}}</span>
            <span v-else>{{ country }}</span>
            <span class="icon icon-xiala1"></span>
          </div>
          <div class="input-box right">
            <span v-if="!city" class="placeholder">{{csp.city}}</span>
            <span v-else>{{ city }}</span>
            <span class="icon icon-xiala1"></span>
          </div>
        </div>
        <van-popup v-model="showCountry" position="bottom">
          <van-picker
            v-if="countryArr.length > 0"
            :confirm-button-text="csp.confirmButton"
          :cancel-button-text="csp.cancelButton"
            show-toolbar
            :columns="columns"
            value-key="name"
            @change="onChange"
            @cancel="() => (showCountry = false)"
            @confirm="confirmCities"
          />
          <div v-else class="loading-box">
            <van-loading />
          </div>
        </van-popup>
        <div class="input-box">
          <div class="prefix" @click="() => (isShowAreaCode = true)">
            <span>{{ form.mobilePrefix }}</span>
            <span class="icon icon-xiala1"></span>
          </div>
          <input @blur="handleBlur" v-model="form.mobile" :placeholder="csp.mobile" value="" />
        </div>
        <div class="input-box verfyCode">
          <input @blur="handleBlur" v-model="form.verfyCode" :placeholder="csp.mobileCode" value="" />
          <span v-if="number == 0" @click="getVerfyCode">{{csp.btnGetCode}}</span>
          <p v-else class="getCode">{{csp.getCodeAgain}}（{{ number }}）</p>
        </div>
        <div class="input-box">
          <input @blur="handleBlur"  v-model="form.email" :placeholder="csp.email" />
        </div>
        <div class="input-box">
          <input @blur="handleBlur" v-model="form.wechatId" :placeholder="csp.wechat" />
        </div>
        <textarea
          v-model="form.extRemarks"
          class="textarea"
          :placeholder="csp.extRemarks"
          @blur="handleBlur"
        ></textarea>
        <div :class="['button', disabled ? 'disabled' : '']" @click="validate">
          {{csp.submitApply}}
        </div>
      </form>
    </div>
    <div class="online-service-wrap display-center-center" @click="handleQimo">
        <i class="icon icon-kefu"></i>
        <p>{{csp.online}}</p>
    </div>
    </template>
  </section>
</template>

<script>
const cspCn = {
  metaTitle: "海外租房_留学生租房_留学生公寓 - hooli官网",
  selectNumber: "选择号码地区",
  online: "客服",
  title: "帮你找房",
  brief1: "说出您的诉求，",
  brief2: "我们会安排专业租房顾问为您找房",
  livingTime: "入住时间*",
  firstName: "姓*",
  lastName: "名*",
  country: "国家*",
  city: "城市*",
  mobile: "手机号*",
  mobileCode: "验证码*",
  email: "邮箱*",
  wechat: "微信*",
  extRemarks: "备注",
  btnGetCode: "点击获取验证码",
  submitApply: "提交申请",
  getCodeAgain: "重新获取",
  tipsMobile: "手机格式不正确",
  tipsCode: "请输入正确的短信验证码",
  tipsEmail: "请输入正确的邮箱",
  confirmButton: "确认",
  cancelButton: "取消"
};
const cspEn = {
  metaTitle:
    "Student accommodation_Buying a house abroad_Apartments of foreign students_hooli",
  selectNumber: "Selection of Number Area",
  online: "online",
  title: "Help you find a room",
  brief1: "Say your request, ",
  brief2:
    "we will arrange a professional rental consultant to find a room for you.",
  livingTime: "Living time*",
  firstName: "First name*",
  lastName: "Last name*",
  country: "Country*",
  city: "City*",
  mobile: "Phone number*",
  mobileCode: "Verification code*",
  email: "Email*",
  wechat: "WeChat*",
  extRemarks: "Remarks",
  btnGetCode: "Get code",
  submitApply: "Submit",
  tipsMobile: "Phone format is incorrect",
  getCodeAgain: "Send again",
  tipsEmail: "Please enter your vaild email",
  tipsCode: "Please enter the correct SMS verification code",
  confirmButton: "Confirm",
  cancelButton: "Cancel"
};
export default {
  data() {
    return {
      showState: 1,
      language: "cn",
      csp: {},
      currentDate: new Date(),
      minDate: new Date(),
      show: false,
      form: {
        countryId: "",
        mobileCountryId: "317",
        cityId: "",
        mobilePrefix: "+86",
        verfyCode: "",
        liveTime: "",
        firstName: "",
        lastName: "",
        email: "",
        wechatId: ""
      },
      country: "",
      city: "",
      countryArr: [],
      showCountry: false,
      countries: {},
      columns: [],
      countryPreFixArr: [],
      isShowAreaCode: false,
      number: 0,
      disabled: true,
      disabledSend: false,
      timer: null
    };
  },
  watch: {
    form: {
      handler: function(val) {
        let n = 0;
        for (const key in val) {
          if (val.hasOwnProperty(key)) {
            const element = val[key];
            if (!element) n++;
          }
        }
        n ? (this.disabled = true) : (this.disabled = false);
      },
      deep: true
    }
  },
  created() {
    let { lang } = this.$route.params;
    this.language = lang;
    if (lang === "en") {
      this.csp = cspEn;
    } else if (lang === "cn") {
      this.csp = cspCn;
    } else if (this.$store.state.langStr === "cn") {
      this.csp = cspCn;
    }

    document.title = this.csp.metaTitle;
    this.countryCity();
    this.countryPrefix();
  },
  mounted() {
    this.$nextTick(() => {
      this.initQimo();
    });
  },
  methods: {
    handleBlur() {
      window.scrollTo(0, 0);
    },
    //客服
    handleQimo() {
      if (window.qimoChatLoaded) {
        window.qimoChatClick();
      }
    },
    loadQimoScript() {
      if (!document.getElementById("QIMO_SCRIPT_ID")) {
        const scriptQimo = document.createElement("script");
        scriptQimo.id = "QIMO_SCRIPT_ID";
        scriptQimo.type = "text/javascript";
        scriptQimo.src =
          "https://webchat.7moor.com/javascripts/7moorInit.js?accessId=0ea72320-f383-11e8-b385-0195b834ee97&autoShow=false&language=ZHCN";
        scriptQimo.onload = () => {
          let loop = () => {
            if (window.qimoChatLoaded) {
              this.handleQimo();
              if (this.timer) {
                window.clearTimeout(this.timer);
                this.timer = null;
              }
              setTimeout(() => {
                this.showState = 2;
              }, 300);
              loop = null;
            } else {
              this.timer = setTimeout(() => {
                loop();
              }, 1000);
            }
          };
          loop();
        };

        document.body.appendChild(scriptQimo);
      }
    },
    initQimo() {
      const { navigator, document } = window;
      const systemInfo = {
        appCodeName: navigator.appCodeName || "",
        appName: navigator.appName || ""
      };
      const loginUserInfo = this.$util.getLoginUserInfo();
      if (loginUserInfo && loginUserInfo.token) {
        window.qimoClientId = {
          userId: loginUserInfo.id,
          nickName: loginUserInfo.userName,
          customField: {
            用户名称: loginUserInfo.userName,
            用户ID: loginUserInfo.id,
            电话: `${loginUserInfo.mobilePrefix || ""}${loginUserInfo.mobile ||
              ""}`,
            邮箱: loginUserInfo.email || "",
            设备类型: "h5",
            设备ID: `${systemInfo.appCodeName} ${systemInfo.appName}`,
            访问来源: document.referrer || "直接访问"
          }
        };
      } else {
        let UNIQUE_TAG_QIMO = window.localStorage.getItem("UNIQUE_TAG_QIMO");
        if (!UNIQUE_TAG_QIMO) {
          UNIQUE_TAG_QIMO = `web_qimo_${new Date().valueOf().toString()}${
            Math.random()
              .toString()
              .split(".")[1]
          }`;
          window.localStorage.setItem("UNIQUE_TAG_QIMO", UNIQUE_TAG_QIMO);
        }
        window.qimoClientId = {
          userId: UNIQUE_TAG_QIMO,
          nickName: "h5端未登录用户",
          customField: {
            用户名称: "h5端未登录用户",
            设备类型: "h5",
            设备ID: `${systemInfo.appCodeName} ${systemInfo.appName}`,
            访问来源: document.referrer || "直接访问"
          }
        };
      }
      this.loadQimoScript();
    },
    validate() {
      if (!this.$util.checkCode(this.form.verfyCode.trim())) {
        this.$Toast(this.csp.tipsCode);
        return;
      }
      if (!this.$util.checkEmail(this.form.email)) {
        this.$Toast(this.csp.tipsEmail);
        return;
      }

      this.submit();
    },
    submit() {
      let params = {};
      params.url = this.$apis.api_order_apply;
      params.data = {};
      Object.assign(params.data, this.form, { language: this.language });
      this.$net.req(params, this).then(
        res => {
          const { code, msg } = res;
          if (parseInt(code) === 0) {
            this.$Dialog
              .alert({
                message: msg
              })
              .then(() => {
                this.form = {
                  countryId: "",
                  mobileCountryId: "317",
                  cityId: "",
                  mobilePrefix: "+86",
                  verfyCode: "",
                  liveTime: "",
                  firstName: "",
                  lastName: "",
                  email: "",
                  wechatId: ""
                };
                (this.country = ""), (this.city = "");
              });
          } else {
            this.$Toast(msg);
          }
        },
        e => {
          this.$Toast(e.msg);
        }
      );
    },
    // 发送验证码
    getVerfyCode() {
      if (this.disabledSend) {
        return;
      }
      this.disabledSend = true;
      if (!this.$util.checkMobile(this.form.mobile)) {
        this.$Toast(this.csp.tipsMobile);
        setTimeout(() => {
          this.disabledSend = false;
        }, 1000);
        return false;
      }
      let params = {};
      params.url = this.$apis.api_user_verification;
      params.data = {};
      params.data = {
        language: this.language,
        mobile: this.form.mobile,
        countryId: this.form.mobileCountryId,
        status: "8"
      };
      this.$net.req(params, this).then(
        res => {
          if (res) {
            const { code } = res;
            if (parseInt(code) === 0) {
              this.time();
            } else {
              this.$Toast(res.msg);
            }
            setTimeout(() => {
              this.disabledSend = false;
            }, 1000);
          }
        },
        e => {
          setTimeout(() => {
            this.disabledSend = false;
          }, 1000);
          this.$Toast(e.msg);
        }
      );
    },
    // 倒计时
    time() {
      let num = 60;
      const name = setInterval(() => {
        num--;
        this.number = num;
        if (num === 0) {
          this.disabledSend = false;
          clearInterval(name);
        }
      }, 1000);
    },
    selectCountry(item) {
      this.isShowAreaCode = false;
      this.form.mobilePrefix = item.code;
      this.form.mobileCountryId = item.id;
    },
    confirmCities(values) {
      this.country = values[0];
      this.city = values[1].name;
      this.countryArr.forEach(element => {
        if (values[0].toString() === element.name.toString()) {
          this.form.countryId = element.id;
        }
        element.son.forEach(val => {
          if (values[1].name.toString() === val.name.toString()) {
            this.form.cityId = val.id;
          }
        });
      });
      this.showCountry = false;
    },
    onChange(picker, values) {
      picker.setColumnValues(1, this.countries[values[0]]);
    },
    countryCity() {
      const that = this;
      let params = {};
      params.url = this.$apis.phpApiHomeCity;
      params.data = {};
      Object.assign(params.data, { language: this.language });
      this.$net.req(params, this).then(
        res => {
          if (res) {
            const { code, data } = res;
            if (parseInt(code) === 0 && data) {
              this.countryArr = data;
              for (const key in data) {
                const objectKey = data[key].name;
                this.countries[objectKey] = data[key].son;
              }
              if (this.language == "cn") {
                that.columns = [
                  {
                    values: Object.keys(that.countries),
                    className: "column1"
                  },
                  {
                    values: that.countries["澳大利亚"],
                    className: "column2",
                    defaultIndex: 2
                  }
                ];
              } else {
                that.columns = [
                  {
                    values: Object.keys(that.countries),
                    className: "column1"
                  },
                  {
                    values: that.countries["Australia"],
                    className: "column2",
                    defaultIndex: 2
                  }
                ];
              }
            }
          }
        },
        e => {
          this.$Toast(e.msg);
        }
      );
    },
    countryPrefix() {
      let params = {};
      params.url = this.$apis.api_national_country_prefix;
      params.data = {};
      Object.assign(params.data, { language: this.language });
      this.$net.req(params, this).then(
        res => {
          if (res) {
            const { code, data } = res;
            if (parseInt(code) === 0 && data) {
              this.countryPreFixArr = data;
            }
          }
        },
        e => {
          this.$Toast(e.msg);
        }
      );
    },
    dataTime() {
      this.show = true;
    },
    confirm(value) {
      this.show = false;
      if (value) {
        this.form.liveTime =
          value.getFullYear() +
          "-" +
          (value.getMonth() + 1) +
          "-" +
          value.getDate();
      }
    }
  }
};
</script>
<style>
.page-csp .van-picker__toolbar {
  height: 50px;
}
.page-csp .van-nav-bar .van-icon {
  color: #000;
  font-size: 20px;
}
</style>

<style lang="less" scoped>
.page-container {
  height: 100vh;
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch;
  &.page-csp {
    .walk-conatiner {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      .walk {
        width: 55px;
      }
    }
    .header {
      position: relative;
      min-height: 150px;
      img {
        width: 100%;
        position: absolute;
        left: 0;
        top: 0;
      }
      .text {
        position: absolute;
        top: 33px;
        left: 30px;
        color: rgba(255, 255, 255, 1);
        h2 {
          font-size: 20px;
          font-family: PingFangSC-Medium;
          font-weight: 500;
          color: rgba(255, 255, 255, 1);
          line-height: 28px;
        }
        p {
          font-size: 12px;
          font-family: PingFangSC-Regular;
          font-weight: 400;
          color: rgba(255, 255, 255, 1);
          line-height: 17px;
          width: 180px;
        }
        .title-line {
          width: 10px;
          height: 2px;
          background: rgba(255, 255, 255, 1);
          margin: 10px 0;
        }
      }
    }

    .online-service-wrap {
      position: fixed;
      right: 20px;
      bottom: 130px;
      z-index: 5;
      width: 52px;
      height: 52px;
      background: #ff523c;
      box-shadow: 0px 2px 4px 0px rgba(70, 70, 70, 0.2);
      border-radius: 44px;
      color: #fff;
      flex-direction: column;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 8px;
      i {
        font-size: 22px;
      }
      p {
        height: 10px;
        font-size: 10px;
        font-family: PingFangSC-Regular;
        line-height: 10px;
      }
    }
    .content {
      padding: 20px 20px 0;
      position: relative;
      top: 20px;
      .button {
        width: 100%;
        height: 45px;
        background: linear-gradient(
          134deg,
          rgba(255, 143, 85, 1) 0%,
          rgba(255, 108, 80, 1) 51%,
          rgba(255, 84, 61, 1) 100%
        );
        box-shadow: 0px 4px 10px 0px rgba(255, 82, 61, 0.2);
        border-radius: 23px;
        font-size: 18px;
        font-family: PingFangSC-Medium;
        font-weight: 500;
        color: rgba(255, 255, 255, 1);
        text-align: center;
        line-height: 45px;
        margin: 30px 0 50px;
      }
      .disabled {
        background: #ffbfab;
        pointer-events: none;
      }
      .verfyCode {
        font-family: PingFangSC-Regular;
        font-weight: 400;
        span {
          color: rgba(255, 82, 61, 1);
        }
        .getCode {
          color: #ddd;
        }
        input {
          width: 61% !important;
        }
      }
      .loading-box {
        height: 100px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .textarea {
        border-radius: 4px;
        width: 100%;
        background: rgba(249, 249, 249, 1);
        border: 0;
        padding: 18px 10px;
        min-height: 120px;
        resize: none;
        &::placeholder {
          color: rgba(204, 204, 204, 1);
        }
      }
      .input-box {
        width: 100%;
        height: 60px;
        background: rgba(249, 249, 249, 1);
        border-radius: 4px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 18px 10px;
        margin-bottom: 10px;
        box-sizing: border-box;
        .placeholder {
          font-family: PingFangSC-Regular;
          font-weight: 400;
          color: rgba(204, 204, 204, 1);
        }
        input {
          display: block;
          background: rgba(249, 249, 249, 1);
          outline: none;
          border: 0;
          width: 100%;
          &::placeholder {
            color: rgba(204, 204, 204, 1);
          }
        }
        .prefix {
          width: 42px;
          height: 25px;
          background: rgba(238, 238, 238, 1);
          border-radius: 4px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-right: 10px;
          padding: 4px;
          box-sizing: border-box;
          span {
            font-size: 12px;
            font-family: PingFangSC-Medium;
            font-weight: 500;
            color: rgba(68, 68, 68, 1);
            line-height: 18px;
          }
          .icon-xiala1 {
            font-size: 10px;
            color: #444444;
            transform: scale(0.4);
            display: inline-block;
            margin-right: 4px;
          }
        }
      }
      .both-input {
        display: flex;
        justify-content: space-between;
        .left,
        .right {
          width: 37%;
          .icon-xiala1 {
            font-size: 10px;
            color: #444444;
            transform: scale(0.8);
          }
        }
        .right {
          width: 60%;
        }
      }
    }
  }
  .guide-wrap {
    height: 100vh;
    overflow: hidden;
    .city {
      height: calc(100vh - 44px);
      overflow-y: auto;
      background: #fff;
      width: 100%;
      flex-shrink: 0;
      span {
        font-weight: 400;
        display: flex;
        align-items: center;
        font-size: 18px;
        padding: 0 0 0 20px;
        height: 38px;
        color: #222;
        background: rgba(238, 238, 238, 1);
      }
      .line {
        height: 45px;
        font-size: 14px;
        color: #999;
        font-weight: 400;
        padding: 0 20px;
        div {
          display: flex;
          align-items: center;
          height: 100%;
          position: relative;
          p:first-child {
            width: 240px;
          }
        }
        div:after {
          content: "";
          position: absolute;
          bottom: 0;
          left: 20px;
          right: 20px;
          height: 1px;
          background: #ddd;
        }
        div:last-child:after {
          height: 0;
        }
      }
    }
    #cityLine {
      position: fixed;
      right: 0;
      top: 20%;
      display: flex;
      width: 22px;
      flex-direction: column;
      z-index: 2;
      a {
        width: 100%;
        text-align: center;
        height: 13px;
        font-size: 11px;
        font-weight: 500;
        color: #222;
        line-height: 13px;
        margin: 0 0 3px;
      }
    }
  }
}
</style>
