<script lang="tsx">
import {
  defineComponent,
  onMounted,
  onUnmounted,
  reactive,
  ref,
  Transition,
} from "vue";
import NavBar from "@/components/NavBar/index.vue";
import LoanCard2 from "@/components/Loan/LoanCard2/index.vue";
import LoanDetailDescribe from "./components/LoanDetailDescribe/index.vue";
import Branch from "@/components/Mine/Branch/branch.vue";
import leftBg from "@/assets/img/left_bg.png";
import crown from "@/assets/img/crown.png";
import { useRoute } from "vue-router";
import { queryLoanProductInfo } from "@/service/LoanProductService/index";
import { eGuaranteeType } from "@/service/LoanProductService/type";
import { filterGuaranteeType } from "@/utils/guarantee-type";
import { Skeleton } from "vant";
import { iNearbyOutLet } from "@/service/AddressService/types";
import AddressService from "@/service/AddressService";
import router from "@/router";
import { goToChatWithOutletRoboot } from "@/router/navigate";
import { chatAuthCheck } from "@/utils/authCheck";
import { eRole } from "@/types/roleType";
import { getUserMsg } from "@/utils/userMsg";

function isInViewPort(element: HTMLElement, barHeight: number) {
  const viewWidth = window.innerWidth || document.documentElement.clientWidth;
  const viewHeight =
    window.innerHeight || document.documentElement.clientHeight;
  const { top, right, bottom, left } = element.getBoundingClientRect();
  return (
    top >= barHeight && left >= 0 && right <= viewWidth && bottom <= viewHeight
  );
}

function showChat() {
  const user = getUserMsg();
  if (!user) return true;
  return user && user?.role2 === eRole.user;
}

export default defineComponent({
  components: {
    NavBar,
    LoanCard2,
    LoanDetailDescribe,
    Branch,
    Transition,
    Skeleton,
  },
  setup() {
    const applyEl = ref();
    const barHeight = ref();
    const canSeeApplyBtn = ref(true);
    const uuid = ref("");
    const min_amount = ref(0);
    const max_amount = ref(0);
    const rate = ref(0);
    // const rate_lower = ref(0);
    // const rate_upper = ref(0);
    const inst_name = ref("");
    const product_name = ref("");
    const date = ref(0);
    const guarantee_type = ref(eGuaranteeType.credit);
    const products = ref("");
    const features = ref("");
    const apply_to = ref("");
    const apply_cond = ref("");
    const submit_cond = ref("");
    const state = reactive({
      outletList: [] as iNearbyOutLet[],
      loading: false,
    });

    const fetchBranch = async () => {
      state.loading = true;
      const ret = await AddressService.getInstance().getNearby({
        bank_code: Number(process.env.VUE_APP_BANK_CODE),
        number: 1,
      });
      if (ret.code === 200) {
        state.outletList = ret.data;
        console.log(state.outletList[0]);
      }
      state.loading = false;
    };

    onMounted(() => {
      uuid.value = useRoute().params.uuid as string;
      queryLoanProductInfo({ uuid: uuid.value }).then((ret) => {
        if (ret.code === 200) {
          console.log(ret);
          const productItem = ret.data;
          min_amount.value = productItem.min_amount;
          max_amount.value = productItem.max_amount;
          rate.value = productItem.rate;
          inst_name.value = productItem.inst_name;
          product_name.value = productItem.product_name;
          date.value = productItem.date;
          guarantee_type.value = productItem.guarantee_type;
          products.value = productItem.products;
          features.value = productItem.features;
          apply_to.value = productItem.apply_to;
          apply_cond.value = productItem.apply_cond;
          submit_cond.value = productItem.submit_cond;
        }
        fetchBranch();
      });

      const barEle = document.querySelector(".theBar");
      barHeight.value = barEle?.clientHeight;
      window.onscroll = () => {
        const canSee = isInViewPort(applyEl.value, barHeight.value);
        canSeeApplyBtn.value = canSee;
      };
    });

    onUnmounted(() => {
      window.onscroll = null;
    });

    const handleClickApply = async () => {
      if (!showChat()) return;
      console.log(11111111);
      chatAuthCheck(getOutletAndNavigateToChat, () => {
        router.push({
          name: "Login",
        });
      });
    };

    const clickChatIcon = async () => {
      chatAuthCheck(getOutletAndNavigateToChat, () => {
        router.push({
          name: "Login",
        });
      });
    };

    const getOutletAndNavigateToChat = async () => {
      const ret = await AddressService.getInstance().getNearby({
        bank_code: Number(process.env.VUE_APP_BANK_CODE),
        number: 1,
      });
      if (ret.code === 200) {
        goToChatWithOutletRoboot({
          outletPosId: ret.data[0].pos_id,
        });
      }
    };

    return () => (
      <div>
        <div class="page flex-col">
          <div class="group1 flex-col">
            <NavBar
              title={"产品详情"}
              iconColor={canSeeApplyBtn.value ? "white" : "black"}
              style={{
                background: canSeeApplyBtn.value
                  ? "#2C3C92 !important"
                  : "white !important",
                color: canSeeApplyBtn.value ? "white" : "black",
              }}
              showSecondIcon={true}
              isRole={showChat()}
              onClickSecondIcon={clickChatIcon}
            />
            <div class="block1 relative">
              <div class="bd1 flex-col">
                <div class="section1 flex-col relative">
                  <span class="word2 w-full break-all mt-16">
                    {product_name.value}
                  </span>
                  <LoanCard2
                    class=" absolute mt-28 right-0 left-0 mx-auto"
                    min_amount={min_amount.value}
                    max_amount={max_amount.value}
                    rate_lower={rate.value}
                    isValid={showChat()}
                    setRef={(el: HTMLElement) => {
                      applyEl.value = el;
                    }}
                  />
                </div>
              </div>
            </div>
            <div class="block7 flex-row">
              <img class="icon4" src={leftBg} />
              <img class="label4" src={crown} />
              <span class="info4">申请流程</span>
              <img class="icon5" src={leftBg} />
            </div>
            <div class="block8 flex-col">
              <div class="layer1 flex-col">
                <div class="layer2 flex-row">
                  <div class="layer3 flex-col flex items-center justify-center">
                    <span class="word5">1</span>
                  </div>
                  <div class="layer4 flex-col"></div>
                  <div class="layer5 flex-col flex items-center justify-center">
                    <span class="word5">2</span>
                  </div>
                  <div class="layer6 flex-col" />
                  <div class="layer7 flex-col flex items-center justify-center">
                    <span class="word5">3</span>
                  </div>
                  <div class="layer8 flex-col" />
                  <div class="layer9 flex-col">
                    <span class="word5">4</span>
                  </div>
                </div>
                <div class="layer10 flex-row">
                  <span class="word6">线上申请</span>
                  <span class="txt1">专人联系</span>
                  <span class="word7">资料准备</span>
                  <span class="info5">审批发放</span>
                </div>
              </div>
            </div>
            <div class="block9 flex-row">
              <img class="icon6" src={leftBg} />
              <img class="label5" src={crown} />
              <span class="word8">产品详情</span>
              <img class="label6" src={leftBg} />
            </div>
            <div class=" bg-white mx-5 rounded-2xl overflow-hidden mt-5">
              <div class="flex justify-between text-sm text-gray-800 border-b border-product-detail-bg">
                <span class=" w-100 align-center bg-product-detail-bg py-4 inline-block text-center">
                  产品机构
                </span>
                <span class=" w-235 py-4 pr-5 inline-block break-words text-right">
                  {inst_name.value}
                </span>
              </div>
              <div class="flex justify-between text-sm text-gray-800 border-b border-product-detail-bg">
                <span class="  w-100 align-center bg-product-detail-bg py-4 inline-block text-center">
                  产品名称
                </span>
                <span class="  w-235 py-4 pr-5 inline-block break-words text-right">
                  {product_name.value}
                </span>
              </div>
              <div class="flex text-sm text-gray-800 border-b border-product-detail-bg justify-between">
                <span class="  w-100 align-center bg-product-detail-bg py-4 inline-block text-center">
                  贷款利率
                </span>
                <span class="  w-235 py-4 pr-5 inline-block break-words text-right">
                  {rate.value}%起
                </span>
              </div>
              <div class="flex text-sm text-gray-800 border-b border-product-detail-bg justify-between">
                <span class="  w-100 align-center bg-product-detail-bg py-4 inline-block text-center">
                  产品额度
                </span>
                <span class="  w-235 py-4 pr-5 inline-block break-words text-right">
                  {min_amount.value}万~{max_amount.value}万
                </span>
              </div>
              <div class="flex text-sm text-gray-800 border-b border-product-detail-bg justify-between">
                <span class="  w-100 align-center bg-product-detail-bg py-4 inline-block text-center">
                  贷款期限
                </span>
                <span class="  w-235 py-4 pr-5 inline-block break-words text-right">
                  {date.value}年
                </span>
              </div>
              <div class="flex text-sm text-gray-800 border-b border-product-detail-bg justify-between">
                <span class="  w-100 align-center bg-product-detail-bg py-4 inline-block text-center">
                  担保方式
                </span>
                <span class="  w-235 py-4 pr-5 inline-block break-words text-right">
                  {filterGuaranteeType(guarantee_type.value)}
                </span>
              </div>
            </div>
            <LoanDetailDescribe
              class=" mt-5"
              products={products.value}
              features={features.value}
              apply_to={apply_to.value}
              apply_cond={apply_cond.value}
              submit_cond={submit_cond.value}
            />
            <div class="title mx-5 mt-5">营业网点</div>
            {state.loading && <div class="mt-2"></div>}
            <Skeleton loading={state.loading} row={4}>
              {state.outletList[0] && (
                <branch
                  class="my-3 mx-5"
                  name={state.outletList[0].name}
                  distance={state.outletList[0].distance}
                  is_normal_work={state.outletList[0].is_normal_work}
                  latitude={state.outletList[0].latitude}
                  location={state.outletList[0].location}
                  longitude={state.outletList[0].longitude}
                  opening_hours={state.outletList[0].opening_hours}
                  weekend_status={state.outletList[0].weekend_status}
                  outlet_id={state.outletList[0].outlet_id}
                  outlet_posId={state.outletList[0].pos_id}
                />
              )}
            </Skeleton>
          </div>
          <div class="h-12"></div>
          <transition name="fade" mode="out-in">
            {!canSeeApplyBtn.value && (
              <div
                class=" fixed left-0 right-0 bottom-0 h-12 bg-app-blue apply-btn flex items-center justify-center"
                style={{
                  zIndex: 300,
                  background: showChat() ? "#3E4FAF" : "gray",
                }}
                onClick={handleClickApply}
              >
                立即申请
              </div>
            )}
          </transition>
        </div>
      </div>
    );
  },
});
</script>

<style lang="less" scoped>
@import "./index.less";
.title {
  font-size: 16px;
  font-family: PingFangHK-Medium, PingFangHK;
  font-weight: 500;
  color: #1b1f37;
  line-height: 22px;
}
.apply-btn {
  font-size: 14px;
  font-family: PingFangSC-Semibold, PingFang SC;
  font-weight: 600;
  color: #ffffff;
}

.w-100 {
  width: 100px;
}
.w-235 {
  width: 235px;
}
</style>
