import React, { Component } from 'react';
import { connect } from 'react-redux';
import DocumentTitle from 'react-document-title';
import 'antd-mobile/dist/antd-mobile.less';
import router from 'umi/router';
import styles from './index.less';
import { Tabs, ListView, PullToRefresh, Button, Toast, Icon } from 'antd-mobile';
import { getCardTypeCZ, getMemberTypeCZ } from '../common/common';

import * as Service from '../services/index';

import maledogbg from '../assets/index/maledogbg.png';
import femaledogbg from '../assets/index/femaledogbg.png';

import femaledogicon from '../assets/index/femaledogicon.png';
import maledogicon from '../assets/index/maledogicon.png';

import dogchipBg from '../assets/index/dogchipBg.png';

@connect(({ indexModel }) => ({ indexModel }))
class Index extends Component {
  timeout = null;
  constructor(props) {
    super(props);
    this.state = {
      isScrolling: false,
    };
  }
  componentWillMount = () => {
    let selectedTab = sessionStorage.getItem('indexSelectedTab');
    if (selectedTab) {
      this.props.dispatch({
        type: 'indexModel/updateState',
        payload: {
          selectedTab,
        },
      });
    } else {
      selectedTab = this.props.indexModel.selectedTab;
    }
    if (selectedTab === 't1') {
      this.getTransferList(1);
    } else {
      this.getNewdogchipList(1);
    }
    //获取用户信息
    this.getUserInfo();
  };
  componentDidMount = () => {
    window.addEventListener('scroll', this.onScroll);
  };

  componentWillUnmount = () => {
    this.props.dispatch({
      type: 'indexModel/updateStateFun',
      payload: {
        isLoading: false,
      },
    });
    clearTimeout(this.timeout);
    this.timeout = null;
  };

  //获取用户信息
  getUserInfo = async () => {
    let ckuUserVoStr = window.sessionStorage.getItem('access-user');

    let ckuUserVo = '';
    if (ckuUserVoStr) {
      ckuUserVo = JSON.parse(window.sessionStorage.getItem('access-user'));
    }

    if (ckuUserVo && ckuUserVo.code) {
      this.props.dispatch({
        type: 'indexModel/updateState',
        payload: {
          userInfo: ckuUserVo || {},
        },
      });
    } else {
      const { rc, data } = await Service.info();
      if (!rc) {
        ckuUserVo = data ? data : null;
        this.props.dispatch({
          type: 'indexModel/updateState',
          payload: {
            userInfo: ckuUserVo || {},
            token: data.token,
          },
        });
        //存储用户信息
        window.sessionStorage.setItem(
          'access-user',
          ckuUserVo ? JSON.stringify(ckuUserVo) : JSON.stringify({}),
        );
      }
    }
  };

  //切换账号
  changeAccount = () => {
    router.push('/ckuh5/mobileCode?need=noOpenId');
  };
  //申请血统证书
  tockuApply = birthCode => {
    router.push(`/ckuh5/ckuApply?birthCode=${birthCode}`);
  };
  //宠物身份电子登记卡
  toRegistrationCard = id => {
    router.push(`/ckuh5/registrationCard?id=${id}`);
  };
  //登记卡注册
  toTransfer = () => {
    router.push('/ckuh5/transfer');
  };
  //电子版血统证书
  toCertificate = dogId => {
    router.push(`/ckuh5/ckuCertificate?id=${dogId}`);
  };
  //立即续费
  renew = async () => {
    this.props.dispatch({
      type: 'indexModel/updateState',
      payload: {
        renewLoading: true,
      },
    });
    const { rc, msg, data } = await Service.renewal();
    if (!rc) {
      window.sessionStorage.setItem('newUser', false);
      this.savePayInfo({
        title: 'CKU',
        detail: `续费业务`,
        orderId: data.orderId,
        orderAmount: data.orderAmount,
      });
      this.props.dispatch({
        type: 'indexModel/updateState',
        payload: {
          renewLoading: false,
        },
      });
      router.push('/ckuh5/pay');
    } else {
      Toast.info(`${msg}`, 2);
      this.props.dispatch({
        type: 'indexModel/updateState',
        payload: {
          renewLoading: false,
        },
      });
    }
  };

  //savePayInfo
  savePayInfo = ({ orderId, orderAmount }) => {
    var obj = {};
    obj.orderId = orderId;
    obj.orderAmount = orderAmount;

    const { userInfo } = this.props.indexModel;

    obj.title = userInfo && userInfo.memberType ? `CKU${getMemberTypeCZ(userInfo.memberType)}` : '';
    obj.detail =
      userInfo && (userInfo.cardType || userInfo.cardType === 0)
        ? `${getCardTypeCZ(userInfo.cardType)}会员`
        : '';

    window.sessionStorage.setItem('payInfo', JSON.stringify(obj));
  };

  //升级
  upgrade = () => {
    window.sessionStorage.setItem('newUser', false);
    router.push(`/ckuh5/memberType?type=upgrade`);
  };

  //血统证书付款
  savePayInfoDogChip = ({ orderId, price, businessName }) => {
    var obj = {};
    obj.orderId = orderId;
    obj.orderAmount = price;

    obj.title = '血统证书';
    obj.detail = businessName;
    window.sessionStorage.setItem('newUser', false);
    window.sessionStorage.setItem('payInfo', JSON.stringify(obj));
    router.push('/ckuh5/pay');
  };

  onScroll = () => {
    this.setState({
      isScrolling: true,
    });
    clearTimeout(this.timeout);

    this.timeout = setTimeout(() => {
      this.setState({
        isScrolling: false,
      });
    }, 200);
  };
  getTransferList = pageNum => {
    this.props.dispatch({
      type: 'indexModel/getTransferList',
      payload: {
        pageNo: pageNum,
        pageSize: 10,
        source: 2,
      },
    });
  };
  getNewdogchipList = pageNum => {
    this.props.dispatch({
      type: 'indexModel/getNewdogchipList',
      payload: {
        pageNo: pageNum,
        pageSize: 10,
      },
    });
  };
  onRefresh = () => {
    const { selectedTab } = this.props.indexModel;
    if (selectedTab === 't1') {
      this.getTransferList(1);
    } else {
      this.getNewdogchipList(1);
    }
  };

  onEndReached = () => {
    const { selectedTab, pageNum } = this.props.indexModel;
    if (selectedTab === 't1') {
      this.getTransferList(pageNum + 1);
    } else {
      this.getNewdogchipList(pageNum + 1);
    }
  };

  //显示续费按钮
  renderRenew = () => {
    const { userInfo, renewLoading } = this.props.indexModel;
    if (renewLoading) {
      return (
        <Button size="small" className={styles.index_head_right_button}>
          <Icon type={'loading'} size={'xs'} />
        </Button>
      );
    } else if (userInfo.cardType) {
      return (
        <Button size="small" className={styles.index_head_right_button} onClick={this.renew}>
          立即续费
        </Button>
      );
    }
  };

  //显示升级按钮
  renderUpgrade = () => {
    const { userInfo } = this.props.indexModel;
    if (userInfo.cardType !== 40) {
      return (
        <div className={styles.index_button}>
          <Button className={styles.index_top_button} size="small" onClick={this.upgrade}>
            升级
          </Button>
        </div>
      );
    } else {
      return <div></div>;
    }
  };

  render() {
    const tabsObj = [{ title: '身份识别登记卡', key: 't1' }, { title: '血统证书', key: 't2' }];
    const row = (rowData, sectionID, rowID) => {
      return (
        <div className={styles.index_content_item}>
          <div className={styles.first_col}>
            <span>No.{rowData.birthCerRegCode}</span>
          </div>
          <div className={styles.second_col}>
            <div className={styles.second_col_left}>
              <img src={rowData.dogGender === '1' ? maledogbg : femaledogbg} alt="" />
            </div>
            <div className={styles.second_col_right}>
              <p className={styles.dog_name}>
                <img src={rowData.dogGender === '1' ? maledogicon : femaledogicon} alt="" />
                {rowData.dogName}
              </p>
              <p className={styles.dog_color}>
                {rowData.colorFlag} ; {rowData.dogBreed}
              </p>
              <p className={styles.dog_birth}>出生日期：{rowData.dogBirthday}</p>
              <p className={styles.dog_birth}>繁殖人:{rowData.breeder}</p>
              <p className={styles.dog_birth}>血统证书号:{rowData.pedigreeCertified}</p>
            </div>
          </div>
          <div className={styles.third_col}>
            <Button
              className={styles.third_col_btn1}
              size="small"
              onClick={() => this.toRegistrationCard(rowData.id)}
            >
              详情
            </Button>
            {rowData.canApplyPedigreeCertifiedFlag === '1' && (
              <Button
                className={styles.third_col_btn2}
                size="small"
                onClick={() => {
                  this.tockuApply(rowData.birthCerRegCode);
                }}
              >
                血统证书申请
              </Button>
            )}
          </div>
        </div>
      );
    };
    const row2 = (rowData, sectionID, rowID) => {
      return (
        <div className={styles.index_content_item}>
          <div className={styles.first_col}>
            <span>血统证书号.{rowData.pedigreeCertified}</span>
            <span className={styles.endTime}>{rowData.createDate}</span>
          </div>
          <div className={styles.second_col}>
            <div className={styles.second_col_left}>
              <img src={dogchipBg} alt="" />
            </div>
            <div className={styles.second_col_right}>
              <p className={styles.dog_name}>
                <img src={rowData.dogGender === '公' ? maledogicon : femaledogicon} alt="" />
                {rowData.callName === '' ? rowData.dogEnName : rowData.callName}
              </p>
              <p className={styles.dog_color}></p>
              <p className={styles.dog_birth}>出生日期：{rowData.dogBirthday}</p>
              <p className={styles.dog_birth}>犬主人:{rowData.tempUserName}</p>
              <p className={styles.dog_birth}>登记卡编号:{rowData.birthCode}</p>
            </div>
          </div>
          <div className={styles.third_col}>
            {rowData.pedigreeCertified && (
              <Button
                className={styles.third_col_btn1}
                size="small"
                onClick={() => this.toCertificate(rowData.dogId)}
              >
                查看证书
              </Button>
            )}

            {rowData.paymentState === '1' && (
              <Button
                className={styles.third_col_btn2}
                size="small"
                onClick={this.savePayInfoDogChip.bind(this, rowData)}
              >
                立即付款
              </Button>
            )}
          </div>
        </div>
      );
    };

    const { userInfo, selectedTab, refreshing } = this.props.indexModel;
    const { isScrolling } = this.state;
    return (
      <DocumentTitle title="会员中心">
        <div className={styles.index_container}>
          <div className={styles.index_top}>
            <div
              className={`${styles.index_head} ${
                userInfo.cardType === 0
                  ? styles.index_head1
                  : userInfo.cardType === 10
                  ? styles.index_head2
                  : userInfo.cardType === 20
                  ? styles.index_head3
                  : userInfo.cardType === 30
                  ? styles.index_head4
                  : userInfo.cardType === 40
                  ? styles.index_head5
                  : null
              }`}
            >
              <div className={styles.index_head_top}>
                <div className={styles.index_head_left}>
                  <p className={styles.index_head_left_p}>
                    <span className={styles.index_head_left_name}>{userInfo.memberName}</span> |{' '}
                    <span className={styles.index_head_left_a} onClick={this.changeAccount}>
                      切换账号>
                    </span>
                  </p>
                  <p className={styles.index_head_left_endtime}>{userInfo.memberEndDate}到期</p>
                </div>
                <div className={styles.index_head_right}>{this.renderRenew()}</div>
              </div>

              <div
                className={`${styles.index_top_img} ${
                  userInfo.cardType === 0
                    ? styles.index_top_img1
                    : userInfo.cardType === 10
                    ? styles.index_top_img2
                    : userInfo.cardType === 20
                    ? styles.index_top_img3
                    : userInfo.cardType === 30
                    ? styles.index_top_img4
                    : userInfo.cardType === 40
                    ? styles.index_top_img5
                    : null
                }`}
              >
                <div className={styles.index_membercode}>
                  <p>NO.{userInfo.memberCode}</p>
                </div>
                {/* <div className={styles.index_button}>
                  <Button className={styles.index_top_button} size="small">
                    升级
                  </Button>
                </div> */}
                {this.renderUpgrade()}
              </div>
            </div>
          </div>
          <div className={styles.index_content}>
            <div className={styles.index_content_tab}>
              <Tabs
                tabs={tabsObj}
                page={selectedTab}
                swipeable={false}
                tabBarActiveTextColor="#2e2e2e"
                tabBarInactiveTextColor="#a8a8a8"
                onChange={(tab, index) => {
                  this.props.dispatch({
                    type: 'indexModel/updateState',
                    payload: {
                      selectedTab: tab.key,
                    },
                  });
                  sessionStorage.setItem('indexSelectedTab', tab.key);
                  if (tab.key === 't1') {
                    this.getTransferList(1);
                  } else {
                    this.getNewdogchipList(1);
                  }
                }}
              >
                <ListView
                  key="t1"
                  dataSource={this.props.indexModel.scoreList}
                  renderFooter={() => (
                    <div
                      style={{
                        padding: '0.1rem',
                        justifyContent: 'center',
                        alignItems: 'center',
                      }}
                    >
                      {this.props.indexModel.isLoading ? '加载中...' : '暂无数据'}
                    </div>
                  )}
                  renderRow={row}
                  style={{
                    padding: '0 .3rem',
                    boxSizing: 'border-box',
                    background: 'rgba(247,247,247,1)',
                  }}
                  pageSize={4}
                  scrollRenderAheadDistance={500}
                  onEndReached={this.onEndReached}
                  onEndReachedThreshold={10}
                  useBodyScroll={true}
                  pullToRefresh={
                    <PullToRefresh refreshing={refreshing} onRefresh={this.onRefresh} />
                  }
                />
                <ListView
                  key="t2"
                  dataSource={this.props.indexModel.scoreList2}
                  renderFooter={() => (
                    <div
                      style={{
                        padding: '0.1rem',
                        justifyContent: 'center',
                        alignItems: 'center',
                      }}
                    >
                      {this.props.indexModel.isLoading ? '加载中...' : '暂无数据'}
                    </div>
                  )}
                  renderRow={row2}
                  style={{
                    padding: '0 .3rem',
                    boxSizing: 'border-box',
                    background: 'rgba(247,247,247,1)',
                  }}
                  pageSize={4}
                  scrollRenderAheadDistance={500}
                  onEndReached={this.onEndReached}
                  onEndReachedThreshold={10}
                  useBodyScroll={true}
                  pullToRefresh={
                    <PullToRefresh refreshing={refreshing} onRefresh={this.onRefresh} />
                  }
                />
              </Tabs>
            </div>
            {selectedTab === 't1' && !isScrolling ? (
              <div className={styles.fixedButtonWrap}>
                <Button className={styles.fixedButton} onClick={this.toTransfer}>
                  身份登记卡登记
                </Button>
              </div>
            ) : null}
          </div>
        </div>
      </DocumentTitle>
    );
  }
}

export default Index;
