import React from 'react';
import { Input } from 'antd';
import Big from 'big.js';
import { GetServerSidePropsContext } from 'next';
import { useRouter } from 'next/router';
import { useSelector } from 'react-redux';
import styled from 'styled-components';
import { InterDataType } from '@/api/interface';
import { AppMallGoodsDetails } from '@/api/interface/mall';
import { MallAPI } from '@/api/modules/mall';
import BreadcrumbView from '@/components/breadcrumb';
import LayoutView from '@/components/layout';
import PaymentCheckout from '@/components/payment-checkout';
import SubmitAddressView from '@/components/submit-comp/submit-address';
import SubmitProductView from '@/components/submit-comp/submit-product';
import { GlobalDataState } from '@/store/module/globalData';
import { formatMoney } from '@/utils/money';

// 商品详情类型
type DetailType = InterDataType<AppMallGoodsDetails>;
// 每次加载页面都会执行
export async function getServerSideProps(context: GetServerSidePropsContext) {
  // 商品id
  const id: number = Number(context.params?.id);
  // 商品详情
  let productDetail: DetailType | undefined;
  // 获取商品详情
  const getMallGoodsDetails = async () => {
    const res = await MallAPI.appMallGoodsDetails({ id });
    if (res && res.code === '200') {
      productDetail = res.result;
      // console.log('获取商品详情 --->', res);
    }
  };
  // 依次获取接口数据
  await (async () => {
    await getMallGoodsDetails();
  })();
  return { props: { id, productDetail } };
}
// 客户端组件
const MallCartSubmitView: React.FC<{
  productDetail: DetailType;
}> = ({ productDetail }) => {
  // 路由钩子
  const router = useRouter();
  // globalData
  const globalData = useSelector(
    (state: any) => state.globalData,
  ) as GlobalDataState;
  // 获取当前用户选择的地址
  const getUserAddressCurrent = () => {
    const item = globalData?.userAddressList?.find(
      (i) => i.id === globalData?.userAddressSelectId,
    );
    return {
      ...item,
      takeRegion: item?.takeRegion?.split('/')?.join(' '),
    };
  };
  // 获取商品的结算价格
  const getCheckoutPrice = () => {
    const item = router?.query?.specId
      ? productDetail?.priceStock?.find(
          (i) => i.id === Number(router?.query?.specId),
        )
      : productDetail?.priceStock?.at(0);
    const salePrice = Big(item?.salePrice || 0);
    const productSpecNum = Big(globalData?.productSpecNum || 1);
    return salePrice.mul(productSpecNum)?.toNumber();
  };
  return (
    <LayoutView>
      <MallCartSubmitWrap>
        <BreadcrumbView />
        <SubmitAddressView />
        <SubmitProductView detail={productDetail} />
        <div className="submit-remark flex-start">
          <div className="remark-view flex-start">
            <div className="label">备注：</div>
            <div className="input">
              <Input.TextArea
                placeholder={'请输入备注'}
                maxLength={50}
                showCount
              />
            </div>
          </div>
        </div>
        <div className="submit-checkout flex-start">
          <div className="checkout-view">
            <div className="checkout-item checkout-price flex-end">
              <div className="label">实付款：</div>
              <div className="unit">￥</div>
              <div className="price">{formatMoney(getCheckoutPrice())}</div>
            </div>
            <div className="checkout-item flex-end">
              <div className="label">寄送至：</div>
              <div className="text">
                {getUserAddressCurrent()?.takeRegion}{' '}
                {getUserAddressCurrent()?.takeAddress}
              </div>
            </div>
            <div className="checkout-item item-last flex-end">
              <div className="label">收货人：</div>
              <div className="text">
                {getUserAddressCurrent()?.takeName}{' '}
                {getUserAddressCurrent()?.takePhone}
              </div>
            </div>
            <PaymentCheckout cost={getCheckoutPrice()} />
          </div>
          <div className="checkout-submit select-none cursor-pointer">
            提交订单
          </div>
        </div>
      </MallCartSubmitWrap>
    </LayoutView>
  );
};

export default MallCartSubmitView;
// 样式
const MallCartSubmitWrap = styled.div`
  position: relative;
  max-width: 1190px;
  box-sizing: border-box;
  padding: 2rem 0 0 0;
  margin: 0 auto;
  .submit-remark {
    position: relative;
    width: 100%;
    min-height: 4.5rem;
    background: #f2f7ff;
    border: 0.04rem solid #d0eaf5;
    padding: 0.67rem;
    margin-bottom: 1rem;
    .remark-view {
      position: relative;
      height: 100%;
      align-items: flex-start;
      .label {
        font-weight: bold;
        color: #333333;
      }
      .input {
        min-height: 4rem;
        width: 25rem;
      }
    }
  }
  .submit-checkout {
    position: relative;
    width: 100%;
    padding-bottom: 2rem;
    box-sizing: border-box;
    align-items: flex-end;
    flex-direction: column;
    .checkout-view {
      position: relative;
      width: 25rem;
      min-height: 8rem;
      border: 1px solid #ff5001;
      box-sizing: border-box;
      display: flex;
      align-items: flex-end;
      justify-content: flex-start;
      flex-direction: column;
      padding: 0.5rem 0.67rem 1rem 0.67rem;
      .checkout-item {
        align-items: baseline;
        margin-bottom: 0.33rem;
        .label {
          font-weight: bold;
          color: #333333;
        }
        .unit {
          color: #ff6700;
          font-size: 16px;
        }
        .price {
          color: #ff6700;
          font-size: 24px;
          font-weight: bold;
        }
        .text {
          max-width: 86%;
        }
      }
      .item-last {
        margin-bottom: 0.66rem;
      }
    }
    .checkout-submit {
      position: relative;
      width: 8.58rem;
      height: 2.63rem;
      background: #ff552d;
      line-height: 2.63rem;
      border: 0.04rem solid #ff5001;
      text-align: center;
      font-size: 16px;
      color: #ffffff;
      box-sizing: border-box;
      &:active {
        filter: brightness(0.9);
      }
    }
  }
`;
