import Taro, { Component } from "@tarojs/taro";
import * as actions from "@/actions/user";
import getUserPhone from "@/utils/getUserPhone";
import { getHFiveDetail } from "@/services/user";
import ready from "@/utils/ready";
// import { reportClient } from "@/services/report";
import { connect } from "@tarojs/redux";
import { ROLE_CODE } from "@/constants/user";
import { getQrCodeParams } from "@/utils/qrcode";
import { getMiniQrcode, savePoint, updatePoint } from "@/services/common";
import { isEmpty, parseURL, mergeQueryParams } from "@/utils/tools";
import { rule as ruleToast } from "@/utils/ruleToast";
import { share as shareSavePoint } from "@/utils/shareSavePoint";
import { report as reportCustomer } from "@/utils/customer";

import "./index.scss";

const bgImg =
  "https://njcj.oss-cn-shanghai.aliyuncs.com/miniapp/images/helpgroup/bg.png";

@connect(
  state => state.user,
  { ...actions }
)
export default class Index extends Component {
  state = {
    recordId: undefined, // 埋点ID
    avatarVisible: false,
    phoneVisible: false,
    webViewVisible: false,
    // pageHide: true,
    pageInfo: {},
    codeParams: {}, // 解析二维码参数
    h5Id: undefined,
    reportedCustomer: false,
    buildingId: undefined,
    queryInfo: {},
    webParams: null,
  };

  componentWillMount() {
    ready.queue(() => {
      // h5页面交互参数
      if (this.$router.params.webParams) {
        this.setState({ webParams: decodeURIComponent(this.$router.params.webParams) })
      }

      Taro.showLoading();
      if (this.$router.params.scene) {
        getQrCodeParams(this.$router.params.scene).then(res => {
          console.log(res, "解析二维码返回值");
          this.setState(
            {
              codeParams: res || {},
              h5Id: res.id,
              buildingId: res.buildingId || "",
              queryInfo: {
                channelId: res.channelId || '',
                qrCodeId: res.qrCodeId || '',
                scene: this.$router.params.scene,
              }
            },
            () => {
              if (isEmpty(res.id)) {
                Taro.showModal({
                  title: "提示",
                  content: "活动不存在",
                  success: res => {
                    if (res.confirm) {
                      this.gotoIndex();
                    }
                  }
                });
                return;
              }

              if (!isEmpty(this.state.h5Id)) {
                this.loadH5Profile(res.id);
              }
              this.avatarPhone();
            }
          );
        });
      } else {
        const hFiveId = this.$router.params.id;
        // 没有 H5ID, 也没有分享
        if (isEmpty(hFiveId)) {
          Taro.showModal({
            title: "提示",
            content: "活动不存在",
            success: res => {
              if (res.confirm) {
                this.gotoIndex();
              }
            }
          });
          return;
        }

        if (!isEmpty(hFiveId)) {
          this.loadH5Profile(hFiveId);
        }

        this.avatarPhone();
      }
    });
  }

  avatarPhone() {
    const {
      userInfo: {
        person: { avatarurl, phone }
      }
    } = this.props;

    if (avatarurl && avatarurl.indexOf("wx.qlogo.cn") != -1) {
      console.log(avatarurl, "有头像哦~");
      this.setState({
        avatarVisible: false
      });
      Taro.hideLoading();
      console.log(phone, "phone#########");
      // 头像手机号都有
      if (phone) {
        // this.reportClientFn();
        this.success();
        this.setState({
          phoneVisible: false,
          webViewVisible: true
        });
      } else {
        this.setState({
          phoneVisible: true
        });
      }
    } else {
      Taro.hideLoading();
      this.setState({
        avatarVisible: true
      });
      if (phone) {
        this.setState({
          phoneVisible: false
        });
      }
    }
  }

  componentWillUnmount() {
    const { recordId } = this.state;
    recordId && updatePoint(recordId);
  }

  // 埋点
  success() {
    const { codeParams, buildingId } = this.state;
    const {
      userInfo: {
        person: { personId, personType, userId }
      }
    } = this.props;
    const firstShare = this.$router.params.firstShare || codeParams.firstShare || "";
    const consultant1 = this.$router.params.consultantId || codeParams.consultant || Taro.getStorageSync('consultantId') || ''
    const consultantId1 = this.$router.params.consultantId || codeParams.consultantId || ''
    const consultant = personType == ROLE_CODE["CONSULTANT"] ? personId : consultant1;
    const consultantId = personType == ROLE_CODE["CONSULTANT"] ? userId : consultantId1;


    const sharePersonId =
      this.$router.params.sharePersonId || codeParams.sharePersonId || "";
    const h5Id = this.state.h5Id || this.$router.params.id;
    const { queryInfo } = this.state

    savePoint({
      event: "detail",
      eventType: "h5",
      propertyName: "h5详情",
      buildingId: buildingId || "",
      consultant: consultant,
      consultantId: consultantId,
      sharePersonId: sharePersonId,
      targetId: h5Id,
      data: '{"firstShare":"' + firstShare + '"}',
      ...queryInfo
    }).then(res => {
      this.setState({
        recordId: res.recordId
      });
      console.log("访问记录");
    });
  }

  h5ExtendParams = null;

  // H5 分享交互
  handleMessage = e => {
    const { data } = e.detail;
    const { params } =
      (data || []).reverse().filter(x => x.type === "share")[0] || {};

    console.log("----share message----->", params);
    if (params) {
      this.h5ExtendParams = params;
    }
  };

  // 分享好友
  onShareAppMessage = () => {
    const { pageInfo, h5Id, buildingId, codeParams } = this.state;
    const [currentPage, currentParams] = this.currentPageAndParams();
    const sharePath = `/${currentPage}?${mergeQueryParams(
      currentParams,
      `webParams=${encodeURIComponent(this.h5ExtendParams)}`
    )}`;
    const {
      userInfo: {
        person: { personId, personType, userId }
      }
    } = this.props;
    const consultantId1 = this.$router.params.consultantId || codeParams.consultantId || ''
    const consultantId = personType == ROLE_CODE["CONSULTANT"] ? userId : consultantId1;

    // 用后即焚
    this.h5ExtendParams = null;

    console.log("----sharePath----->", sharePath);

    shareSavePoint(
      {
        event: "share",
        eventType: "activity",
        targetType: "h5",
        propertyName: "h5详情分享",
        consultantId: consultantId,
        sharePersonId: personId,
        targetId: h5Id,
        buildingId: buildingId || "",
        data: "{}"
      },
      "h5"
    );

    return {
      title: pageInfo.shareTitle,
      path: sharePath,
      imageUrl: pageInfo.shareImg
    };
  };

  currentPageAndParams() {
    const { userInfo: { person } } = this.props;
    const { h5Id, buildingId, codeParams } = this.state;
    const consultant1 = this.$router.params.consultant || codeParams.consultant || Taro.getStorageSync('consultantId') || ''
    const consultantId1 = this.$router.params.consultantId || codeParams.consultantId || ''
    const consultant = person.personType == ROLE_CODE["CONSULTANT"] ? person.personId : consultant1
    const consultantId = person.personType == ROLE_CODE["CONSULTANT"] ? person.userId : consultantId1

    const firstShare = this.$router.params.firstShare || person.personId;

    let queryParams = [
      `sharePersonId=${person.personId}`,
      `recommender=${person.personId}`,
      `consultant=${consultant}`,
      `from=h5_share`,
      `consultantId=${consultantId}`,
      `firstShare=${firstShare}`,
      `id=${h5Id}`,
      `buildingId=${buildingId}`
    ];

    const res = ["pages/project/h5Page", queryParams.join("&")];
    console.log("path--------------------------->", res)
    return res;
  }

  gotoIndex = () => {
    Taro.switchTab({
      url: "/pages/project/index"
    });
  };

  loadH5Profile = id => {
    // h5id 、第一个分享人ID、置业顾问ID、分享人ID
    const { queryInfo, codeParams } = this.state
    const consultant = this.$router.params.consultant || codeParams.consultant || Taro.getStorageSync('consultantId') || ''
    const recommender = this.$router.params.recommender || codeParams.recommender || Taro.getStorageSync('recommender') || ''
    getHFiveDetail(id, queryInfo, { ['x-consultant']: consultant, ['x-recommender']: recommender }).then(res => {
      Taro.hideLoading();
      if (res.status == 1) {
        this.setState({
          pageInfo: res,
          h5Id: id,
          buildingId: res.buildingId || ""
        });
      } else {
        Taro.showModal({
          title: "提示",
          content: "活动已下架",
          showCancel: false
        }).then(() => {
          this.gotoIndex();
        });
      }
    });
  };

  // 授权头像成功
  onAvatarSuccess() {
    this.setState({
      avatarVisible: false
    });
    const {
      userInfo: {
        person: { phone }
      }
    } = this.props;
    if (phone) {
      this.setState({
        phoneVisible: false,
        webViewVisible: true
      });
      this.success();
    } else {
      this.setState({
        phoneVisible: true
      });
    }
    console.log("授权头像成功！");
  }

  // 授权用户信息
  getUserInfo() {
    const { dispatchUpdateUserInfo } = this.props;
    const sessionKey = Taro.getStorageSync("sessionKey");

    Taro.showLoading();

    Taro.getUserInfo({
      lang: "zh_CN",
      success: res => {
        const payload = Object.assign(res, { sessionKey });
        console.log(res, "获取用户信息返回值");
        // 用户信息保存至服务器
        dispatchUpdateUserInfo(payload).then(res => {
          this.onAvatarSuccess();
          console.log("获取用户信息成功");
          Taro.hideLoading();
        });
      },
      fail: err => {
        Taro.hideLoading();
        console.error(err);
        this.setState({
          avatarVisible: true
        });
        Taro.showToast({
          title: "获取用户信息失败",
          icon: "none"
        });
        return;
      }
    });
  }
  userInfoClick() {
    console.log("userInfoClick");
    this.setState({
      avatarVisible: false
    });
  }
  // 授权手机号
  getPhoneNumber(e) {
    const { buildingId, pageInfo, queryInfo } = this.state;
    const loadOptions = wx.getLaunchOptionsSync();
    const achieveParams = {
      buildingId: buildingId || "",
      targetName: pageInfo.name || "",
      targetType: "h5",
      targetId: pageInfo.drainageId || "",
      promoter: Taro.getStorageSync("recommender"),
      sceneId: loadOptions.scene,
      ...queryInfo
    };
    console.log(
      achieveParams,
      "achieveParamsachieveParamsachieveParamsachieveParams"
    );
    getUserPhone(e, achieveParams, phoneNumber => {
      if (!phoneNumber) {
        Taro.showToast({
          title: "获取手机号失败",
          icon: "none"
        });
      } else {
        ruleToast("signup-agent");
        setTimeout(() => {
          this.success();
          // this.reportClientFn();
          this.setState({
            phoneVisible: false,
            webViewVisible: true
          });
        }, 1000);
      }
    });
  }
  // 报备客户
  // reportClientFn() {
  //   const { codeParams } = this.state;
  //   const consultant =
  //     this.$router.params.consultant || codeParams.consultant || "";
  //   const {
  //     userInfo: { person }
  //   } = this.props;

  //   if (!this.state.reportedCustomer) {
  //     reportCustomer(person, consultant).then(() => {
  //       this.setState({ reportedCustomer: true });
  //     });
  //   }
  // }

  renderMaskBanner() {
    const { avatarVisible, phoneVisible, pageInfo, h5Id } = this.state;
    return (
      <View>
        <Image
          src={pageInfo.middleImg || bgImg}
          mode="widthFix"
          className="bg_img"
        ></Image>
        <View className="middle-page">
          {avatarVisible && h5Id && (
            <View className="content">
              <View className="title">授权头像，围观活动</View>
              <View className="touxiang">
                <open-data type="userAvatarUrl"></open-data>
              </View>
              <View className="name">
                <open-data type="userNickName"></open-data>
              </View>
              <Button
                className="btn"
                open-type="getUserInfo"
                lang="zh_CN"
                onClick={this.userInfoClick}
                onGetUserInfo={this.getUserInfo}
              >
                好
              </Button>
            </View>
          )}
          {phoneVisible && h5Id && (
            <Button
              className="phone-btn"
              open-type="getPhoneNumber"
              lang="zh_CN"
              onGetphonenumber={this.getPhoneNumber}
            >
              点击授权查看详情
            </Button>
          )}
        </View>
      </View>
    );
  }
  render() {
    const {
      pageInfo,
      webViewVisible,
      codeParams,
      pageHide,
      h5Id,
      buildingId,
      webParams,
    } = this.state;
    const {
      userInfo: { person }
    } = this.props;

    const consultant1 = this.$router.params.consultantId || codeParams.consultant || Taro.getStorageSync('consultantId') || ''
    const consultantId1 = this.$router.params.consultantId || codeParams.consultantId || ''
    const consultant = person.personType == ROLE_CODE["CONSULTANT"] ? person.personId : consultant1;
    const consultantId = person.personType == ROLE_CODE["CONSULTANT"] ? person.userId : consultantId1;

    const firstShare = this.$router.params.firstShare || person.personId;
    const webUrlParams = [
      `personId=${person.personId}`,
      `recommender=${person.personId}`,
      `h5id=${h5Id}`,
      `buildingId=${buildingId}`,
      `consultant=${consultant}`,
      `consultantId=${consultantId}`,
      `firstShare=${firstShare}`,
      `codeParams=${encodeURIComponent(mergeQueryParams(webParams || '', codeParams["__raw"]))}`
    ].join("&");

    const showH5 =
      !isEmpty(h5Id) &&
      pageInfo.h5Address &&
      pageInfo.h5Address !== "about" &&
      pageInfo.h5Address !== "http://about" &&
      pageInfo.h5Address !== "https://about";

    const originURL = parseURL(pageInfo.h5Address) || {};
    const queryString = [webUrlParams, originURL.query].join("&");
    const webURL = [
      `${originURL.origin}${originURL.path}?${queryString}`,
      originURL.hash
    ].join("#");

    return (
      <Block>
        {this.renderMaskBanner()}
        {webViewVisible && showH5 && (
          <WebView src={webURL} onMessage={this.handleMessage} />
        )}
      </Block>
    );
  }
}
