import styles from "./index.module.scss";
import Layout from "~/components/layout";
import { Space, Image as AImage, Row, Col, Button, Divider, Badge } from "antd";
import { useContext, useEffect, useState } from "react";
import { DownOutlined, RightOutlined } from "@ant-design/icons";
import Image from "next/image";
import errImg from "~/assets/errImg";
import { useRouter } from "next/router";
// Import Swiper React components
import { Swiper, SwiperSlide } from "swiper/react";
import { Navigation } from "swiper";

// Import Swiper styles
import "swiper/css";
import "swiper/css/navigation";
import api, { GetLeaseGoodsDetailResp, ProductSpecList } from "./api";
import IntentionModal from "./components/intentionModal";
import { UserContext } from "~/lib/userProvider";

export default function MallDetail() {
  const { userInfo, setNeedLogin } = useContext(UserContext);
  const [visible, setVisible] = useState(false); //商品图预览
  const router = useRouter();
  const [id, setId] = useState<number | null>(null);
  const [detail, setDetail] = useState<GetLeaseGoodsDetailResp | null>(null); //详情数据
  const [intentionModalOpen, setIntentionModalOpen] = useState(false); //意向弹窗
  const [productImg, setProductImg] = useState(""); //展示的商品图
  const [previewIndex, setPreviewIndex] = useState(0); //预览开始索引
  const [checkItems, setCheckItems] = useState<ProductSpecList[]>([]); //选中的规格
  const [specCount, setSpecCount] = useState(0); //规格数量

  useEffect(() => {
    if (detail) {
      let count = 0;
      detail.goodsSpec?.forEach((good) => {
        good.productSpecList?.forEach((product) => {
          count++;
        });
      });
      setSpecCount(count);
    }
  }, [detail]);

  //打开意向modal
  const openIntentionModal = () => {
    if (userInfo) {
      setIntentionModalOpen(true);
    } else {
      setNeedLogin(true);
    }
  };

  //提交意向
  const handleIntentionOk = () => {
    setIntentionModalOpen(false);
  };

  const handleIntentionCancel = () => {
    setIntentionModalOpen(false);
  };

  useEffect(() => {
    setId(Number(router.query.id));
  }, [router]);

  useEffect(() => {
    if (id) {
      api
        .getLeaseGoodsDetail({
          goodsId: id,
          type: 0,
        })
        .then((res) => {
          setDetail(res.result || null);
          setProductImg(res.result?.images?.[0]?.imgUrl || "");
        });
    }
  }, [id]);

  return (
    <Layout>
      {/* 意向弹窗 */}
      <IntentionModal
        open={intentionModalOpen}
        detail={detail}
        onOk={handleIntentionOk}
        onCancel={handleIntentionCancel}
        onChange={(items: ProductSpecList[]) => setCheckItems(items)}
      ></IntentionModal>
      <div className="page" style={{ marginTop: 20, backgroundColor: "#fff" }}>
        <div style={{ display: "none" }}>
          <AImage.PreviewGroup
            preview={{
              visible,
              onVisibleChange: (vis) => setVisible(vis),
              current: previewIndex,
            }}
          >
            {detail?.images?.map((item) => {
              return <AImage key={item.id} src={item.imgUrl} />;
            })}
          </AImage.PreviewGroup>
        </div>
        <Space
          size={30}
          style={{ padding: "22px 24px 0", alignItems: "start" }}
        >
          {/* 商品图 */}
          <Space size={17} direction="vertical" style={{ width: 300 }}>
            <AImage
              preview={{ visible: false }}
              width={300}
              height={300}
              src={productImg}
              onClick={() => setVisible(true)}
              fallback={errImg}
              style={{
                borderRadius: 6,
              }}
            />
            <Swiper
              modules={[Navigation]}
              spaceBetween={6}
              slidesPerView={5}
              onSlideChange={() => console.log("slide change")}
              onSwiper={(swiper) => console.log(swiper)}
            >
              {detail?.images?.map((item, i) => {
                return (
                  <SwiperSlide key={item.id}>
                    <AImage
                      preview={false}
                      width={50}
                      height={50}
                      src={item.imgUrl}
                      fallback={errImg}
                      style={{ cursor: "pointer" }}
                      onClick={() => {
                        setProductImg(item.imgUrl), setPreviewIndex(i);
                      }}
                    />
                  </SwiperSlide>
                );
              })}
            </Swiper>
          </Space>

          <Space direction="vertical" size={17}>
            <div className={`${styles.font1} ${styles.ellipsis}`}>
              {detail?.goodsName}
            </div>
            <div className={`${styles.font2} ${styles.ellipsis2}`} style={{}}>
              {detail?.goodsDetail?.goodsDesc}
            </div>
            <Space
              size={24}
              direction="vertical"
              style={{
                padding: "24px 40px 0px 0",
                width: 470,
              }}
            >
              <Row wrap={false} justify="space-between">
                <Col span={12}>
                  <Row>
                    <Col flex="60px" className={styles.font3}>
                      选择
                    </Col>
                    <Col flex="auto" className={styles.font4} style={{}}>
                      已选：{checkItems.length}件
                    </Col>
                  </Row>
                </Col>
                <Col>
                  <Row align="middle" style={{ cursor: "pointer" }}>
                    <Col className={styles.font4} onClick={openIntentionModal}>
                      共{specCount}种可选
                    </Col>
                    <Col style={{ marginLeft: 9 }}>
                      <DownOutlined
                        style={{
                          fontSize: 12,
                          color: "RGBA(219, 219, 219, 1)",
                        }}
                      />
                    </Col>
                  </Row>
                </Col>
              </Row>
              <Row wrap={false}>
                <Col flex="60px" className={styles.font3}>
                  送至
                </Col>
                <Col flex="auto" style={{ cursor: "pointer" }}>
                  <Space size={5}>
                    <Image
                      alt=""
                      width={18}
                      height={18}
                      src={require("./assets/locate.png")}
                    ></Image>
                    <span className={`${styles.font3} ${styles.ellipsis}`}>
                      广东深圳市南山区万科云城创新谷6栋A座…
                    </span>
                  </Space>
                  <div className={styles.font4} style={{ marginTop: 7 }}>
                    现货，22:00前下单，预计后天（8月30日）送达
                  </div>
                </Col>
              </Row>
            </Space>
            <Space size={12} style={{ marginTop: 123 }}>
              <Button className={styles.btn1} onClick={openIntentionModal}>
                加入购物车
              </Button>
              <Button
                className={styles.btn2}
                type="primary"
                onClick={openIntentionModal}
              >
                提交意向
              </Button>
              <Space size={20} style={{ marginLeft: 19 }}>
                <div style={{ textAlign: "center", cursor: "pointer" }}>
                  <Image
                    alt=""
                    src={require("./assets/phone.png")}
                    width={20}
                    height={20}
                  ></Image>
                  <div className={styles.font5} style={{ marginTop: 5 }}>
                    电话
                  </div>
                </div>
                <div style={{ textAlign: "center", cursor: "pointer" }}>
                  <Badge count={55} size="small">
                    <Image
                      alt=""
                      src={require("./assets/car.png")}
                      width={20}
                      height={20}
                    ></Image>
                  </Badge>
                  <div className={styles.font5} style={{ marginTop: 5 }}>
                    购物车
                  </div>
                </div>
              </Space>
            </Space>
          </Space>
        </Space>
        <Divider className={styles.divider}>商品详情</Divider>
        <div style={{ textAlign: "center" }}>
          <div
            dangerouslySetInnerHTML={{
              __html: detail?.goodsDetail?.content || "",
            }}
          ></div>
        </div>
      </div>
    </Layout>
  );
}
