import Taro, {
  useState,
  useEffect,
  useShareAppMessage,
  clientRectElement,
} from '@tarojs/taro';
import { View, Button, Input, ScrollView } from '@tarojs/components';
import { useSelector } from '@tarojs/redux';

import './Feedback.scss';
import { shareHandle } from '@/common/shareMethod';
import useInputValue from '@/hooks/useInputValue';
import { Customer } from '@/types/Customer/Customer';
import useFeedbackList from './useFeedbackList';
import { addFeedback } from '@/api/feedback';
import useButtonPadding from '@/hooks/useButtonPadding';
import FeedbackItem from './components/FeedbackItem/FeedbackItem';
import { formatDate } from '@/utils/time';
import useSystemInfo from '@/hooks/useSystemInfo';
import { compareVersion } from '@/utils/version';

function Feedback() {
  useShareAppMessage(shareHandle);
  const { value, onChange } = useInputValue('');
  const userInfo = useSelector((state: any): Customer => state.userinfo);
  const { list, fetchListHandle, pushNewMsg } = useFeedbackList(
    userInfo.customerId,
  );
  const bottomHeight = useButtonPadding();
  const [showKeyboard, setShowKeyboard] = useState(false);
  const addFeedbackHandle = () => {
    Taro.showLoading();
    if (value) {
      addFeedback({
        content: value,
        customerId: userInfo.customerId,
      })
        .then(res => {
          Taro.hideLoading();
          console.log(res);
          onChange({
            type: '',
            detail: { value: '', cursor: 0, keyCode: 0 },
            timeStamp: 0,
            target: this,
            currentTarget: this,
            preventDefault: () => {},
            stopPropagation: () => {},
          });
          pushNewMsg({
            id: 0,
            content: value,
            createDate: formatDate(new Date()),
            replayList: [],
          });
        })
        .catch(err => {
          Taro.hideLoading();
          console.log(err);
          Taro.showToast({
            title: '反馈失败',
            icon: 'none',
          });
        });
    } else {
      Taro.showToast({
        title: '请输入至少5个字',
        icon: 'none',
      });
    }
  };
  const [scrollTop, setScrollTop] = useState(0);
  const systemInfo = useSystemInfo();

  useEffect(() => {
    if (compareVersion(systemInfo.SDKVersion, '2.7.0')) {
      wx.onKeyboardHeightChange(res => {
        console.log(res.height);
        if (res.height) {
          setShowKeyboard(true);
        } else {
          setShowKeyboard(false);
        }
      });
    } else {
      console.log('in focus');
    }
  }, []);
  useEffect(() => {
    Taro.createSelectorQuery()
      .select('.Feedback-Content')
      .boundingClientRect((rect: clientRectElement) => {
        console.log(rect);
        if (rect) setScrollTop(rect.height);
      })
      .exec();
  }, [list.length]);
  const scrollToUpperHandle = () => {
    if (list.length) {
      fetchListHandle(list[0].id);
    }
  };
  return (
    <View
      className='Feedback'
      style={`padding-bottom: ${Taro.pxTransform(112 + bottomHeight)}`}>
      <ScrollView
        className='Feedback-Content-wrap'
        scrollY
        scrollWithAnimation
        upperThreshold={-40}
        onScrollToUpper={scrollToUpperHandle}
        scrollTop={scrollTop}>
        <View className='Feedback-Content'>
          {list.map(item => (
            <FeedbackItem
              key={item.id}
              msgData={item}
              userData={{
                customerHead: userInfo.customerHead,
                customerSex: userInfo.customerSex,
              }}
            />
          ))}
        </View>
      </ScrollView>
      <View
        className='Feedback-Footer'
        style={`bottom: ${Taro.pxTransform(bottomHeight)}`}>
        <Input
          className='Feedback-Footer-Input'
          value={value}
          onInput={onChange}
          placeholder='反馈问题不超过50字'
          maxLength={50}
          confirmType='send'
          onConfirm={addFeedbackHandle}
        />
        {!showKeyboard && (
          <Button className='Feedback-Footer-Btn' onClick={addFeedbackHandle}>
            发送
          </Button>
        )}
      </View>
    </View>
  );
}

Feedback.config = {
  navigationBarTitleText: '意见反馈',
};

export default Feedback;
