import Taro, { useShareAppMessage } from "@tarojs/taro";
import CustomNav from "@/components/CustomNav";
import withLayout from "@/layouts";
import {
  getShopDetail,
  getShopPackage,
  getExtendContent,
} from "@/services/home";
import { getVerifyTargetList } from "@/services/payOrder";
import { useState, useEffect, useRef } from "react";
import { Button, View, Ad } from "@tarojs/components";
import Star from "@/components/Star/Star.jsx";
import NoData from '@/components/NoData'
import Cards from "@/components/foodCards/foodCards.jsx";
import SpinBox from "@/components/Spin/SpinBox";
import TabIcon from "@/components/HorTabbar/TabIcon";
import ax from "@/assets/icons/housemantj/onlove.png";
import yysj from "@/assets/icons/housemantj/openTime.png";
import dw from "@/assets/icons/housemantj/loc-o.png";
import phoneImg from "@/assets/icons/housemantj/phone-o.png";
import zhuandao from "@/assets/icons/housemantj/backTop.png";
import titlezs from "@/assets/icons/housemantj/titleTip.png";
import share from "@/assets/icons/housemantj/touristShare.png";
import good from "@/assets/icons/housemantj/touristGood.png";
import baozan from "@/assets/icons/housemantj/bgood.png";
import weibaozan from "@/assets/icons/housemantj/unLike.png";
import logo from "@/assets/icons/UserCenter/laba.png"

import useSave from "@/utils/hooks/useSave";
import useLike from "@/utils/hooks/useLike";
import Extend from "../components/Extend/extend";
import ImageList from "../components/ImageList";
import "./foodDetails.less";

export default withLayout((props) => {
  const { router, person, location } = props;
  const { id, subOrderId, scene } = props.router.params;

  useEffect(() => {
    if (id && (scene || subOrderId)) {
      getVerifyTargetList({
        shopId: id,
        isMine: true,
        isVerified: 0,
      }).then((res) => {
        if (res?.records?.length > 0) {
          Taro.navigateTo({
            url: `/pages/TobeShop/index?id=${id}&subOrderId=${subOrderId}`,
          });
        }
      });
    }
  }, [id, scene, subOrderId]);

  //商铺基础信息
  const [loading, setLoading] = useState(false)
  const [detail, setDetail] = useState({});
  //商铺套餐
  const [spackage, setPackage] = useState([]);
  //banner图集数组
  const [imglist, setimglist] = useState([]);

  const [isSaved, toggleSave] = useSave(detail.isSaved, "shop", id);
  const [isLike, toggleLike] = useLike(detail.isLike, "shop", id);

  //引导显隐
  const [guidance, setGuidance] = useState('shareOff')
  //引导显隐

  useEffect(() => {
    if (router.params.scene || router.params.enterType === "share") {
      setGuidance('shareOn')
    }
  }, [router.params.enterType, router.params.scene])

  //本店指南
  const [extend, setExtend] = useState([]);

  const openMap = () => {
    Taro.openLocation({
      longitude: log.current - 0,
      latitude: lat.current - 0,
      name: detail.shopName,
      address: detail.address,
      scale: 12,
    });
  };
  const log = useRef("");
  const lat = useRef("");

  const handlePhone = () => {
    if (!detail.phone) {
      Taro.showToast({
        title: '暂无商家联系方式',
        icon: 'none',
      })
      return;
    }
    Taro.makePhoneCall({
      phoneNumber: detail.phone
    })
  }

  useEffect(() => {
    if (id) {
      setLoading(true)
      getShopDetail(id, { location }).then((res) => {
        setDetail(res);
        log.current = res.locaton.toString().split(",")[0];
        lat.current = res.locaton.toString().split(",")[1];
        setimglist(res.imageList || []);
        setLoading(false)
      }).catch(() => setLoading(false));
      getShopPackage(id, { pageSize: 500 }).then((res) => {
        setPackage(res.records || []);
      });
      getExtendContent("shop", id, { pageSize: 500 }).then((res) => {
        setExtend(res.records || []);
      });
    }
  }, [id]);

  const star = parseFloat(
    (
      (detail.sweetScore + detail.environmentScore + detail.serviceScore) / 3).toFixed(1)
  );

  // 分享
  useShareAppMessage(() => {
    // setShareAppMessage('shareOff')
    return {
      title: detail.shopName,
      path: `/pages/details/foodDetails/foodDetails?id=${id}&subOrderId=${subOrderId}&enterType=share`,
      imageUrl: detail.poster,

    };
  });
  const [isScroll, setScroll] = useState(true)
  return (
    <view className='page-index'>
      {
        guidance === 'shareOn' ? <view className='index-navbar'>
          <add-tipsFood logo={logo} custom duration={-1} />
          <CustomNav title='十公里' noback />
        </view> :
          <view className='index-navbar'>
            <CustomNav title='十公里' />
          </view>
      }
      <SpinBox loading={loading} className='index-container' style={{ padding: '0 30rpx', background: '#F8F8F8' }}>
        <scroll-view
          scrollY={isScroll}
          style={{ height: '100%' }}
        >
          <view className='storeDetails'>
            <ImageList imglist={imglist} />
            <view className='storeJs'>
              <view style={{ overflow: "hidden" }}>
                <view className='storeName'>{detail.shopName}</view>
                <view className='sprice'>
                  <text className='t1'>￥</text>
                  {detail.averagePrice / 100}/人
                  <view className='bzRight'>
                    <image
                      src={baozan}
                      style={{
                        width: "15px",
                        height: "15px",
                        marginRight: "11rpx",
                        marginBottom: "-2px",
                      }}
                    />
                    爆赞{detail.likeNum}
                  </view>
                </view>
              </view>
              <view className='appraise'>
                <Star star={star} />
                {star}
                <view style={{ float: "right", marginTop: "5px" }}>
                  <text className='comment'>点评：</text>
                  <text className='t1'>口味：{detail.sweetScore}</text>
                  <text className='t1'>环境：{detail.environmentScore}</text>
                  <text className='t1'>服务：{detail.serviceScore}</text>
                </view>
              </view>
              <view className='yysj'>
                <image src={yysj} className='yysjImg' />
                <text>营业时间：{detail.businessHours}</text>
                <view style={{ float: 'right', paddingLeft: '30rpx', borderLeft: '1px dotted #999' }} onClick={handlePhone}>
                  <image src={phoneImg} style={{ width: '32rpx', height: '32rpx' }} />
                </view>
              </view>
              <view className='dpPosition' onClick={openMap}>
                <image src={dw} className='dwTip' />
                <view>
                  {detail.address}
                  <image src={zhuandao} className='zhuandao' />
                </view>
              </view>
            </view>
          </view>
          {
            spackage == '' && extend == "" ?
              <NoData /> :
              <>
                <view
                  style={{
                    position: "relative",
                    display: spackage == "" ? "none" : "",
                  }}
                >
                  <view className='title'>
                    <image src={titlezs} />
                    <text>返现套餐</text>
                  </view>
                  {(spackage || []).map((item) => (
                    <Cards scene={scene} id={id} setScroll={setScroll} subOrderId={subOrderId} key={item.packageId} editable='1' st={star} goshop='1' item={item} det={detail} />
                  ))}
                </view>
                <view class='adContainer'>
                  <Ad unit-id='adunit-a0f97bb7ec8ec7bb' ad-intervals='30' />
                </view>
                <view
                  style={{
                    display: extend == "" ? "none" : "",
                  }}
                >
                  <view className='title'>
                    <image src={titlezs} />
                    <text>本店指南</text>
                  </view>
                  <View style={{ background: '#FFF' }}>
                    {(extend || []).map((item) => (
                      <Extend key={item.extId} item={item} />
                    ))}
                  </View>
                </view>
                <view
                  className='botton'
                >
                  这是我的底线
                </view>
              </>
          }
        </scroll-view>
      </SpinBox>
      <view className='index-tabber weui-tabbar' style={{ background: '#fff' }}>
        <view className='weui-tabbar__item'>
          <Button openType='share' className='purebtn'><TabIcon icon={share} text='分享' /></Button>
        </view>
        <view className='weui-tabbar__item' onClick={toggleLike}>
          <TabIcon icon={isLike > 0 ? baozan : weibaozan} text={isLike > 0 ? "已爆赞" : "爆赞"} />
        </view>
        <view className='weui-tabbar__item' onClick={toggleSave}>
          <TabIcon icon={isSaved > 0 ? ax : good} text={isSaved > 0 ? "已收藏" : "加入收藏"} />
        </view>
      </view>
    </view>
  );
});
