import React from 'react';
import { GetServerSidePropsContext } from 'next';
import { InterDataType } from '@/api/interface';
import {
  AppMallGoodsDetails,
  GetCompanyInfoByBUId,
} from '@/api/interface/mall';
import { MallAPI } from '@/api/modules/mall';
import BreadcrumbView from '@/components/breadcrumb';
import LayoutView from '@/components/layout';
import ProductHeadView from '@/components/product-comp/product-head';
import ProductStoreView from '@/components/product-comp/product-store';
import { ProductWrap } from '@/pages/mall/product/styled';

// 商品详情类型
type DetailType = InterDataType<AppMallGoodsDetails>;
// 商城详情类型
type StoreType = InterDataType<GetCompanyInfoByBUId>;

// 每次加载页面都会执行
export async function getServerSideProps(context: GetServerSidePropsContext) {
  // 商品id
  const id: number = Number(context.params?.id);
  // 商品详情
  let productDetail: DetailType | undefined;
  // 店铺详情
  let storeDetail: StoreType | undefined;
  // 获取商品详情
  const getMallGoodsDetails = async () => {
    const res = await MallAPI.appMallGoodsDetails({ id });
    if (res && res.code === '200') {
      productDetail = res.result;
      // console.log('获取商品详情 --->', res);
    }
  };
  // 获取店铺详情
  const getCompanyInfoById = async () => {
    const res = await MallAPI.getCompanyInfoByBUId({
      backUserAccountId: Number(productDetail?.userAccountId),
    });
    if (res && res.code === '200') {
      storeDetail = res.result;
      // console.log('获取店铺详情 --->', res);
    }
  };
  // 依次获取接口数据
  await (async () => {
    await getMallGoodsDetails();
    await getCompanyInfoById();
  })();
  return { props: { id, productDetail, storeDetail } };
}

const MallProductView: React.FC<{
  id: number;
  productDetail: DetailType;
  storeDetail: StoreType;
}> = ({ productDetail, storeDetail }) => {
  return (
    <LayoutView>
      <ProductWrap>
        {/* 面包屑 */}
        <BreadcrumbView />
        <div className="flex-start align-start">
          <ProductHeadView detail={productDetail} />
          <ProductStoreView detail={productDetail} store={storeDetail} />
        </div>
        <div className="product-title">商品详情</div>
        <div className="product-richText">
          {productDetail?.goodsDetails && (
            <div
              className="content-html"
              dangerouslySetInnerHTML={{ __html: productDetail?.goodsDetails }}
            />
          )}
        </div>
      </ProductWrap>
    </LayoutView>
  );
};

export default MallProductView;
