import React from 'react';
import { observer } from 'mobx-react';
import styles from './DetailPage.module.less';
import store from "@/store/store.ts";
import { Button, Toast } from "@grace/ui";
import { PageCtrl } from '@/core/ctrls/PageCtrl';
import { motion } from "motion/react"
import classNames from "classnames";
import API from "@/api";
import { _asyncThrottle } from '@/utils/utils';

import hxLink from "hx-product_detail-link";
import { ModalCtrl } from "@/core/ctrls/ModalCtrl.tsx";
import { BuyPanel } from "@/panels/BuyPanel/BuyPanel.tsx";
import { SellPanel } from '@/panels/SellPanel/SellPanel';
import JumpConfirmPop from '@/panels/jumpConfirmPop/jumpConfirmPop.jsx';
import { diffJump } from "@/AppTools.ts";
import HomePage from "@/pages/HomePage/HomePage.tsx";

enum EOpType {
    Buy = "buy",
    Sell = "sell",
}

@observer
class DetailPage extends React.Component<any, any> {

    state = {
        tabType: EOpType.Buy,
        productName: "",
        totalProfit: 0,
        tranche: 0,
        marketValue: 0,
        yesterdayProfit: 0,
        availableFunds: 0,
        minBuyLimit: 0,
        sellInput: "",
        buyInput: "",
        iframeUrl: "",
    }

    async componentDidMount() {
        this.getFrameUrl();
        this.updateInfo();
    }

    getFrameUrl = () => {
        // 1912121000101
        hxLink({ fundcode: this.props.code }).then((res) => {
            this.setState({
                iframeUrl: res.path,
            });
        });
    }

    async updateInfo() {
        const { success, data } = await API.mncpIndex({ code: this.props.code, });
        if (!success) return;
        this.setState({
            productName: data.productName,
            totalProfit: data.totalProfit,
            tranche: data.tranche,
            marketValue: data.marketValue,
            yesterdayProfit: data.yesterdayProfit,
            availableFunds: data.availableFunds,
            minBuyLimit: data.minBuyLimit,
        });
    }


    clickTab = (type: EOpType) => {
        this.setState({
            tabType: type,
        });
    }

    clickSimulateBuy = _asyncThrottle(async () => {
        const { buyInput } = this.state;

        console.log(buyInput);

        if (!+buyInput || buyInput.toString().trim() === "") {
            Toast.show("请输入买入金额");
            return;
        }

        if(+buyInput * 100 < this.state.minBuyLimit){
            Toast.show("低于起购价");
            return;
        }

        const div = +buyInput * 100 / this.state.minBuyLimit;
        if(div !== Math.floor(div)){
            Toast.show("按起购倍数递增哦～");
            return;
        }

        if (+buyInput * 100 > this.state.availableFunds) {
            Toast.show("超出买入上限啦");
            return;
        }

        ModalCtrl.showModal(BuyPanel, {
            name: this.state.productName,
            amount: buyInput,
            call: async () => {
                const { success, data } = await API.buy({ code: this.props.code, amount: +buyInput * 100 });
                this.updateInfo();
                if (!success) return;
                Toast.show("购买成功");
            }
        });
    });

    clickReallyBuy = _asyncThrottle(async () => {
        ModalCtrl.showModal(JumpConfirmPop, {
            confirmCb: () => {
                diffJump(this.props.realBuyJumpUrl)
            }
        })
    });


    clickSimulateSell = _asyncThrottle(async () => {
        const { sellInput } = this.state;

        console.log(sellInput);
        
        if (!+sellInput || sellInput.toString().trim() === "") {
            Toast.show("请输入赎回份额");
            return;
        }

        if (+sellInput * 100 > this.state.tranche) {
            Toast.show("超出赎回上限啦");
            return;
        }

        ModalCtrl.showModal(SellPanel, {
            name: this.state.productName,
            amount: sellInput,
            call: async () => {
                const { success, data } = await API.redeem({ code: this.props.code, amount: +sellInput * 100 });
                this.updateInfo();
                if (!success) return;
                Toast.show("赎回成功");
            }
        });
    });

    // 新增：输入校验，只允许数字和最多两位小数
    handleInputChange = (e: React.ChangeEvent<HTMLInputElement>, key: 'buyInput' | 'sellInput') => {
        let value = e.target.value;
        // 只允许输入数字和最多两位小数
        if (value === '' || /^\d*(\.\d{0,2})?$/.test(value)) {
            this.setState({
                [key]: value,
            });
        }
    }

    clickBack = () => {
        PageCtrl.changePage(HomePage);
    }

    render() {
        const {
            tabType, iframeUrl,
            productName, totalProfit, tranche, minBuyLimit,
            marketValue, yesterdayProfit, availableFunds,
            sellInput,
            buyInput,
        } = this.state;

        const isBuy = tabType == EOpType.Buy;

        const isBuyed = totalProfit || tranche || marketValue || yesterdayProfit;

        return <div className={styles.DetailPage}>
            {isBuyed ? <div className={styles.topArea}>
                <div className={styles.topBg}/>
                <div className={styles.productName}>{productName}</div>
                <div className={styles.totalProfit}>{totalProfit/100}</div>
                <div className={styles.tranche}>{tranche/100}</div>
                <div className={styles.marketValue}>{marketValue/100}</div>
                <div className={styles.yesterdayProfit}>{yesterdayProfit/100}</div>
            </div> : ""}
            <iframe className={styles.prodIframe} src={iframeUrl} />

            <motion.div
                className={styles.options}
                initial={{ height: 570 * remScale }}
                // animate={{ height: (isBuy ? 570 : 400) * remScale }}
            >
                <div className={styles.tab}>
                    <div
                        className={styles.tabItem}
                        onClick={() => this.clickTab(EOpType.Buy)}
                    >购买
                    </div>
                    <div
                        className={styles.tabItem}
                        onClick={() => this.clickTab(EOpType.Sell)}
                    >赎回
                    </div>
                    <motion.div
                        className={styles.actBar}
                        animate={{ left: (isBuy ? 61.5 : 436.5) * remScale }}
                    />
                </div>
                <motion.div
                    className={styles.buy}
                    transition={{ type: "tween" }}
                    initial={{ x: 0 }}
                    animate={{ x: isBuy ? 0 : 750 * remScale }}
                >
                    <div className={styles.buyInfo}>
                        <div>买入金额</div>
                        <span>可用资金：{availableFunds / 100}元</span>
                    </div>
                    <input
                        className={styles.bugInput}
                        placeholder={`¥最低买入${minBuyLimit / 100}元`}
                        type='text'
                        inputMode='decimal'
                        value={buyInput}
                        onChange={(e) => this.handleInputChange(e, 'buyInput')}
                    />
                    <div className={styles.buyTip}>首次购买{minBuyLimit/100}元起 再次购买{minBuyLimit/100}元起 {minBuyLimit/100}元递增</div>
                    <Button
                        className={classNames(styles.buyBtn, styles.simulateBuy, "md9")}
                        onClick={this.clickSimulateBuy}
                    >模拟买入</Button>

                    <Button
                        className={classNames(styles.buyBtn, styles.reallyBuy, "md10")}
                        onClick={this.clickReallyBuy}
                    >真实买入</Button>
                </motion.div>
                <motion.div
                    className={styles.sell}
                    transition={{ type: "tween" }}
                    initial={{ x: 750 * remScale }}
                    animate={{ x: isBuy ? 750 * remScale : 0 }}
                >
                    <div className={styles.sellInfo}>
                        <div>赎回份额</div>
                        <span>持有份额：{tranche/100}份</span>
                    </div>
                    <div className={styles.sellInput}>
                        <input
                            value={sellInput}
                            type='text'
                            inputMode='decimal'
                            placeholder={`最多可赎回${tranche / 100}份`}
                            onChange={(e) => this.handleInputChange(e, 'sellInput')}
                        />
                        <Button className={styles.sellAll} onClick={() => {
                            this.setState({
                                sellInput: tranche/100,
                            });
                        }}>全部</Button>
                    </div>
                    <Button
                        className={classNames(styles.sellBtn, styles.simulateSell, "md13")}
                        onClick={this.clickSimulateSell}
                    >模拟赎回</Button>
                    <Button
                        className={classNames(styles.sellBtn, styles.reallyBuy, "md10")}
                        onClick={this.clickReallyBuy}
                    >真实买入</Button>
                </motion.div>
            </motion.div>
            <Button
                className={classNames(styles.backBtn)}
                onClick={this.clickBack}
            />
        </div>;
    }
}

export default DetailPage;
