import { Component } from "react";
import {
  View,
  Text,
  Swiper,
  SwiperItem,
  Image,
} from "@tarojs/components";
import { AtIcon } from "taro-ui";
import {
  getProductDetail,
  getProductLikeList,
  getProductPromotion,
  getShareJump,
  bindShareJump,
} from "../../../service";
import "./index.less";
import Taro from "@tarojs/taro";
import productDetailIcon from "../../../images/productDetail/productDetailIcon.png";
import like from "../../../images/productDetail/like.png";
import home from "../../../images/nav/home.png";
import selfBuy from "../../../images/productDetail/selfBuy.png";
import share from "../../../images/productDetail/share.png";
import ProductCard from "../../../components/ProductCard"; //产品卡片
import Modal from "../../../components/Modal"; //弹窗
import ShareModal from "../../../components/shareModal"; //分享弹窗
export default class Index extends Component {
  state = {
    id: "", //商品id
    isShare: false, //是否是分享
    isOpened: '', //是否打开弹窗
    productDetail: [], //商品详情
    productLikeList: [], //推荐商品列表
    productPromotion: [], //商品推广转链
    isHighCommission: false, //是否是高佣金页面
    isSeckill: false, //是否是秒杀页面
    shareJump: "", //分享跳转标识
  };
  // 获取产品详情的方法
  fetchProductDetails = async (id) => {
    const res = await getProductDetail({
      goods_id: id,
    });
    this.setState(
      {
        productDetail: res,
      },
      () => {
        let session_key = Taro.getStorageSync("session_key");
        if (session_key) {
          this.getProductPromotion(); //获取商品推广转链
        }
      }
    );
  };
  // 获取猜你喜欢列表
  getProductLikeList = async () => {
    const res = await getProductLikeList();
    this.setState({
      productLikeList: res,
    });
  };
  // 获取商品推广转链
  getProductPromotion = async () => {
    const res = await getProductPromotion({
      goods_id: [this.state.id],
      item_id: [this.state.productDetail.item_id],
    });
    this.setState({
      productPromotion:
        res.alibaba_idle_affiliate_general_link_convert_response.result.result,
    });
  };
  componentDidMount() {
    const { id, isShare, isHighCommission, isSeckill, shareJump } =
      Taro.getCurrentInstance().router.params;
    this.setState(
      {
        id,
        isShare,
        isHighCommission: isHighCommission === "true",
        isSeckill: isSeckill === "true",
      },
      () => {
        // 获取分享跳转标识
        shareJump &&
          Taro.setStorage({
            key: "shareJump",
            data: shareJump,
          });
        this.fetchProductDetails(id); //获取产品详情
        this.getProductLikeList(); //获取猜你喜欢列表
        let session_key = Taro.getStorageSync("session_key");
        if (session_key && shareJump) {
          this.bindShareJump(); //绑定分享跳转标识
        }
      }
    );
  }
  // 复制商品编号
  handleCopy = (text) => {
    Taro.setClipboardData({
      data: text,
      success: () => {
        Taro.showToast({
          title: "复制成功",
          icon: "success",
        });
      },
    });
  };

  // 添加跳转首页方法
  handleToHome = () => {
    Taro.switchTab({
      url: "/pages/index/index",
    });
  };

  // 立即购买
  handleBuy = async () => {
    if (!this.state.productPromotion.short_tpwd) {
      await this.getProductPromotion();
    }
    this.setState({
      isOpened: 'self',
    });
  };

  // 分享
  openSharePopup = async () => {
    const res = await getShareJump({
      share_type: 1,
      share_id: this.state.id,
    });
    this.setState({
      shareJump: res.share_unique_value,
      isOpened: 'share',
    });
  };
  // 绑定分享跳转标识
  bindShareJump = async () => {
    let shareJump = Taro.getStorageSync("shareJump");
    await bindShareJump({
      share_type: 1,
      share_unique_value: shareJump,
    });
    Taro.removeStorageSync("shareJump");
  };
  // 配置分享内容
  onShareAppMessage() {
    return {
      title: this.state.productDetail.item_title,
      path: `/pages/indexSub/productDetail/index?id=${this.state.id}&&isShare=true&&isHighCommission=${this.state.isHighCommission}&&isSeckill=${this.state.isSeckill}&&shareJump=${this.state.shareJump}`,
      imageUrl: this.state.productDetail.images[0].img,
    };
  }
  // 添加返回方法
  handleBack = () => {
    const pages = Taro.getCurrentPages();
    if (pages.length > 1) {
      Taro.navigateBack();
    } else {
      Taro.switchTab({
        url: "/pages/index/index",
      });
    }
  };
  render() {
    const { productDetail } = this.state;
    return (
      <View
        className="index"
        style={{ paddingTop: Taro.navigationBarHeight + "px" }}
      >
        {!this.state.isShare && (
          <View className="back-btn" onClick={this.handleBack}>
            <AtIcon value="chevron-left" size="24" color="#999999"></AtIcon>
          </View>
        )}
        {/* 轮播图 */}
        <Swiper className="swiper" autoplay circular>
          {productDetail.images &&
            productDetail.images.map((imageObj, index) => (
              <SwiperItem key={index}>
                <Image
                  className="swiper-img"
                  src={imageObj.img}
                  mode="aspectFill"
                />
              </SwiperItem>
            ))}
        </Swiper>
        {/* 商品详情模块 */}
        <View className="product-info">
          {/* 商品名称 */}
          <Text className="product-name">
            <Text className="self-tag">
              {this.state.isHighCommission
                ? "高佣专项"
                : this.state.isSeckill
                ? "鱼市秒杀"
                : "自营"}
            </Text>
            {productDetail.item_title}
          </Text>

          {/* 价格和标签行 */}
          <View className="price-tag-row">
            {/* 价格区域 */}
            <View className="price-box">
              <Text className="current-price">
                <Text className="currency">¥</Text>
                {productDetail.reserve_price}
              </Text>
              {productDetail.original_price != "0.00" && (
                <Text className="original-price">
                  ¥{productDetail.original_price}
                </Text>
              )}
            </View>
            {/* 标签区域 */}
            <View className="tag-box">
              <Text className="tag">
                分享赚￥{productDetail.estimated_commission}
              </Text>
            </View>
          </View>

          {/* 分割线 */}
          <View className="divider" />

          {/* 商品编号行 */}
          <View className="product-number-row">
            <Text className="number-label">
              商品编号：{productDetail.goods_number}
            </Text>
            <Text
              className="copy-btn"
              onClick={() => this.handleCopy("123456")}
            >
              复制
            </Text>
          </View>
        </View>
        {/* 商品标签模块 */}
        <View className="product-tag-row">
          <View className="tag-item">
            <Image src={productDetailIcon} mode="aspectFit" />
            <Text className="tag-text">渔市商品</Text>
          </View>
          <View className="tag-item">
            <Image src={productDetailIcon} mode="aspectFit" />
            <Text className="tag-text">品质保证</Text>
          </View>
          <View className="tag-item">
            <Image src={productDetailIcon} mode="aspectFit" />
            <Text className="tag-text">无忧售后</Text>
          </View>
        </View>
        {/* 猜你喜欢 */}
        <View className="guess-you-like">
          <Image src={like} mode="aspectFit" />
          <Text className="title">猜你喜欢</Text>
        </View>
        {/* 猜你喜欢产品列表 */}
        <View className="product-card-list">
          {this.state.productLikeList.map((product) => (
            <ProductCard key={product.id} product={product} />
          ))}
        </View>
        {/* 底部购买模块 */}
        <View className="bottom-buy">
          <View onClick={this.handleToHome} className="bottom-buy-left">
            <Image src={home} mode="aspectFit" />
            <Text className="bottom-buy-text">首页</Text>
          </View>
          <View className="bottom-buy-right">
            {!this.state.isShare ? (
              <>
                <View
                  onClick={this.openSharePopup}
                  className="bottom-buy-right-self"
                >
                  <Image src={share} mode="aspectFit" />
                  <Text className="bottom-buy-text">分享赚</Text>
                </View>
                <View
                  onClick={this.handleBuy}
                  className="bottom-buy-right-share"
                >
                  <Image src={selfBuy} mode="aspectFit" />
                  <Text className="bottom-buy-text">自购省</Text>
                </View>
              </>
            ) : (
              <View onClick={this.handleBuy} className="bottom-buy-right-btn">
                <Text className="bottom-buy-text">立即购买</Text>
              </View>
            )}
          </View>
        </View>
        {/* 自购弹窗 */}
        <Modal
          title="咸鱼口令已复制"
          isOpened={this.state.isOpened=='self'}
          productPromotion={this.state.productPromotion}
          linkText={this.state.productPromotion.short_tpwd}
        />
        {/* 分享弹窗 */}
        <ShareModal
          isOpened={this.state.isOpened=='share'}
          onClose={() => this.setState({ isOpened: '' })}
          title="分享赚"
        />
      </View>
    );
  }
}
