<template>
  <div>
    <buy v-if="orderState <= 2" :state="orderState" />
    <success v-if="orderState === 3 && isLogin && !showQuestion" />
    <exclusive
      v-if="(orderState === 4 || orderState === 5) && isLogin"
      :has-suggestion="orderState === 5"
    />
    <question v-if="showQuestion && isLogin" />
    <tabbar />
  </div>
</template>

<script>
import Tabbar from "@/components/Tabbar";
import Buy from "./Buy";
import Success from "./Success";
import Question from "./Question";
import Exclusive from "./Exclusive";
import { mapState, mapActions } from "vuex";
import localStorage from "@/service/localStorage";
import { getCulOrder, getPayState } from "@/api/consultant";
export default {
  name: "Consultant",
  components: {
    Tabbar,
    Buy,
    Success,
    Exclusive,
    Question
  },
  data() {
    return {
      isLogin: localStorage.get("mongoToken"),
      showQuestion: false,
      orderInfo: [
        {
          consultantOrderNo: "",
          state: -1
        }
      ]
    };
  },
  computed: {
    orderState() {
      this.changePageTitle();
      return this.orderInfo[0] ? this.orderInfo[0].state : -1;
    },
    ...mapState(["isShowLogin"])
  },
  watch: {
    isShowLogin(val) {
      if (!val) {
        this.isLogin = localStorage.get("mongoToken");
        this.getOrderInfo();
      }
    }
  },
  mounted() {
    this.getOrderInfo();
  },
  methods: {
    ...mapActions(["setIsPayWait"]),
    // 1-待支付,3-支付成功,4-问卷收集完成，方案配置中,5-方案配置完成,  -1 -支付失败订单关闭,-2 -支付超过1小时订单关闭,-3 -订单关闭
    async getOrderInfo(checkPayState = false) {
      if (!this.isLogin) return;
      this.showQuestion = false;
      const res = await getCulOrder();
      if (res) {
        this.orderInfo = res;
        if (checkPayState && res.state < 3) {
          this.getPayState();
        } else {
          this.setIsPayWait(false);
        }
        this.$forceUpdate();
      }
    },
    async getPayState() {
      const res = await getPayState();
      if (res.state === 2) {
        setTimeout(() => {
          this.getPayState();
        }, 3000);
      } else {
        this.setIsPayWait(false);
        this.getOrderInfo();
      }
    },
    changeQuestion() {
      this.showQuestion = true;
    },
    changePageTitle() {
      const state = "" + (this.orderInfo[0] ? this.orderInfo[0].state : -1);
      let pageTitle = "";
      switch (state) {
        case "-1":
        case "2":
        case "1-1":
        case "1-2":
        case "1-3":
          pageTitle = "1对1保险顾问";
          break;
        case "3":
          pageTitle = "调查问卷";
          break;
        case "4":
        case "5":
          pageTitle = "保险顾问";
          break;
        default:
          pageTitle = "1对1保险顾问";
          break;
      }
      document.title = pageTitle;
    }
  }
};
</script>
