import { ComponentClass } from 'react';
import Taro, { Component, Config } from '@tarojs/taro';
import { View, Textarea, Button } from '@tarojs/components';
import { fetchFeedback } from '../../api/customer';
import { connect } from '@tarojs/redux';

import './Feedback.scss';
import { shareHandle } from '@/common/shareMethod';

type PageProps = {
  areaId: number;
  areaName: string;
  customerId: number;
  customerName: string;
  customerPhone: string;
};
type PageState = {
  feedbackContent: string;
};

interface Feedback {
  props: PageProps;
  state: PageState;
}
@connect(({ userinfo }) => ({
  areaId: userinfo.areaId,
  areaName: userinfo.areaName,
  customerId: userinfo.customerId,
  customerName: userinfo.customerName,
  customerPhone: userinfo.customerPhone,
}))
class Feedback extends Component<PageProps, PageState> {
  config: Config = {
    navigationBarTitleText: '意见反馈',
  };
  constructor(props) {
    super(props);
    this.state = {
      feedbackContent: '',
    };
  }
  onShareAppMessage = shareHandle;

  feedbackHandle() {
    Taro.showLoading();
    const { feedbackContent } = this.state;
    if (feedbackContent && feedbackContent.length >= 5) {
      const {
        areaId,
        areaName,
        customerId,
        customerName,
        customerPhone,
      } = this.props;
      fetchFeedback({
        areaId,
        areaName,
        customerId,
        customerName,
        customerPhone,
        feedbackContent,
      })
        .then(res => {
          Taro.hideLoading();
          console.log(res);
          Taro.showToast({
            title: '反馈成功',
            icon: 'success',
          });
          setTimeout(() => {
            Taro.navigateBack();
          }, 2000);
        })
        .catch(err => {
          Taro.hideLoading();
          console.log(err);
          Taro.showToast({
            title: '反馈失败',
            icon: 'none',
          });
        });
    } else {
      Taro.showToast({
        title: '请输入至少5个字',
        icon: 'none',
      });
    }
  }

  render() {
    return (
      <View className='Feedback'>
        <Textarea
          className='Feedback-input'
          value={this.state.feedbackContent}
          placeholder='反馈问题不超过50字'
          maxlength={50}
          onInput={({ detail: { value } }) => {
            this.setState({
              feedbackContent: value.trim(),
            });
            return value.trim();
          }}
        />
        <Button className='Feedback-btn' onClick={this.feedbackHandle}>
          提交
        </Button>
      </View>
    );
  }
}

export default Feedback as ComponentClass<PageProps, PageState>;
