import { useState, useEffect } from 'react';
import Taro from '@tarojs/taro';
import withLayout from '@/layout';
import {
  ScrollView,
  Image,
  RichText,
  View,
  Text,
  Input,
  Picker,
  Button
} from '@tarojs/components';
import Disclaimer from '@/components/Disclaimer';
import { useSelector } from 'react-redux';
import {
  signupActivity,
  queryActivityDetail,
} from "@/services/activity";
import { getImgURL } from "@/utils/image";
import { formatDate } from "@/utils/chatDate";
import useParams from "@/utils/hooks/useParams";
import useShare from "@/utils/hooks/useShare";
import useFavor from "@/utils/hooks/useFavor";
import { times } from "@/utils/tools";
import useStatus from './useStatus'
import CountDown from './CountDown'

import "./index.scss";

const activityStatusDict = {
  0: {
    text: '立即参与',
    text1: '立即参团',
    className: 'yellow',
  },
  1: {
    text: '未开始',
    text1: '未开始',
    className: 'blue',
  },
  2: {
    text: '已结束',
    text1: '已结束',
    className: 'grey',
  },
  3: {
    text: '已参与',
    text1: '已结束',
    className: 'yellow',
  },
};

export default withLayout((props) => {
  const { router, shareContent, trackData, person, page } = props;
  const { id } = router.params;

  const user = useSelector((state) => state.user);

  const [detail, setDetail] = useState({})
  const [canChoose, setCanChoose] = useState('none');
  const [inputName, setInputName] = useState('');
  const [selectorChecked, setSelectorChecked] = useState('1');
  const [selector, setSelector] = useState('');

  const buildingId = detail?.buildingId;

  const [btnText, btnDisabled] = useStatus(detail)

  const getDetail = (params) => {
    Taro.showLoading();

    queryActivityDetail(params).then((res) => {
      const maxperson = 10
      setSelector(times(maxperson).map((_, i) => `${i + 1}`));

      setDetail(res);
      Taro.hideLoading();
    });
  };

  // 本页面分享或者海报参数
  const paramsRef = useParams({
    id,
    buildingId,
    person,
    from: `${page.type}_share`,
  });

  const fullTrackData = { ...trackData, buildingId };

  const [isSaved, handleFavor] = useFavor(detail?.isSaved, {
    id,
    buildingId,
    ...trackData,
  });

  useShare(
    {
      title: shareContent.shareContentTitle || detail?.title,
      path: `${router.path}?${paramsRef.current}`,
      image: shareContent.shareContentImg || getImgURL(detail?.imgUrl),
    },
    fullTrackData
  );

  useEffect(() => {
    if (id) {
      getDetail(id);
    }
  }, [id])

  const handleSignup = () => {
    setCanChoose("block");
  };

  const comfire = () => {
    const { dynamicId } = detail
    const { userInfo: { person: { phone, tel } } } = user
    if (inputName === '') {
      Taro.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return
    }

    const payload = {
      buildingId,
      dynamicId,
      name: inputName,
      phone: phone ? phone : tel,
      attendNum: selectorChecked,
    };

    signupActivity(payload).then(() => {
      Taro.showToast({
        title: "报名成功",
      });
      setCanChoose('none')
      setTimeout(() => {
        getDetail(id)
      }, 500)
    });
  };

  function hideModal () {
    setCanChoose('none');
  }

  const onInputText = (e) => {
    setInputName(e.detail.value);
  };

  const dymic = () => (
    <view className='Info'>
      <view>
        <view className='Title flex-h'>
          <view className='flex-item'>
            <text>{detail.halfTitle}</text>
          </view>
          <text className='Tips'>{detail.enlisted || 0}人已报名</text>
        </view>
        <text className='Time'>
          报名截止时间：
          {formatDate(detail.enlistEnd, 'yyyy/M/d')}
        </text>
        <text className='Name'>{detail.title}</text>
        <view className='flex-h Address'>
          <text>地址：</text>
          <view className='flex-item'>
            <text>{detail.address}</text>
          </view>
        </view>
        <view className='flex-h Date'>
          <text>时间：</text>
          <view className='flex-item'>
            <text>
              {`${formatDate(detail.startDate, 'yyyy/M/d')} - ${formatDate(detail.endDate, 'yyyy/M/d')}`}
            </text>
          </view>
        </view>
        <view className='Btn'>
          <Button open-type='share'>
            <text>分享好友</text>
          </Button>
        </view>
      </view>
    </view>
  );

  const house = () => (

    <view className='BuildingInfo'>

      <view className='flex-h Title'>
        <view className='flex-item'>
          <text className='Name'>{detail.title}</text>
          <view className='Address flex-h'>
            <text className='iconfont icon-dingwei'></text>
            <view className='flex-item'>
              <text>{detail.address}</text>
            </view>
            <text className='Price'>价格待定</text>
          </view>
          <text className='Time'>时间：{formatDate(detail.startDate, 'yyyy/M/d')} - {formatDate(detail.endDate, 'yyyy/M/d')}</text>
        </view>
        <view className='Option'>
          <view>
            <text className='iconfont icon-fenxiang1'></text>
            <text>分享</text>
            <Button open-type='share' className='ShareBtn'>分享</Button>
          </view>
          <view>
            <text className='iconfont icon-pengyouquan1'></text>
            <text>朋友圈</text>
          </view>
        </view>
      </view>

      <CountDown endTime={detail?.enlistEnd} />

      <view className='Apply flex-h'>
        <view className='Collect' onClick={handleFavor}>
          <text className='iconfont icon-shoucang' style={isSaved ? { color: 'red' } : undefined}></text>
          <text>{isSaved ? '已收藏' : '收藏'}</text>
        </view>
        <text className='iconfont icon-baoming'></text>
        <view className='flex-item'>
          <text>{detail.enlisted || 0}人已报名</text>
        </view>
        <button className='Btn' disabled={btnDisabled} onClick={handleSignup}>{btnText}</button>
      </view>

    </view>
  );

  return (
    <>
      {detail && (
        <view className='Page activityDetail flex-v'>
          <view className='flex-item'>
            <view>
              <ScrollView scroll-y>
                <view className='PageContent'>
                  <view className='Top'>
                    <Image
                      mode='aspectFill'
                      src={getImgURL(detail.bannerListImg)}
                      className='centerLabel'
                    ></Image>
                  </view>

                  {detail.type == "dymic" && dymic()}
                  {detail.type !== "dymic" && house()}
                  <view className='ActivityIntro'>
                    <view className='Title'>
                      <text>活动介绍</text>
                    </view>
                    <RichText nodes={detail.desc} />
                  </view>

                  <Disclaimer />
                </view>
              </ScrollView>
            </view>
          </view>
          {detail.type == "dymic" && (
            <view className='PageBottom flex-h'>
              <Button className='Share' open-type='share'>
                <text className='iconfont icon-fenxiang'></text>
                <text>分享</text>
              </Button>
              <view className='Collect' onClick={handleFavor}>
                <text
                  className='iconfont icon-shoucang'
                  style={isSaved ? { color: "red" } : undefined}
                ></text>
                <text>{isSaved ? '已收藏' : '收藏'}</text>
              </view>
              <view className='flex-item'></view>

              <Button disabled={btnDisabled} className='Post' onClick={handleSignup}>
                {btnText}
              </Button>
            </view>
          )}
        </view>
      )}

      <View className='page-body' style={{ display: canChoose }}>
        <View className='mask' onClick={() => hideModal()}></View>
        <View className='page-section'>
          <Text className='page-section__title'>报名信息</Text>
          <View className='page-content'>
            <Input
              className='inputName'
              onInput={onInputText}
              type='text'
              placeholder='请输入姓名'
            />
            <Picker
              mode='selector'
              range={selector}
              onChange={(e) => setSelectorChecked(selector[e.detail.value])}
            >
              <View className='picker'>
                <Text>参加人数</Text>
                <Text className='content'>{selectorChecked}</Text>
                <Text>人</Text>
              </View>
            </Picker>
            <View onClick={comfire} className='comfire'>
              确认
            </View>
          </View>
        </View>
      </View>
    </>
  );
});
