import "./index.scss";
import UserApi from "@/apis/userApi";
import Button from "@/component/button";
import Flex from "@/component/flex";
import Label from "@/component/label";
import Layout from "@/component/layout";
import Padding, { EdgeInsets } from "@/component/padding";
import SizeBox from "@/component/sizeBox";
import APPConfig from "@/config";
import AppContext from "@/context/appContext";
import UserHelper from "@/helper/userHelper";
import ImageUtil from "@/utils/imgUtils";
import RouteUtil from "@/utils/routeUtil";
import {
  Image,
  ScrollView,
  View,
  Text,
  OfficialAccount,
} from "@tarojs/components";
import {
  parseQueryParams,
  isOuterLink,
  replaceQueryParam,
} from "@/utils/toolsUtil";
import StorageUtil, { EStorage } from "@/utils/storageUtil";
import { pxTransform } from "@tarojs/taro";
import { useRequest } from "ahooks";
import React, { useContext, useMemo, useState, useRef } from "react";
import LoginBox from "../user/components/LoginBox";
import BottomBarContext from "@/context/bottomBarContext";

import Taro from "@tarojs/taro";

const Home = () => {
  const channelCode: any = StorageUtil.get(EStorage.channelCode) || "";

  const bottomBarContext = useContext(BottomBarContext);

  const childRef: any = useRef();
  const handleOpen = () => {
    childRef.current.handleOpen();
  };
  const appContext = useContext(AppContext);
  const { screenWidth, statusBarHeight } = appContext.systemInfo!;
  const [bottomRemark, setBottomRemark] = useState("");
  const isUserLogin = UserHelper.isLogin();
  const indexInfoResult: any = useRequest(() => {
    return UserApi.getIndexInfoUsingPost({
      params: { appId: APPConfig.APPID },
    }).toData();
  });

  const channelResult: any = useRequest(() => {
    return UserApi.homeFetchChannel({
      data: {
        channelCode: channelCode || APPConfig.CHANNELCODE,
        refer: "",
      },
    })
      .toData()
      .then((res) => {
        setBottomRemark(res.bottom_remark);
        return res;
      });
  });

  const postJumpUrlResult = () => {
    const params: any = parseQueryParams(indexInfoResult.data.link);
    return UserApi.getJumpUrlPost({
      loading: true,
      data: {
        appId: APPConfig.APPID,
        channelCode: params.channelCode,
        productId: params.productId,
      },
    })
      .toData()
      .then((res: any) => {
        console.log("获取跳转链接结果", res);
        RouteUtil.toWebViewPage({ url: res?.adJumpLink });
      });
  };

  const loginFlowHandler = async () => {
    await UserHelper.UpdateOpenId();
    if (isOuterLink(indexInfoResult.data.link)) {
      // 如果是外部链接，不用管
      await postJumpUrlResult();
    } else {
      const jumpUrl = channelCode
        ? replaceQueryParam(
            indexInfoResult.data.link,
            "channelCode",
            channelCode
          )
        : indexInfoResult.data.link;

      RouteUtil.toWebViewPage({
        url: jumpUrl,
      });
    }
  };

  const carLoanFlowHandler = async () => {
    const DEFAULT_CHANNEL_CODE = APPConfig.CHANNELCODE;

    const url =
      "https://m1.h5.hrshuke.cn/carv2/" + (channelCode || DEFAULT_CHANNEL_CODE);
    RouteUtil.toWebViewPage({
      url,
    });
  };

  const houseLoanFlowHandler = async () => {
    const DEFAULT_CHANNEL_CODE = APPConfig.CHANNELCODE;

    const url =
      "https://m1.h5.hrshuke.cn/house/" + (channelCode || DEFAULT_CHANNEL_CODE);
    RouteUtil.toWebViewPage({
      url,
    });
  };

  const toPhone = () => {
    const phone = channelResult.data?.customerServiceInfo || "400-003-9350";

    Taro.makePhoneCall({
      phoneNumber: phone,
    });
  };

  const imgBackStyle = useMemo(() => {
    return {
      ...ImageUtil.calculationHeight(332 / 170, (screenWidth - 64 + 16) / 2),
      position: "relative",
    } as React.CSSProperties;
  }, []);
  // @ts-ignore
  const item = (index: number, title: string, desc: string) => {
    return (
      <View style={imgBackStyle}>
        <Image
          className="background-image"
          src={require(`../../assets/icon_home_characteristic_b_${index}.png`)}
        />
        <Flex
          rowGap="sm"
          className="background-content background-content-wrap"
        >
          <Flex columnGap="sm" direction="row" alignItem="center">
            <Image
              className="background-content-i"
              src={require(`../../assets/icon_home_characteristic_i_${index}.png`)}
            />
            <Label bold>{title}</Label>
          </Flex>
          <Label style={{ fontSize: pxTransform(22) }} type="secondary">
            {desc}
          </Label>
        </Flex>
      </View>
    );
  };

  const BottomRemark = () =>
    bottomRemark
      .split(";")
      .map((text) => <View style={{ margin: "4px 0" }}>{text}</View>);
  const ApplyButton = ({ isLogin }) => {
    return (
      <>
        {isLogin ? (
          <Button
            className="index-back-btn"
            onClick={() => {
              UserHelper.afterLogin({
                pop: false,
                callback: async () => {
                  indexInfoResult.data && loginFlowHandler();
                  // indexInfoResult.data && postJumpUrlResult()
                  // RouteUtil.toWebViewPage({
                  //   url: indexInfoResult.data.link,
                  // });
                },
              });
            }}
          >
            立即申请额度
          </Button>
        ) : (
          <Button onClick={handleOpen} fill className="index-back-btn">
            立即申请
          </Button>
        )}
      </>
    );
  };
  return (
    <Layout safe className="index" bottomBarIndex={0}>
      <ScrollView className="index-container">
        <SizeBox height={statusBarHeight} />
        {/* <Image
          className="index-logo"
          src={require("../../assets/home_logo_hrqb.png")}
        /> */}
        <Image
          className={APPConfig.APPID == "480" ? "index-logo-cyr" : "index-logo"}
          src={APPConfig.HOME_LOGO}
        />

        <SizeBox height={20} />

        <Padding padding={EdgeInsets.symmetric({ horizontal: 32 })}>
          <View
            style={{
              ...ImageUtil.calculationHeight(
                686 / 484,
                appContext.systemInfo!.screenWidth - 32
              ),
              position: "relative",
            }}
            className="index-panel"
          >
            <Flex
              alignItem="center"
              justifyContent="center"
              // rowGap={24}
              className="index-back-content"
            >
              <Label className="index-back-se">最高可申请（元）</Label>
              <Label className="index-back-amount">200,000.00</Label>
              <View className="index-back-tip">具体额度以资金方审批为准</View>
              <Flex
                alignItem="center"
                justifyContent="center"
                direction="row"
                className="index-back-info"
                columnGap={12}
              >
                <Text>年化利率7.2-24%(单利)</Text>
                <View className="split-char"></View>
                <Text>期限3-36个月</Text>
              </Flex>
              <View className="index-back-btn-container">
                <View className="index-back-btn-tip">
                  现在申请，快速评估需求
                </View>
                <ApplyButton isLogin={isUserLogin}></ApplyButton>
                {/* <Button
                  onClick={() => {
                    UserHelper.afterLogin({
                      pop: false,
                      callback: async () => {
                        indexInfoResult.data &&
                          RouteUtil.toWebViewPage({
                            url: indexInfoResult.data.link,
                          });
                      },
                    });
                  }}
                  className='index-back-btn'
                >
                  立即申请额度
                </Button> */}
              </View>
            </Flex>
          </View>
          <View className="index-step-container">
            <View className="background"></View>
            <Flex
              alignItem="center"
              justifyContent="center"
              direction="row"
              columnGap={8}
            >
              <Text>01.提交申请</Text>
              <Image
                style={{ width: "24px", height: "24px" }}
                src={require("../../assets/new-edition/icon-next.svg")}
              />
              <Text>02.需求评估</Text>
              <Image
                style={{ width: "24px", height: "24px" }}
                src={require("../../assets/new-edition/icon-next.svg")}
              />
              <Text>03.签约办理</Text>
            </Flex>
          </View>
        </Padding>

        <SizeBox height={24} />
        {/* <Padding padding={EdgeInsets.symmetric({ vertical: 68 })}>
          <Flex alignItem="center" justifyContent="center">
            <Image
              src={require("@/assets/icon_home_characteristic.png")}
              className="index-iocn-title"
            />
          </Flex>
        </Padding> */}

        {/* <Flex rowGap="sm" style={{ padding: "0 16PX" }}>
          <Flex direction="row">
            {item(0, "产品丰富", "信用、抵押、质押均可")}
            <SizeBox width={16} />
            {item(1, "快速便捷", "最快10分钟出结果")}
          </Flex>
          <Flex direction="row">
            {item(2, "场景多元", "可用于消费、经营等")}
            <SizeBox width={16} />
            {item(3, "信息保密", "严格保护申请人信息")}
          </Flex>
        </Flex> */}

        {/* <Padding padding={EdgeInsets.symmetric({ horizontal: 32 })}>
          <View className="index-car-loan-entrance">
            <View className="index-car-loan-entrance-header">
              <View className="index-car-loan-entrance-title">车抵贷</View>
              <Image
                src={require("../../assets/v1.5.0/badge-car.svg")}
                className="icon-car-badge"
              />
            </View>
            <View className="index-car-loan-entrance-body">
              <View className="index-car-loan-entrance-body-p1">
                <Image
                  className="icon-car-product"
                  src={require("../../assets/v1.5.0/icon-car-product.svg")}
                />
                <Text className="index-car-loan-entance-body-p1-product-name">
                  车主贷
                </Text>

                <View className="product-tag-wrapper">
                  <View className="product-tag">不押车</View>
                  <View className="product-tag">大额度</View>
                  <View className="product-tag">流程快</View>
                </View>
              </View>
              <View className="index-car-loan-entrance-body-p2">
                <View className="loan-information-item">
                  <Text className="money-text">
                    3~100<Text className="unit">万</Text>
                  </Text>
                  <Text className="sub">额度范围（元）</Text>
                </View>
                <View className="loan-information-item">
                  <Text className="rate-text">7.20%</Text>
                  <Text className="sub">参考年化利率</Text>
                </View>
                <Image
                  src={require("../../assets/v1.5.0/car-loan-apply-button.svg")}
                  className="index-car-loan-apply-button"
                  onClick={carLoanFlowHandler}
                />
              </View>
            </View>
          </View>
        </Padding> */}

        {/* <Padding padding={EdgeInsets.symmetric({ horizontal: 32 })}>
          <View className="index-car-loan-entrance">
            <View className="index-car-loan-entrance-header">
              <View className="index-car-loan-entrance-title">房抵贷</View>
              <Image
                src={require("../../assets/v1.5.0/icon-house-product.svg")}
                className="icon-car-badge"
              />
            </View>
            <View className="index-car-loan-entrance-body">
              <View className="index-car-loan-entrance-body-p1">
                <Image
                  className="icon-car-product"
                  src={require("../../assets/v1.5.0/badge-house.svg")}
                />
                <Text className="index-car-loan-entance-body-p1-product-name">
                  房主贷
                </Text>

                <View className="product-tag-wrapper">
                  <View className="product-tag">额度高</View>
                  <View className="product-tag">流程快</View>
                </View>
              </View>
              <View className="index-car-loan-entrance-body-p2">
                <View className="loan-information-item">
                  <Text className="money-text">
                    5~1000<Text className="unit">万</Text>
                  </Text>
                  <Text className="sub">额度范围（元）</Text>
                </View>
                <View className="loan-information-item">
                  <Text className="rate-text">7.20%</Text>
                  <Text className="sub">参考年化利率</Text>
                </View>
                <Image
                  src={require("../../assets/v1.5.0/car-loan-apply-button.svg")}
                  className="index-car-loan-apply-button"
                  onClick={houseLoanFlowHandler}
                />
              </View>
            </View>
          </View>
        </Padding> */}

        <Padding padding={EdgeInsets.symmetric({ horizontal: 32 })}>
          <Image
            src={require("../../assets/new-edition/platform.png")}
            className="index-platform-image"
          />
        </Padding>

        <Flex
          justifyContent="center"
          alignItem="center"
          rowGap={24}
          className="customer-service-conenter"
        >
          <View className="customer-service-box" onClick={toPhone}>
            <Image className="img" src={require(`../../assets/customer.svg`)} />
            <Text className="span">
              客服：{channelResult.data?.customerServiceInfo || "400-003-9350"}
            </Text>
          </View>
        </Flex>

        <Flex
          justifyContent="center"
          alignItem="center"
          rowGap={24}
          className="index-bottom-tip"
        >
          <View>
            <BottomRemark />
            {/* { bottomRemark } */}
            {/* 郑重声明：平台只提供贷款咨询和推荐服务，放款由银行或金融机构进行，贷款额度、放款时间以资金分审批结果为准，所有贷款申请在未成功贷款前绝不收取任何费用，为了保证您的资金安全，请不要相信任何要求您支付费用的信息、邮件、电话等不实信息。 */}
          </View>
        </Flex>
      </ScrollView>

      {/* <View className="index-official-account">
        <View className="index-official-box ">
          {bottomBarContext?.index === 0 && <OfficialAccount />}
        </View>
      </View> */}

      <LoginBox ref={childRef}></LoginBox>
    </Layout>
  );
};

export default Home;
