import React from "react";
import { observer } from "mobx-react";
import "./index.less";
// import { Button, Toast } from "@grace/ui";
import { motion } from "framer-motion";
import classNames from "classnames";
import API from "@src/api";
import { _throttle } from "@src/utils/utils";
import { PAGE_MAP } from "@src/utils/constants";
import { Button } from "@src/components/Button";

import modalStore from "@src/store/modal";
import modal from "@src/store";
import hxLink from "hx-product_detail-link";
// import { diffJump } from "@src/AppTool";

const EOpType = {
  Buy: "buy",
  Sell: "sell",
};

@observer
class DetailPage extends React.Component {
  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,
      buyInput: data.availableFunds / 100,
    });
  }

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

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

    console.log(buyInput);

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

    // +(+xxx * 100).toFixed(0) 解决精度问题 比如76.9*100=7690.000000000001 而不是7690
    if (+(+buyInput * 100).toFixed(0) < this.state.minBuyLimit) {
      // Toast.show("低于起购价");
      return;
    }

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

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

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

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

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

    console.log(sellInput);

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

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

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

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

  clickBack = () => {
    modal.changePage(PAGE_MAP.ACTUAL_HOME_PAGE);
  };

  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;
    // const isBuyed = false;

    return (
      <div className="DetailPage">
        {isBuyed ? (
          <div className="topArea">
            <div className="productName">{productName}</div>
            <div className="label1">累计收益（元）</div>
            <div className="totalProfit">{totalProfit / 100}</div>
            <div className="label2">持有份额</div>
            <div className="tranche">{tranche / 100}</div>
            <div className="label3">持有市值（元）</div>
            <div className="marketValue">{marketValue / 100}</div>
            <div className="label4">昨日收益（元）</div>
            <div className="yesterdayProfit">{yesterdayProfit / 100}</div>
          </div>
        ) : (
          <div className="topArea2">
            <div className="productName">{productName}</div>
          </div>
        )}
        <iframe className="prodIframe" src={iframeUrl} />

        <motion.div className="options">
          <div className="tab">
            <div
              className="tabItem"
              style={{
                color: tabType == EOpType.Buy ? "#EA1211" : "#333333",
              }}
              onClick={() => this.clickTab(EOpType.Buy)}>
              购买
            </div>
            <div
              className="tabItem"
              style={{
                color: tabType == EOpType.Sell ? "#EA1211" : "#333333",
              }}
              onClick={() => this.clickTab(EOpType.Sell)}>
              赎回
            </div>
            <motion.div className="actBar" animate={{ left: (isBuy ? 80 : 455) * remScale }} />
          </div>
          <motion.div
            className="buy"
            style={{
              opacity: isBuy ? 1 : 0,
            }}
            transition={{ type: "tween" }}
            initial={{ x: 0 }}
            animate={{ x: isBuy ? 0 : 750 * remScale }}>
            <div className="buyInfo">
              <div>买入金额</div>
              <span>可用资金：{availableFunds / 100}元</span>
            </div>
            <input
              className="bugInput"
              placeholder={`¥最低买入${minBuyLimit / 100}元`}
              type="text"
              inputMode="decimal"
              value={buyInput}
              onChange={(e) => this.handleInputChange(e, "buyInput")}
            />
            <div className="tip">
              首次购买{minBuyLimit / 100}元起 再次购买{minBuyLimit / 100}元起 {minBuyLimit / 100}元递增
            </div>
            <div className="btnArea">
              <Button className="btn simulate" onClick={this.clickSimulateBuy}>
                模拟买入
              </Button>

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

export default DetailPage;
