import {useEffect, useState} from 'react'
import {Image, Tag} from '@nutui/nutui-react-taro'
import {useRouter} from '@tarojs/taro'
import {Divider} from '@nutui/nutui-react-taro'
import dayjs from 'dayjs'
import Taro, {
  useLoad,
  useShareAppMessage,
  useShareTimeline,
} from '@tarojs/taro';
import {CmsArticle} from "@/api/cms/cmsArticle/model"
import {Eye, Clock, PickedUp, Purse, Coupon} from '@nutui/icons-react-taro'
import AddCartBar from "@/components/AddCartBar";
// 显示html富文本
import {View, RichText} from '@tarojs/components'
import './detail.scss'
import Line from "@/components/Gap";
import {wxParse} from "@/utils/common";
import {getCmsArticle} from "@/api/cms/cmsArticle";
import {pageBszxPay} from "@/api/bszx/bszxPay";
import {getUserInfo, getWxOpenId} from "@/api/layout";

function Detail() {
  const {params} = useRouter();
  // 文章详情
  const [item, setItem] = useState<CmsArticle>()
  // 浏览量
  const [views, setViews] = useState<number>()
  // 报名人数
  const [bmUsers, setBmUsers] = useState<number>()
  // 是否登录
  const [isLogin, setIsLogin] = useState<boolean>(false)
  const reload = () => {
    getCmsArticle(Number(params.id)).then(data => {
      if (data) {
        data.content = wxParse(data.content)
        setItem(data)
        setViews(data.actualViews)
      }
    })
    pageBszxPay({
      formId: Number(params.id),
    }).then(res => {
      if (res) {
        setBmUsers(res.count)
      }
    })
    // 登录
    Taro.getUserInfo({
      success: (res) => {
        console.log(res.userInfo.avatarUrl)
        getUserInfo().then((data) => {
          if (data) {
            setIsLogin(true);
            console.log(isLogin,'isLogin')
            Taro.setStorageSync('UserId', data.userId)
            // 获取openId
            if (!data.openid) {
              Taro.login({
                success: (res) => {
                  getWxOpenId({code: res.code}).then(() => {
                  })
                }
              })
            }
          }
        }).catch(() => {
          console.log('未登录')
        });
      }
    });
  }

  useLoad(async () => {
    //获取进入页面参数 scene为1154===朋友圈进入
    const data = Taro.getLaunchOptionsSync();
    console.log(data, 'data')
    //开启分享
    Taro.showShareMenu({
      withShareTicket: true,
    });
  })

  useShareTimeline(() => {
    return {
      title: item?.title,
      path: `/bszx/pay/detail?id=${item?.articleId}`,
      imageUrl: item?.image,
    };
  });

  useShareAppMessage(() => {
    return {
      title: item?.title,
      path: `/bszx/pay/detail?id=${item?.articleId}`,
      imageUrl: item?.image,
      success: function (res) {
        console.log('分享成功', res);
      },
      fail: function (res) {
        console.log('分享失败', res);
      }
    };
  });

  useEffect(() => {
    reload();
  }, []);

  return (
    <>
      <Image src={item?.image} height={375}/>
      {/*linear-gradient(to bottom, #ffe0e0, #ffb6c1)*/}
      <div className={'pb-5 nr-bg'}>
        <div className={'p-3 font-bold text-lg'}>{item?.title}</div>
        <div className={'flex justify-between px-3'}>
          <Tag type={'success'}>{item?.categoryName}</Tag>
          <div className={'flex items-center gap-2 text-sm text-gray-500'}><Eye size={14}/>{views}</div>
        </div>
        <Divider/>
        {
          item?.model == 'bm' ? '' :
            <div>
              {
                !item?.endTime ? '' :
                  <>
                    <div className={'flex px-3 items-center gap-2'}>
                      <Clock size={14}/>
                      <div
                        className={'text-sm font-bold'}>{dayjs(item?.startTime).format('YYYY-MM-DD')} 至 {dayjs(item?.endTime).format('YYYY-MM-DD')}</div>
                    </div>
                    <Divider/>
                  </>
              }
              {
                !item?.price ? '' :
                  <>
                    <div className={'flex px-3 items-center gap-2'}>
                      <Purse size={14}/>
                      <div
                        className={'text-sm font-bold text-orange-500'}>{item?.price == 0 ? '线下收费' : '￥' + item?.price}
                      </div>
                    </div>
                    <Divider/>
                  </>
              }
              <div className={'flex px-3 items-center gap-2'}>
                <PickedUp size={14}/>
                <div
                  className={'text-sm font-bold'}>已捐款人数 {bmUsers}
                </div>
              </div>
            </div>
        }

        <Divider/>
        <div className={'flex px-3 items-center gap-2'}>
          <Coupon size={14}/>
          <div
            className={'text-sm font-bold'}>活动详情
          </div>
        </div>
        <View className={'content text-gray-700 text-sm relative content-bg'}>
          <RichText nodes={item?.content}/>
        </View>
        <Line height={44}/>
      </div>
      <AddCartBar/>
    </>
  )
}

export default Detail
