import { View } from '@tarojs/components';
import { Component, ReactNode } from 'react';
import Taro from '@tarojs/taro';
import {
  AtCard,
  AtInputNumber,
  AtButton,
  AtList,
  AtListItem,
  AtActivityIndicator,
  AtToast,
} from 'taro-ui';
import clockIcon from '@/assets/icons/MainPage/clock.svg';
import type CustomTabBar from '@/custom-tab-bar';
import PageFooter from '@/components/PageFooter/PageFooter';
import pt from '@/plain-text';
import { getDutyInfo } from '@/service/dutyInfo';
import { RequestState } from '@/service';
import moment from 'moment';
import wechatUser from '@/wechat';
import { getMemberDutyInfo } from '@/service/memberDutyInfo';
import { getUncompletedTicketList } from '@/service/uncompletedTicket';
import { changeDutyCnt } from '@/service/changeDutyCount';
import { TicketListItem } from '@/components/TicketListItem/TicketListItem';
import { ExpandItem } from '@/components/ExpandItem/ExpandItem';
import './index.scss';
import TitleCard from './TitleCard';
import { DutyInfo, DutyData } from './DutyInfo';
import { StepInfo, TipsInfo } from './StepTipsInfo';

const submitInterval = 5000;

class CardContent {
  title: string;
  note: string;
  extra: JSX.Element | string;
  content: () => JSX.Element;
}

function mainPageCard(c: CardContent): JSX.Element {
  return (
    <View style={{ marginTop: '20rpx', marginBottom: '40rpx' }}>
      <AtCard note={c.note} extra={c.extra} title={c.title}>
        {c.content()}
      </AtCard>
    </View>
  );
}

interface MainPageState {
  fixList: Array<TicketListItem>;
  rs: RequestState;
  dutyData: DutyData;
  dutyInfoCard: CardContent;
  stepInfoCard: CardContent;
  tipsInfoCard: CardContent;
  isLoading: boolean;
  isDisable: boolean;
}

export default class MainPage extends Component<{}, MainPageState> {
  state = {
    dutyData: new DutyData(),
    dutyInfoCard: {
      title: '',
      note: '',
      extra: '',
      content: () => <></>,
    },
    stepInfoCard: {
      title: '',
      note: '',
      extra: '',
      content: () => <></>,
    },
    tipsInfoCard: {
      title: '',
      note: '',
      extra: '',
      content: () => <></>,
    },
    fixList: [new TicketListItem(0, '', '', 1, moment())],
    rs: new RequestState(),
    isLoading: false,
    isDisable: false,
  };

  componentDidMount(): void {
    const ptPage = wechatUser.getAccess() ? 'memberPage' : 'mainPage';
    this.setState({
      dutyData: new DutyData(),
      dutyInfoCard: {
        title: pt.get()[ptPage].cardTitle.dutyInfo,
        note: pt.get()[ptPage].cardTips.dutyInfo,
        extra: pt.get()[ptPage].extraInfo.dutyInfo,
        content: () => <DutyInfo data={this.state.dutyData} />,
      },
      stepInfoCard: {
        title: pt.get()[ptPage].cardTitle.stepInfo,
        note: pt.get()[ptPage].cardTips.stepInfo,
        extra: pt.get()[ptPage].extraInfo.dutyInfo,
        content: () => <StepInfo />,
      },
      tipsInfoCard: {
        title: pt.get()[ptPage].cardTitle.tipsInfo,
        note: pt.get()[ptPage].cardTips.tipsInfo,
        extra: pt.get()[ptPage].extraInfo.dutyInfo,
        content: () => <TipsInfo />,
      },
    });

    if (wechatUser.getAccess()) {
      getMemberDutyInfo(this);
      getUncompletedTicketList(this);
    } else {
      getDutyInfo(this);
    }
  }

  // 以下是TabBar相关
  pageCtx = Taro.getCurrentInstance().page;
  componentDidShow() {
    const tabbar = Taro.getTabBar<CustomTabBar>(this.pageCtx);
    tabbar?.setSelected(0);
  }
  // 以上是TabBar相关

  handleCnt(inDutyCnt: number) {
    this.setState({
      dutyData: {
        ...this.state.dutyData,
        inDutyCnt: inDutyCnt,
      },
    });
    return inDutyCnt;
  }

  onChangeCnt() {
    this.setState({
      isDisable: true,
    });
    changeDutyCnt(this);
    setTimeout(() => {
      this.setState({
        isDisable: false,
      });
    }, submitInterval);
  }

  ticketListPage() {
    Taro.navigateTo({
      url: '/pages/TicketList/TicketList',
    });
  }

  conclusionPage() {
    Taro.navigateTo({
      url: '/pages/Conclusion/Conclusion',
    });
  }

  render(): ReactNode {
    const mainPage = pt.get().mainPage;
    const memberPage = pt.get().memberPage;
    if (this.state.rs.loading) {
      return (
        <AtActivityIndicator
          mode='center'
          content={pt.get().actIndicator.loading}
        ></AtActivityIndicator>
      );
    }
    if (!this.state.rs.success) {
      return (
        <AtToast
          isOpened
          text={pt.get().toast.error}
          icon='close-circle'
        ></AtToast>
      );
    }
    const fixListRenderer = this.state.fixList.map((item) => item.render());
    return (
      <View>
        <TitleCard />
        <View style={{ width: '94%', marginLeft: '3%' }}>
          <View style={{ marginTop: '60rpx' }}>
            {mainPageCard(this.state.dutyInfoCard)}
            {mainPageCard(this.state.tipsInfoCard)}
            {wechatUser.getAccess() && this.state.dutyData.isInDuty ? (
              <ExpandItem
                title={memberPage.expandTitle.admin}
                content={
                  <View style={{ marginBottom: '40rpx' }}>
                    <View
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        marginBottom: '40rpx',
                      }}
                    >
                      <View
                        className='.at-article__h3'
                        style={{
                          marginTop: '40rpx',
                        }}
                      >
                        {pt.get().memberPage.dutyCount.text}
                      </View>
                      <View
                        style={{
                          marginTop: '40rpx',
                        }}
                      >
                        <AtInputNumber
                          type='number'
                          min={0}
                          max={10}
                          step={1}
                          value={this.state.dutyData.inDutyCnt}
                          onChange={this.handleCnt.bind(this)}
                        />
                      </View>
                      <View style={{ marginLeft: 'auto', marginTop: '40rpx' }}>
                        <AtButton
                          type='secondary'
                          size='small'
                          loading={this.state.isLoading}
                          disabled={this.state.isDisable}
                          onClick={this.onChangeCnt.bind(this)}
                        >
                          {pt.get().memberPage.dutyCount.button}
                        </AtButton>
                      </View>
                    </View>
                    <View>
                      <AtButton type='primary' onClick={this.conclusionPage}>
                        {pt.get().button.indexText.conclusion}
                      </AtButton>
                    </View>
                  </View>
                }
              />
            ) : (
              <View></View>
            )}
            <ExpandItem
              title={mainPage.expandTitle.stepInfo}
              content={mainPageCard(this.state.stepInfoCard)}
            />
          </View>
          {wechatUser.getAccess() ? (
            <View style={{ marginTop: '40rpx' }}>
              <View
                className='at-article__h3'
                style={{ marginBottom: '20rpx', fontWeight: 'bold' }}
              >
                {(this.state.fixList.length === 0
                  ? memberPage.ticketList.nohint
                  : '') + memberPage.ticketList.hint}
              </View>
              <AtList>{fixListRenderer}</AtList>
              <AtList>
                <AtListItem
                  title={pt.get().memberPage.ticketList.title}
                  note={pt.get().memberPage.ticketList.note}
                  arrow='right'
                  thumb={clockIcon}
                  onClick={this.ticketListPage}
                />
              </AtList>
            </View>
          ) : (
            <View></View>
          )}
          <PageFooter />
        </View>
      </View>
    );
  }
}
