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: "",
        firtIn: true,
    }


    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,
            buyInput: data.availableFunds,
        });
    }


    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 (this.state.firtIn && (+buyInput < this.state.minBuyLimit)) {
            Toast.show("低于起购价");
            return;
        }

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

        let div = +buyInput * 100 / this.state.minBuyLimit;

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

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

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

        ModalCtrl.showModal(BuyPanel, {
            name: this.state.productName,
            amount: this.state.firtIn ? +buyInput / 100 : +buyInput,
            call: async () => {
                const { success, data } = await API.buy({ code: this.props.code, amount: !this.state.firtIn ? +buyInput * 100 : +buyInput});
                this.setState({
                  firtIn: true
                })
                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') => {
        key == 'buyInput' && this.setState({ firtIn: false })
        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,
            firtIn
        } = this.state;

        const isBuy = tabType == EOpType.Buy;

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

        return <div className={styles.DetailPage}>
            {isBuyed
                ? <div className={styles.topArea}>
                    <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>
                : <div className={styles.topArea2}>
                    <div className={styles.topBg} />
                    <div className={styles.productName}>{productName}</div>
                </div>
            }
            <iframe className={styles.prodIframe} src={iframeUrl} />

            <motion.div className={styles.options}>
                <div className={styles.tab}>
                    <div
                        className={styles.tabItem}
                        style={{
                            color: tabType == EOpType.Buy ? "#bc251c" : "#000000"
                        }}
                        onClick={() => this.clickTab(EOpType.Buy)}
                    >购买
                    </div>
                    <div
                        className={styles.tabItem}
                        style={{
                            color: tabType == EOpType.Sell ? "#bc251c" : "#000000"
                        }}
                        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={firtIn ? (Number(buyInput) / 100) : buyInput}
                        onChange={(e) => this.handleInputChange(e, 'buyInput')}
                    />
                    <div className={styles.tip}>首次购买{minBuyLimit / 100}元起
                        再次购买{minBuyLimit / 100}元起 {minBuyLimit / 100}元递增
                    </div>
                    <div className={styles.btnArea}>
                        <Button
                            className={classNames(styles.btn, styles.simulate, "md9")}
                            onClick={this.clickSimulateBuy}
                        >模拟买入</Button>

                        <Button
                            className={classNames(styles.btn, styles.really, "md10")}
                            onClick={this.clickReallyBuy}
                        >真实买入</Button>
                    </div>
                </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>
                    <div className={styles.tip}>{"  "}</div>
                    <div className={styles.btnArea}>
                        <Button
                            className={classNames(styles.btn, styles.simulate, "md13")}
                            style={{ width: "100%" }}
                            onClick={this.clickSimulateSell}
                        >模拟赎回</Button>
                    </div>
                </motion.div>
            </motion.div>
            <Button
                className={classNames(styles.backBtn)}
                onClick={this.clickBack}
            />
        </div>;
    }
}

export default DetailPage;
