import withLayout from "@/layouts";
import Taro, { useDidShow } from "@tarojs/taro";
import { getPackageDetail } from "@/services/home";
import { saveOrder, getOrderSub, payOrder } from "@/services/payOrder";
import { useState, useEffect } from "react";
import formatPrice from "@/utils/formatPrice";
import { Button, Radio, View } from "@tarojs/components";
import InputNumber from "@/components/InputNumber";
import AuthPage from '@/components/AuthPage'
import CustomNav from "@/components/CustomNav";
import OrderMolded from "@/components/OrderMolded";
import Popup from "@/components/Popup";
import Card from "./Card";
import "./style.less";


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

  const [payInfo, setPayInfo] = useState();

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

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

  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);
  };

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

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

  const requestPayment = (params) => {
    Taro.hideLoading()
    Taro.requestPayment({
      ...params,
      package: params.packageValue,
      success: () => {
        setPayInfo();
        Taro.redirectTo({
          url: "/pages/MineUserAll/AllOrder/index",
        });
        Taro.showToast({
          title: "支付成功",
          icon: "none",
          duration: 2000,
        });
      },
      fail: (e) => {
        Taro.showToast({
          title: "支付失败",
          icon: "none",
          duration: 2000,
        });
      },
    });
  };

  const onShowPay = (e) => {
    if (agreement) {
      if (payInfo) {
        requestPayment(payInfo);
        return;
      }
      Taro.showLoading({
        title: '支付中',
      })

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

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

  //用户协议
  const goRules = () => {
    Taro.navigateTo({ url: `/pages/MineUserAll/Rules/index` })

  }

  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 (
    !person.phone ? <AuthPage /> :
      <view class='page-index container'>
        <view className='index-navbar'>
          <CustomNav title='订单' />
        </view>
        <Popup show={showDialog} maskClosable={false}>
          <OrderMolded item={detail} />
          <InputNumber value={BuyNumber} onChange={x => setBuyNumber(x)} style={{ marginTop: '40rpx' }} />
          <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-box'>
          {(list || []).map((item, index) => {
            return (
              <Card key={index} item={item} packageId={packageId} onMoldeOn={ShowMoldeOn} />
            );
          })}
        </view>
        <view className='view-button'>
          {/* 协议条款 */}
          <view className='Card-number-box'>
            <view className='Card-number'>
              <text>
                手机号码:
              </text>
              <text style='right:0;position: absolute;'>
                {person.phone}
              </text>
            </view>
            <view className='Card-user'>
              <Radio
                className='Radio-text'
                value='agreement'
                checked={agreement}
                onClick={() => {
                  setAgreement(!agreement);
                }}
              >
                我已阅读知晓并同意
              </Radio>
              <text className='ptxy' onClick={goRules}>
                《平台用户服务协议》
              </text>
            </view>
            <view className='ul-li-text'>
              <view className='ul-li-view'></view>
              <text className='ul-li-textname'>返现金将以退款形式到账</text>
            </view>

          </view>
          {/* 支付按钮 */}
          <Button className='payorder' onClick={() => onShowPay()}>
            <View className='paytext'>￥{formatPrice(totalPrice?.actualPrice || 0)}元</View>
            <View className='paycontent'>
              <View className='paybuttontop'>返现￥{formatPrice(totalPrice?.cashback || 0)}</View>
              <View className='paybuttonbottom'>门店市面价：{formatPrice(totalPrice?.standardPrice || 0)}元</View>
            </View>
            <View className='paytext'>支付订单</View>
          </Button>
        </view>
      </view>
  );
});
