/* eslint-disable prefer-destructuring */
/* eslint no-dupe-keys: 0, no-mixed-operators: 0 */
import React from 'react';
import { Tabs, Badge, SearchBar, ListView, Modal, List, Button } from 'antd-mobile-v2';
import 'antd-mobile-v2/dist/antd-mobile.css';
import styles from '.././mobile.less';
import commonConfig from '../../utils/config';
import * as commonServices from '../../services/services';
import * as commonUtils from '../../utils/utils';

// function MyBody(props) {
//   return (
//     <div className="am-list-body my-body">
//       <span style={{ display: 'none' }}>you can custom body wrap element</span>
//       {props.children}
//     </div>
//   );
// }


// const prompt = Modal.prompt;
const operation = Modal.operation;


const tabs = [
  { title: <Badge text="26">全部数据v</Badge> },
  { title: <Badge text="">筛选..</Badge> },
];


class DeviceMobile extends React.Component {
  constructor(props) {
    super(props);

    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row2,
    });

    this.state = {
      dataSource: dataSource.cloneWithRows({}),
      isLoading: true, // 判断是否正在加载中
      modal1: false,
      height: document.documentElement.clientHeight * 3 / 4,
      totalData: [],
      pageSize: 5,
      pageIndex: 1,
      hasMore: true, // 判断是否有更多
    };
  }
  async componentWillMount() {
    let { sModelType } = this.props;
    sModelType = commonUtils.isEmptyObject(sModelType) ? 'device' : sModelType;
    const { token } = this.props.app;
    const configUrl = `${commonConfig.server_host}mobilephone/getMenu/${sModelType}?sModelsId=100`;
    const configReturn = (await commonServices.getService(token, configUrl)).data;
    if (configReturn.code === 1) {
      const returnData = configReturn.dataset.rows[0];/* 全部数据 */
      if (commonUtils.isNotEmptyArr(returnData)) {
        const sModelsId = returnData.sId;
        const configUrl = `${commonConfig.server_host}business/getModelBysId/${sModelsId}?sModelsId=${sModelsId}`;
        const configReturn = (await commonServices.getService(token, configUrl)).data;
        if (configReturn.code === 1) {
          const [configData] = configReturn.dataset.rows;
          const masterConfig = configData.formData.filter(item => item.bGrd)[0];
          if (commonUtils.isNotEmptyArr(masterConfig)) {
            this.setState({ masterConfig, sModelsId });
          }
          const configDataId = masterConfig.sId;

          const dataUrl = `${commonConfig.server_host}business/getBusinessDataByFormcustomId/${configDataId}?sModelsId=${sModelsId}`;
          const dataReturn = (await commonServices.postValueService(token, { pageNum: this.state.pageIndex, pageSize: this.state.pageSize }, dataUrl)).data;
          if (configReturn.code === 1) {
            if (commonUtils.isNotEmptyArr(dataReturn.dataset.rows)) {
              const dT = dataReturn.dataset.rows;
              if (dT.length > 0) {
                this.setState({ totalData: dT[0].dataSet });
                this.getInitData();
              }
            }
          }
        }
      }
    }
  }
  // componentDidMount() {
  // }


  onEndReached = async (event) => {
    // load new data
    // hasMore: from backend data, indicates whether it is the last page, here is false
    if (this.state.isLoading && !this.state.hasMore) {
      return;
    }
    console.log('reach end', event);
    this.setState({ isLoading: true, hasMore: true });
    // var token=this.state.token;
    const { token } = this.props.app;
    let currpagedata = [];
    // var size=this.state.pageSize;
    // var status=this.state.status;
    const configDataId = this.state.masterConfig.sId;
    const dataUrl = `${commonConfig.server_host}business/getBusinessDataByFormcustomId/${configDataId}?sModelsId=${this.state.sModelsId}`;
    const dataReturn = (await commonServices.postValueService(token, { pageNum: this.state.pageIndex, pageSize: this.state.pageSize }, dataUrl)).data;
    console.log('===pageNum====', this.state.pageIndex);
    if (dataReturn.code === 1) {
      if (commonUtils.isNotEmptyArr(dataReturn.dataset.rows)) {
        const dT = dataReturn.dataset.rows;
        if (dT.length > 0) {
          currpagedata = dT[0].dataSet;
        }
      }
    }
    setTimeout(() => {
      const priortotalData = this.state.totalData; // 小于 pageIndex 的订单
      this.rData = priortotalData.concat(currpagedata);
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(this.rData),
        isLoading: false,
        pageIndex: this.state.pageIndex + 1,
        totalData: this.rData,
      });
    }, 1000);
  }
  onClose = key => () => {
    this.setState({
      [key]: false,
    });
  }

  getInitData=() => {
    this.setState({
      isLoading: true, hasMore: true, pageIndex: 1,
    });
    // const that = this;
    // 取第一页订单 作为初始
    // const page = 1;
    // const size = this.state.pageSize;
    // that.props.orderAction.getOrderList({
    //   token, status, page, size,
    // });
    const dT = this.state.totalData;
    if (dT.length > 0) {
      setTimeout(() => {
        this.rData = this.genData();
        this.setState({
          dataSource: this.state.dataSource.cloneWithRows(this.rData),
          isLoading: false,
          pageIndex: this.state.pageIndex + 1,
        });
      }, 600);
    }
  }
  genData() {
    const dataArr = [];
    let order = [];
    // const order = this.props.order.orderList;
    const dT = this.state.totalData;
    if (dT.length > 0) {
      order = dT;
      for (let i = 0; i < order.length; i += 1) {
        dataArr.push(order[i]);
      }
    }
    return dataArr;
  }


  render() {
    const { masterConfig } = this.state;
    if (masterConfig === undefined) {
      return (<div />);
    }

    const f1 = masterConfig.gdsconfigformslave.filter(item => item.bVisible)[0];
    const f2 = masterConfig.gdsconfigformslave.filter(item => item.bVisible)[1];
    const f3 = masterConfig.gdsconfigformslave.filter(item => item.bVisible)[2];
    const f4 = masterConfig.gdsconfigformslave.filter(item => item.bVisible)[3];
    const f5 = masterConfig.gdsconfigformslave.filter(item => item.bVisible)[4];
    const separator = (sectionID, rowID) => (
      <div
        key={`${sectionID}-${rowID}`}
        style={{
          backgroundColor: '#F5F5F9',
          height: 6,
          borderTop: '1px solid #ECECED',
          borderBottom: '1px solid #ECECED',
        }}
      />
    );
    const row = (rowData, sectionID, rowID) => {
      const obj = rowData;
      return (
        <div key={rowID} style={{ padding: '0 15px' }}>
          <div
            style={{
                lineHeight: '35px',
                color: '#888',
                fontSize: 16,
                fontWeight: 'bold',
                borderBottom: '1px solid #F6F6F6',
              }}
          > {f1.showName}:<span style={{ fontSize: 16, color: '#000', paddingLeft: '6px' }}>{obj[f1.sName]}</span>
            <span style={{ float: 'right', fontSize: 14, color: '#888' }}>{obj[f2.sName]}</span>
          </div>
          <div style={{ display: 'flex', padding: '10px 0' }}>
            <div style={{ lineHeight: 1, width: '100%' }}>
              <div style={{ marginBottom: '8px' }}>{f3.showName}:<span style={{ color: '#000', paddingLeft: '6px' }}>{obj[f3.sName]}</span></div>
              <div style={{ marginBottom: '8px' }}>{f4.showName}:<span style={{ color: '#000', paddingLeft: '6px' }}>{obj[f4.sName]}</span>
                <span style={{ float: 'right', fontSize: 14 }}>{f5.showName}:
                  <span style={{ fontSize: '14px', color: '#000' }} >{obj[f4.sName]}
                  </span>
                </span>
                {masterConfig.gdsconfigformslave.filter(item => item.bVisible).map((item, iIndex) => {
                  if (iIndex > 5) {
                    return (<div style={{ marginBottom: '8px' }}>item.showName：{obj[item.sName]}</div>);
                  } else {
                    return ('');
                  }
                })}
              </div>
            </div>
          </div>
        </div>
      );
    };
    return (

      <div>

        <SearchBar placeholder="工单号" />
        <Tabs
          tabs={tabs}
          initialPage={1}
          onChange={(tab, index) => { console.log('onChange', index, tab); }}
          onTabClick={(tab, index) => {
             if (index === 0) {
               operation([
                        { text: '全部单据', onPress: () => console.log('标为未读被点击了') },
                        { text: '已审核单据', onPress: () => console.log('置顶聊天被点击了') },
                        { text: '本月单据', onPress: () => console.log('置顶聊天被点击了') },
                      ]);
            } else {
                        this.setState({
                          modal1: true,
                        });
            }
}}
        >
          <div />
          <div />

        </Tabs>

        <ListView
          ref={(el) => { this.lv = el; }}
          dataSource={this.state.dataSource}
          // initialListSize={5} // 进入页面时记录数
          // renderHeader={() => <span>header</span>}
          renderFooter={() => (
            <div style={{ padding: 30, textAlign: 'center' }}>
              {this.state.isLoading ? 'Loading...' : 'Loaded'}
            </div>)}
          renderRow={row}
          renderSeparator={separator}
          style={{
         height: this.state.height,
         overflow: 'auto',
         }}
          pageSize={this.state.pageSize}
          onScroll={() => {}}
          scrollRenderAheadDistance={500}
          onEndReached={this.onEndReached}
          onEndReachedThreshold={10}
        />

        <Modal
          popup
          visible={this.state.modal1}
          onClose={this.onClose('modal1')}
          animationType="slide-down"
          className={styles.modal}
          // afterClose={() => { alert('afterClose'); }}
        >
          <List renderHeader={() => <div>筛选条件</div>} >
            {['股票名称', '股票代码', '买入价格'].map((i, index1) => (
              <List.Item key={index1.toString()}>{i}</List.Item>
            ))}
            <List.Item>
              <Button type="primary" onClick={this.onClose('modal1')}>确定</Button>
            </List.Item>
          </List>
        </Modal>
      </div>


    );
  }
}

export default DeviceMobile;
