import React from 'react';
import { observer } from 'mobx-react';
import './MyPrize.less';
import { Button, Toast } from "@grace/ui";
import { _throttle, dateFormatter, isMiniprogram, miniGoUrl } from "@/utils/utils.ts";
import API from "@/api";
import { PageCtrl } from "@/core/ctrls/PageCtrl.tsx";
import { isWeChat } from '@/utils/share.ts';
import store from '@/store/store';
import { ModalCtrl } from '@/core/ctrls/ModalCtrl';
import HomePage from '../HomePage/HomePage.tsx';
import {Axios} from 'axios';
import FillAddress from '@/panels/FillAddress/FillAddress.jsx';
import { LOG_KEY, MatterShareOpt, MatterViewOpt, pageView, sensorLog,MatterViewDuration } from '../../utils/sensors.js';
import shareStore from '@/store/share.js';
import { handleLogClick, handleLogExposure } from '../../MD.ts';
const apiAxios = new Axios({
    timeout: 10000,
  });
@observer
class MyPrize extends React.Component {
    
    constructor(props) {
        super(props);
        this.state = {
            list: [],
            records: [],
            tabActive: 0,
            prizeInfo: {},
            projectTabList: [],
        };
        this.projectId = null;
    }


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

        sensorLog(LOG_KEY.exposure, "b14626", "d14628", {
            page_name: "我的奖品页",
            button_name: "返回按钮",
        });
        this.getPrize('');
        
    }

    getPrize = async (projectId) => {
        let params = {};
        if (projectId) {
            params = {
              projectId: projectId,
              page: 1,
              prod: CFG.env == "prod"
            };
          } else {
            params = {
              page: 1,
               prod: CFG.env == "prod"
            };
        }
        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, "b14626", "d14627", {
                        page_name: "我的奖品页",
                        button_name: "去查看按钮",
                    });
                }
            });
        }
    };
    /** 奖品跳转 app渠道可正常跳转领奖；微信公众号用户中奖后在我的奖品页点击【进入详情】按钮需换端app领奖 */
    // sp_bean 保豆跳转特殊处理
    goPrizeDetail = _throttle(async (item) => {
        if (item?.invalid) {
            Toast.show("奖品已过期");
            return;
        }
        handleLogClick(38)
        sensorLog(LOG_KEY.click, "b14626", "d14627", {
            page_name: "我的奖品页",
            button_name: "去查看按钮",
        });

        // stopSound('bg_music')
        const { recordId, url, itemType, recordInfo, projectId, drawStatus } = item;
        const { projectTabList } = this.state;
        console.log('itemType',itemType)
        if (isMiniprogram()) {
            //小程序渠道toast
            Toast.show("请前往人保寿险管家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") {
                    const resInfo = await apiAxios.request({
                        method: 'get',
                        url: codeUrl,
                    })
                    const res = JSON.parse(resInfo.data)
                    console.log('res',res)
                    if (!res?.success) {
                        return;
                    }
                    if (!recordInfo && !!res.data.boundYkCode) {
                        //未填写地址切绑定业务员
                        ModalCtrl.showModal(FillAddress,{
                                projectId: this.projectId,
                                saveAddresUrl: saveAddresUrl,
                                getPrize: this.getPrize,
                                recordId,
                                agentCode: res?.data?.boundYkCode,
                                prizeProjectId: projectId,
                        })
                    } else {
                        //已填写地址或未绑定业务员
                        if (recordInfo?.status == "0") {
                            Toast.show("已领取，请耐心等待发货～");
                        } 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,
        });
    });
    clickBack = () => {
        sensorLog(LOG_KEY.click, "b14626", "d14628", {
            page_name: "我的奖品页",
            button_name: "返回按钮",
        });
        // PageCtrl.backPage();
        PageCtrl.changePage(HomePage);
    }


    render() {

        const { records, tabActive, projectTabList } = this.state;
        return (
            <div className="prizepage_wrap">
                <div className="prizepage">
                    <span className="bg"></span>
                    <span className="title"></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) => {
                                !item?.invalid && handleLogExposure(38)
                                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>
                                );
                            })
                        ) : (
                            <span className="empty">暂无数据</span>
                        )}
                    </div>
                    <Button className="back md37" onClick={this.clickBack}></Button>
                </div>
            </div>
        );
    }
}

export default MyPrize;
