"use strict";

import React from "react";
import { observer } from "mobx-react";
import "./prizepage.less";
import { callApi } from "@spark/api-base";
import { stopSound } from "@spark/utils";
import { Toast } from "@spark/ui";
import modalStore from "../../store/modal";
// import shareStore from "../../store/share";
import { isWeChat } from "../../utils/share";
import { LOG_KEY, pageView, sensorLog } from "../../utils/sensors";
import { PAGE_MAP, extranceName } from "../../utils/constants";
import { Button } from "../../components/Button";
import API from "../../api";
import store from "../../store";
import { _throttle, dateFormatter, getUrlParam, isMiniprogram } from "../../utils/utils";
import shareStore from "@src/store/share";

@observer
class Prizepage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      records: [],
      tabActive: 0,
      prizeInfo: {},
      projectTabList: [],
    };
    this.projectId = null;
  }

  async componentDidMount() {
    // modalStore.pushPop("Yinsirulepop")
    // modalStore.pushPop("FillAddress")
    await this.getPrize();

    pageView("b12124", { page_name: "我的奖品页" });

    sensorLog(LOG_KEY.exposure, "b12124", "d12126", { page_name: "我的奖品页", button_name: "返回" })
  }

  fetchData = async () => {
    const ps = [];
    ps.push(callApi("/crecord/getrecordmn", { page: 1 }, undefined, undefined, false));
    const [oldRecordsResp] = await Promise.all(ps);
    let records = [];
    if (oldRecordsResp) {
      for (let item of oldRecordsResp.records) {
        if (item.itemType.indexOf("sp_") == -1) {
          const { title, url, img } = item;
          records.push({
            url,
            name: title,
            icon: img,
            data: item,
          });
        }
      }
    }
    this.setState({ records });
  };

  getPrize = async (projectId) => {
    let params = {};
    console.log("!!!!", store.homeInfo?.prod)
    if (projectId) {
      params = {
        projectId: projectId,
        page: 1,
        prod: true//store.homeInfo?.prod !== null ? (store.homeInfo?.prod || false) : true
      };
    } else {
      params = {
        page: 1,
        prod: true//store.homeInfo?.prod !== null ? (store.homeInfo?.prod || false) : true,
      };
    }
    const res = await API.prize(params);
    if (res?.success) {
      let tabList = [];
      let PrizeList = [];
      if (res?.projectTabList?.length > 0) {
        tabList = [{ projectName: "全部" }, ...res?.projectTabList];
      } else {
        tabList = [{ projectName: "全部" }];
      }
      if (res?.records?.length > 0) {
        res.records.map((item) => {
          if (item.itemType.indexOf("sp_") == -1) {
            PrizeList.push(item);
          } else {
            if (item.itemType.startsWith("sp_bean")) {
              PrizeList.push(item);
            }
          }
        });
      }

      this.setState({
        prizeInfo: res,
        records: PrizeList,
        projectTabList: tabList,
      });

      PrizeList.forEach((item) => {
        if (!item?.invalid) {
          sensorLog(LOG_KEY.exposure, "b12124", "d12125", {
            button_name: "去领取",
            page_name: "我的奖品页",
            entrance: extranceName[CFG.channel],
            operation_name: "去领取",
          });
        }
      });
    }
  };

  /** 奖品跳转 app渠道可正常跳转领奖；微信公众号用户中奖后在我的奖品页点击【进入详情】按钮需换端app领奖 */
  // sp_bean 保豆跳转特殊处理
  goPrizeDetail = _throttle(async (item) => {
    if (item?.invalid) {
      Toast("奖品已过期");
      return;
    }

    sensorLog(LOG_KEY.click, "b12124", "d12125", {
      button_name: "去领取",
      page_name: "我的奖品页",
      operation_name: "去领取",
    });

    // stopSound('bg_music')
    const { recordId, url, itemType, recordInfo, projectId, drawStatus } = item;
    const { projectTabList } = this.state;

    if (isMiniprogram()) {
      //小程序渠道toast
      Toast("请前往人保寿险管家app领奖~");
      return;
    } else if (isWeChat()) {
      // 微信渠道唤端
      shareStore.goAppPrize();
    } else {
      // app直接跳
      if (itemType?.startsWith("sp_bean")) {
        // 保豆app端跳转
        console.info("保豆");
        const thirdBrowseParams = {
          url: "picclifeapp://MyPolicyBeansActivity",
          // is_back: "true",
          // functionType: "1",
        };
        setTimeout(async () => {
          window.PICCLifeJsBrage.callNative({
            module: "Router",
            method: "",
            params: JSON.stringify(thirdBrowseParams),
            callback: "jscallback",
          });
        }, 300);
      } else {
        console.info("其他奖品");
        const { tabActive, projectTabList } = this.state;
        //是否走人保定制流程（走流程+绑定业务员+未填写地址+未领取）
        let codeUrl = "";
        let rbClaim = "";
        let saveAddresUrl = "";
        for (let i = 0; i < projectTabList?.length; i++) {
          if (projectTabList[i]?.projectId == projectId) {
            codeUrl = projectTabList[i]?.queryBindAgentCodeUrl;
            rbClaim = projectTabList[i]?.rbClaim;
            saveAddresUrl = projectTabList[i]?.saveAddressUrl;
            console.info(codeUrl, rbClaim, saveAddresUrl);
          }
        }
        if (rbClaim && itemType.indexOf("object") != -1 && drawStatus == "2") {
          let res = await callApi(`${codeUrl}`);
          if (!recordInfo && !!res?.boundYkCode) {
            //未填写地址切绑定业务员
            modalStore.pushPop("FillAddress", {
              projectId: this.projectId,
              saveAddresUrl: saveAddresUrl,
              getPrize: this.getPrize,
              recordId,
              agentCode: res?.boundYkCode,
              prizeProjectId: projectId,
            });
          } else {
            //已填写地址或未绑定业务员
            if (recordInfo?.status == "0") {
              Toast("已领取，请耐心等待发货～");
            } else {
              location.href = `/aaw/projectx/takePrize?projectOrderNo=${recordId}`;
            }
          }
        } else {
          setTimeout(() => {
            if (url) {
              location.href = url;
            } else {
              location.href = `/aaw/projectx/takePrize?projectOrderNo=${recordId}`;
            }
          }, 300);
        }
      }
    }
  });

  switchTab = _throttle(async (val, key) => {
    if (val?.projectId) {
      await this.getPrize(val?.projectId);
      this.projectId = val?.projectId;
    } else {
      // 全部
      await this.getPrize();
      this.projectId = null;
    }
    this.setState({
      tabActive: key,
    });
  });

  back = _throttle(async () => {
    // store.changePage(this.props?.from || PAGE_MAP.HOME_PAGE);
    store.backPage();
    sensorLog(LOG_KEY.click, "b12124", "d12126", {
      operation_name: "返回",
      button_name: "返回",
      operation_id: CFG.operationId,
    });
  });

  render() {
    const { records, tabActive, projectTabList } = this.state;
    return (
      <div className="prizepage_wrap modal_center">
        <div className="prizepage">
          <span className="bg"></span>
          <div className="all_tab">
            {projectTabList?.length > 0 &&
              projectTabList.map((val, key) => {
                return (
                  <Button
                    className={key == tabActive ? "tab_item" : "tab_item opacity"}
                    key={key}
                    onClick={() => this.switchTab(val, key)}>
                    {val?.projectName}
                    <span className={key == tabActive ? "stick" : "opacity"}></span>
                  </Button>
                );
              })}
          </div>
          <div className="list">
            {records?.length > 0 ? (
              records.map((item, index) => {
                return (
                  <div className="item" key={index} onClick={() => this.goPrizeDetail(item)}>
                    <span className="bg_item"></span>
                    <img src={item?.img} className="img" />
                    <span className="name">{item?.title}</span>
                    <span className="prize_time">中奖时间:{dateFormatter(item?.gmtCreate, "yyyy-MM-dd hh:mm:ss")}</span>
                    <span className="expire_time">
                      领奖截止日期:{dateFormatter(item?.expireTime, "yyyy-MM-dd hh:mm:ss")}
                    </span>
                    {item?.invalid ? <Button className="gray_btn grey"></Button> : <Button className="gobtn"></Button>}
                  </div>
                );
              })
            ) : (
              <div className="empty_wrap">
                <span className="empty_img"></span>
                <span className="empty">暂无数据</span>
              </div>
            )}
          </div>
          <Button className="back" onClick={this.back}></Button>
        </div>
      </div>
    );
  }
}
export default Prizepage;
