import withLayout from "@/layouts";
import image from "@/assets/icons/ProCard/8kb.jpg";
import { useState, useEffect } from "react";
import { Button, Checkbox, Input } from "@tarojs/components";
import food from "@/assets/icons/ProCard/food.png";
import ProCard_hot from "@/assets/icons/ProCard/ProCard_hot.png";
import CustomNav from "@/components/CustomNav";
import OrderMolded from "@/components/OrderMolded";
import Popup from "@/components/Popup";
import "./style.less";
import Taro, { useDidShow } from "@tarojs/taro";
import { getShopPackageDetail } from "@/services/home";
import { saveOrder, getOrderSub, payOrder } from "@/services/payOrder";
import formatTime from "@/utils/formatTime";

export default withLayout((props) => {
  const { router, person } = props;
  const { packageId, orderId } = props.router.params;

  const [payInfo, setPayInfo] = useState()

  const [showDialog, setShowDialog] = useState(false);
  // 是否已阅读协议
  const [agreement, setAgreement] = useState(false);
  // 总价 totalPrice
  const [totalPrice, setTotalPrice] = useState({});
  const [list, setList] = useState([]);

  const [BuyNumber, setBuyNumber] = useState(1);
  const [detail, setDetail] = useState({});

  const [DisabledBool, setDisabledBool] = useState(false);

  const ShowMoldeOn = (e) => {
    if (packageId) {
      setBuyNumber(e.amount || 1);
      setDetail(e);
      setShowDialog(true);
    }
  };
  const ButtonCancel = () => {
    setShowDialog(false);
  };
  const ButtonOK = (e) => {
    setList(
      list.map((x) =>
        x.packageId == detail.packageId ? { ...x, amount: BuyNumber } : x
      )
    );
    setShowDialog(false);
  };

  const NumberAdd = () => {
    setBuyNumber(BuyNumber + 1);
    console.log(BuyNumber);
  };

  const NumberCut = () => {
    if (DisabledBool) return;
    setBuyNumber(BuyNumber - 1);
    console.log(BuyNumber);
  };

  const onInput = (e) => {
    let values = e.detail.value;
    setBuyNumber(values - 0);
  };

  const requestPayment = (params) => {
    console.log(params, 'requestPayment')
    Taro.requestPayment({
      ...params,
      package: params.packageValue,
      success: () => {
        console.log("success");
        setPayInfo()
        Taro.showToast({
          title: "支付成功",
          icon: "none",
          duration: 2000,
        });
      },
      fail: (e) => {
        console.log(e, "fail");
        Taro.showToast({
          title: "支付失败",
          icon: "none",
          duration: 2000,
        });
      },
    });
  }

  const onShowPay = (e) => {
    if (agreement) {
      if (payInfo) {
        requestPayment(payInfo)
        return
      }
      if (packageId) {
        saveOrder(
          list.map((x) => {
            return {
              amount: x.amount || 1,
              itemId: x.packageId,
              price: x.actualPrice,
            };
          })
        ).then((res) => {
          setPayInfo(res)
          requestPayment(res)
        });
      }
      if (orderId) {
        payOrder(orderId).then((res) => {
          setPayInfo(res)
          requestPayment(res)
        });
      }
    } else {
      Taro.showToast({
        title: "请勾选《平台用户服务协议》",
        icon: "none",
        duration: 2000,
      });
    }
  };

  useEffect(() => {
    if (packageId) {
      getShopPackageDetail(packageId).then((res) => {
        setList([res]);
      });
    }
    if (orderId) {
      getOrderSub({ pageNum: 1, pageSize: 999, orderId }).then((res) => {
        setList(res.records);
      });
    }
  }, [packageId, orderId]);

  useEffect(() => {
    if (BuyNumber < 2) {
      setDisabledBool(true);
    } else {
      setDisabledBool(false);
    }
  }, [BuyNumber]);

  useEffect(() => {
    let total = {
      cashback: 0,
      actualPrice: 0,
      standardPrice: 0,
    };
    list.map((x) => {
      total.cashback += x.cashback * (x.amount || 1);
      total.actualPrice += (x.actualPrice || x.unitPrice) * (x.amount || 1);
      total.standardPrice += x.standardPrice * (x.amount || 1);
    });
    setTotalPrice(total);
  }, [list]);

  return (
    <view class="container">
      <CustomNav title="订单" />
      <Popup show={showDialog} maskClosable={false}>
        <OrderMolded item={detail} />
        <view className="item-center-Number">
          <view
            className="buy-num-minus"
            disabled={DisabledBool}
            onClick={NumberCut}
          >
            -
          </view>
          <Input
            className="buy-num-input"
            type="number"
            min="1"
            onInput={onInput}
            value={BuyNumber}
          />
          <view className="buy-num-add" onClick={NumberAdd}>
            +
          </view>
        </view>
        <view className="buy-button-box">
          <button className="button-Cancel" onClick={ButtonCancel}>
            取消
          </button>
          <button className="button-OK" onClick={ButtonOK}>
            确定
          </button>
        </view>
      </Popup>
      <view class="coupon-list">
        {list?.map((item) => {
          return (
            <view class="wrapper">
              <view class="left-complete-one">
                <image className="left-image-1" src={ProCard_hot}></image>
                <view className="left-viewText">
                  返现￥{(item.cashback || 0) / 100}
                </view>
                <view className="title-image">
                  <image
                    className="image-1"
                    mode="scaleToFill"
                    src={item.poster}
                  ></image>
                  <image className="image-2" src={food}></image>
                </view>
                <view className="title-content">
                  <view className="Pro-title">
                    <view className="title-text">{item.description}</view>
                  </view>
                  <text className="title-money">
                    ￥{(item.actualPrice || item.unitPrice || 0) / 100}元
                    <text className="title-money-2">
                      门市价{(item.standardPrice || 0) / 100}元
                    </text>
                  </text>
                  <view className="title-time">
                    有效期：{formatTime(item.startTime, "yyyy/MM/dd")}-
                    {formatTime(item.endTime, "yyyy/MM/dd")}
                  </view>
                </view>
              </view>
              <view
                class="right-complete-two"
                onClick={() => ShowMoldeOn(item)}
              >
                <view className="right-content">
                  <view className="right-number">×{item.amount || 1}</view>
                  <view className="right-title">数量</view>
                </view>
              </view>
            </view>
          );
        })}
      </view>
      <view className="view-button">
        <view className="Card-number-box">
          <view className="Card-number">
            <text style="left:29px;position: absolute; padding-top:20px">
              手机号码:
            </text>
            <text style="right:29px;position: absolute;padding-top:20px">
              {person.phone}
            </text>
          </view>
          <view className="Card-user">
            <Checkbox
              style="padding-left:20px; position: relative; top:24px;"
              value="agreement"
              checked={agreement}
              onClick={() => {
                setAgreement(!agreement);
              }}
            >
              我已阅读知晓并同意
              <text style="color:#274190;text-decoration:underline;font-weight:400">
                《平台用户服务协议》
              </text>
            </Checkbox>
          </view>
        </view>
        <view className="button-box-button-box">
          <view className="button-text-image">
            <text className="button-text-money-hot">
              返现￥{(totalPrice?.cashback || 0) / 100}
            </text>
            <image className="button-image" src={ProCard_hot}>
              123123
            </image>
            <view className="button-text-money">
              门店市面价：{(totalPrice?.standardPrice || 0) / 100}元
            </view>
          </view>
          <Button className="button-box-one" onClick={() => onShowPay()}>
            ￥{(totalPrice?.actualPrice || 0) / 100}元
            <text className="button-text-one">支付订单</text>
          </Button>
        </view>
      </view>
    </view>
  );
});
