import _ from "lodash";
import STATUS_MAP from "../constants";
import { parseTime } from "@/service/utils";
import GOODS_LIST from "@/api/goodsList.mock";

export default {
  data() {
    return {
      isFromPay: false
    };
  },
  methods: {
    getData(policy) {
      const key = this.findKey(policy);
      let value = _.cloneDeep(STATUS_MAP[key]);

      // 保单详情key为“15”时特殊处理
      if (key === "15" && this.policy) {
        value = _.cloneDeep(STATUS_MAP["6"]);
      }

      if (["6", "7", "8", "9"].includes(key)) {
        value.title = value.title.replace("${title}", policy?.refundInfo?.amount || "-");
        value.contend = value.contend.replace(
          "${start}",
          parseTime(policy?.refundInfo?.payTime, "{y}-{m}-{d}")
        );
      } else {
        value.title = value.title.replace("${title}", policy?.insuredUserNameMask || "-");
        value.contend = value.contend
          .replace("${start}", parseTime(policy?.policyEffectiveDate, "{y}-{m}-{d}"))
          .replace("${end}", parseTime(policy?.policyEndDate, "{y}-{m}-{d}"))
          .replace("${money}", policy?.payInfo?.amount || "-");

        if (key === "2") {
          value.recordText = value.recordText.replace("${money}", policy?.payInfo?.amount || "-");
        }
      }

      // 长险保障期限特殊处理
      if (
        ["BNZJX001", "HGSX001"].includes(policy.productNo) &&
        value.contend.includes("保障期限") &&
        policy?.productItem?.policyPeriod
      ) {
        const goods = GOODS_LIST.find(v => v.id === policy.productNo);
        const policyPeriod = goods.policyPeriod.find(
          v => v.value === policy.productItem.policyPeriod
        );
        value.contend = `保障期限：${policyPeriod.label}`;
      }

      // 校验是否支付成功
      const status = this.getStatus(policy);
      if (["6.2-3", "6.1-3"].includes(status) && this.isFromPay) {
        this.$router.replace(`/policy/success/${this.$route.params.orderNo}`);
      }

      return {
        ...policy,
        ..._.find(GOODS_LIST, { id: policy?.productNo }),
        cardConfig: { ...value, key, status: this.getStatus(policy) }
      };
    },
    findKey(policy) {
      const status = this.getStatus(policy);
      return _.findKey(STATUS_MAP, v => v.status.includes(status));
    },
    getStatus(policy) {
      return policy?.payState
        ? `${policy?.policyState}-${policy?.payState}`
        : String(policy?.policyState);
    },
    getGoodsInfo(policy) {
      return {
        ...policy,
        ..._.find(GOODS_LIST, { id: policy?.productNo })
      };
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      const prePath = ["/goods/inform", "/goods/detail", "/policy/add"];
      if (prePath.includes(from.path)) {
        vm.isFromPay = true;
      }
    });
  }
};
