/* eslint-disable */
/* eslint-disable prefer-destructuring */
/* eslint no-dupe-keys: 0, no-mixed-operators: 0 */
import React from 'react';
import { ListView, Checkbox, Modal, Toast, Flex } from 'antd-mobile-v2';
import { createForm } from 'rc-form';
import 'antd-mobile-v2/dist/antd-mobile.css';
import commonConfig from '../../../utils/config';
import * as commonUtils from '../../../utils/utils';
import CommobileBase from '../../../mobile/common/CommobileBase';
import CommobileListEvent from '../CommobileListEvent';
import CommobileSearchComponent from '../CommobileSearchComponent';
import CommobileToolBar from '../CommobileToolBar';
import CommonbileStep from '../CommobileStep';
import StaticEditTable from "@/components/Common/CommonTable"; /* 可编辑表格 */
import SearchComponent from "@/components/Common/SearchComponent";
import * as commonBusiness from "@/components/Common/commonBusiness"; /* 单据业务功能 */
import * as commonFunc from "@/components/Common/commonFunc";
import styles from '../../mobile.less';
import stylesNew from './index.less';
import preView from '../../components/preView';
import { useEffect } from 'react';

const CheckboxItem = Checkbox.CheckboxItem;
const AgreeItem = Checkbox.AgreeItem;

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

class CommobileList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: false,
      partNameStatusVisible: false, /* 查看进度 */
      sSlaveId: '',
    };
  }

  onEndReached = async () => {
    if ((this.props.slavePagination.current + 1) <= Math.ceil(this.props.slavePagination.total / commonConfig.pageSize)) {
      const { slaveFilterCondition } = this.props;
      const addState = await this.props.onGetData(this.props.slaveConfig, slaveFilterCondition, this.props.slavePagination.current + 1, true);
      addState.slaveData = this.props.slaveData.concat(addState.slaveData);
      this.props.onSaveState({ ...addState });
    }
  }
  onClose = key => () => {
    this.setState({
      [key]: false,
    });
  }
  onModalShow = key => () => {
    this.setState({
      [key]: true,
    });
  }
  handlePartNameStatusLook = (sSlaveId) => {
    if (commonUtils.isNotEmptyObject(sSlaveId)) {
      this.setState({
        partNameStatusVisible: true,
        sSlaveId,
      });
    } else {
      Toast.fail('请选择要查看的工单', 1);
    }
  }
  /* 列表弹出详情 */
  handleDoubleClick = (rowData) => {
    this.props.onDoubleClick(rowData);
  }

  padTitles = (titles) => {
    return titles.padEnd(4, ' ') + '：';
  }
  // topHeight = (value) => {
  //   let subHeight = 0;
  //   if ( value % 2 === 0 ) {
  //     subHeight = ( value / 2 ) * 22;
  //   } else {
  //     subHeight = (Math.floor(value / 2) + 1) * 22;
  //   }
  //   return subHeight;
  // }

  render() {
    return (
      <>
        <div style={{ display: 'none' }}><CommobileSearchComponent {...this.props} showScan="true" /></div>
        <CommobilePadListComponent {...this.props} />
      </>
    );

    const {
      slaveConfig, slaveData: slaveDataOld, slaveTotal, slaveSelectedRowKeys: slaveSelectedRowKeysOld, onReturnForm,
    } = this.props;
    const slaveDataOld2 = slaveDataOld === undefined ? [] : slaveDataOld;
    const slaveData = dataSource.cloneWithRows(slaveDataOld2);
    const slaveSelectedRowKeys = slaveSelectedRowKeysOld === undefined ? [] : slaveSelectedRowKeysOld;
    const f1 = commonUtils.isEmptyObject(slaveConfig) ? {} : slaveConfig.gdsconfigformslave.filter(item => item.bVisible && item.sName !== '')[0];
    const f2 = commonUtils.isEmptyObject(slaveConfig) ? {} : slaveConfig.gdsconfigformslave.filter(item => item.bVisible && item.sName !== '')[1];
    const f3 = commonUtils.isEmptyObject(slaveConfig) ? {} : slaveConfig.gdsconfigformslave.filter(item => item.bVisible && item.sName !== '')[2];
    const f4 = commonUtils.isEmptyObject(slaveConfig) ? {} : slaveConfig.gdsconfigformslave.filter(item => item.bVisible && item.sName !== '')[3];
    const f5 = commonUtils.isEmptyObject(slaveConfig) ? {} : slaveConfig.gdsconfigformslave.filter(item => item.bVisible && item.sName !== '')[4];
    const f6 = commonUtils.isEmptyObject(slaveConfig) ? {} : slaveConfig.gdsconfigformslave.filter(item => item.sControlName === 'printPdf')[0];
    const f7 = commonUtils.isEmptyObject(slaveConfig) ? {} : slaveConfig.gdsconfigformslave.filter(item => item.bVisible && item.sName === 'sPartNameStatus')[0]; /* 查看进度 */
    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 = JSON.parse(JSON.stringify(rowData)); // 深拷贝
      if (commonUtils.isNotEmptyObject(f7)) {
        // eslint-disable-next-line jsx-a11y/anchor-is-valid
        obj[f7.sName] = (<span style={{ fontWeight: 'bold', fontSize: 14, color: '#888' }}><a onClick={this.handlePartNameStatusLook.bind(this, rowData.sSlaveId)}>查看工单状态</a></span>);
      }
      const f1View = f1 ?
        (
          <div
            key={rowData.sSlaveId}
            style={{
              padding: '0 15px',
              marginRight: 0,
              lineHeight: '30px',
              color: '#888',
              fontSize: 16,
              fontWeight: 'bold',
              borderBottom: '1px solid #F6F6F6',
            }}
          >
            {f1.showName}:<span style={{ fontSize: 16, color: '#000', paddingLeft: '6px' }}>{obj[f1.sName]}</span>
            {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
            <span style={{ float: 'right', fontSize: 14, color: '#888' }}>{obj[f2.sName]}</span>
          </div>
        ) : '';

      return (
        <div className={styles.CheckboxItem}>

          {/* eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
           onClick={() => this.props.onCopyToClick(rowData)} */}
          {/* eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions */}
          <li key={rowID} style={{ listStyle: 'none' }} onDoubleClick={() => this.handleDoubleClick(rowData)} >
            {
              true ?
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <CheckboxItem
                    key={rowData.sSlaveId}
                    checked={slaveSelectedRowKeys.findIndex(item => item === rowData.sSlaveId) > -1}
                    onChange={e => this.props.onCheckboxChange(e, rowData.sSlaveId)}
                    style={{
                      width: f6 ? '76%' : '100%',
                      marginRight: 0,
                      lineHeight: '30px',
                      color: '#888',
                      fontSize: 16,
                      fontWeight: 'bold',
                      borderBottom: '1px solid #F6F6F6',
                    }}
                  >

                    {f1 ? `${f1.showName}:` : ''}<span style={{ fontSize: 16, color: '#000', paddingLeft: '6px' }}>{obj[f1.sName]}</span>
                    {f6 ? '' : f2 ? <span style={{ float: 'right', fontSize: 14, color: '#888' }}>{obj[f2.sName]}</span> : ''}
                  </CheckboxItem>
                  {
                    // eslint-disable-next-line jsx-a11y/anchor-is-valid
                    f6 ?
                      <div
                        style={{
                          borderBottom: '1px solid #F6F6F6',
                          fontSize: 14,
                          lineHeight: '40px',
                          fontWeight: 'bold',
                          paddingRight: '15px',
                        }}
                      >
                        {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
                        <a onClick={e => this.props.onPrintView(e, rowData, f6)}>{obj[f6.sName]}</a>
                      </div> : ''
                  }
                </div> : f1View
            }
            {f3 ?
              <div key={rowID} style={{ padding: '0 15px', fontSize: 17, color: '#000' }}>
                <div style={{ display: 'flex', padding: '10px 0' }}>
                  <div style={{ lineHeight: 1, width: '100%', fontSize: 16 }}>
                    {/* { f6 ? f2 ? */}
                    {/*  '' : '' : ''} */}
                    {/* <div style={{ marginBottom: '12px' }} className={styles.wordsFlow}>{f3.showName}:<span style={{ color: '#000', paddingLeft: '6px' }}>{obj[f3.sName]}</span></div> */}
                    {/* <div */}
                    {/*  style={{ */}
                    {/*  marginBottom: '12px', */}
                    {/*  display: 'flex', */}
                    {/*  alignItem: 'center', */}
                    {/*  justifyContent: 'center', */}
                    {/* }} */}
                    {/*  className={styles.wordsFlow} */}
                    {/* > */}
                    {/*  {f4 ? */}
                    {/*    <div style={{ width: '70%', display: 'flex' }} className={styles.wordsFlow}> */}
                    {/*      <div>{f4.showName}:</div> */}
                    {/*      <div style={{ whiteSpace: 'normal', paddingLeft: '6px' }}><span style={{ color: '#000' }}>{obj[f4.sName]}</span></div> */}
                    {/*    </div> : '' */}
                    {/*  } */}
                    {/*  {f5 ? */}
                    {/*    <div style={{ width: '30%', textAlign: 'right' }} className={styles.wordsFlow}> */}
                    {/*      { */}
                    {/*        f6 ? */}
                    {/*          <span style={{ fontSize: '14px', color: '#108ee9' }} >{obj[f5.sName]}</span> : */}
                    {/*          <span style={{ fontSize: '14px', color: '#000' }} >{obj[f5.sName]}</span> */}
                    {/*      } */}
                    {/*    </div> : '' */}
                    {/*  } */}
                    {/* </div> */}
                    {slaveConfig.gdsconfigformslave.filter(item => item.bVisible && item.sName !== '').map((item, iIndex) => {
                      if (iIndex > 1) {
                        /**
                         * 修改日期：2021-04-06
                         * 修改人：吕杰
                         * 区域：以下 - 行
                         * BUG：1144
                         * 说明：现实缩略图，点击展示预览弹窗
                         * 原代码：
                         */
                        const bNotViewTitle = item.bNotViewTitle; /* 不显示标题 */
                        const sMemo = item.sName.toLowerCase().endsWith('memo');
                        const iRowNum = item.iColValue === 1 ? 24 : 1; /* 每个字段占的网格个数 ，网格总个数是24 */
                        const iColValue = sMemo ? 24 : item.iColValue * iRowNum; /* 跨度 */
                        const iRowValue = commonUtils.isEmptyNumber(item.iRowValue) || item.iRowValue === 0 ? 1 : item.iRowValue; /* 行高 */
                        const height = iRowValue * 18; /* 行高 */
                        const { token } = this.props.app;
                        const dataUrl = []; /* 缩略图 */
                        if ((item.showName === '缩略图' || item.sName === 'spicture') && obj[item.sName]) {
                          obj[item.sName].split(',').forEach(url => dataUrl.push(`${commonConfig.file_host}file/download?savePathStr=${url}&sModelsId=100&token=${token}`));
                        }
                        if (dataUrl.length) {
                          // eslint-disable-next-line
                          return (<span>{item.showName}：<img onClick={(e) => preView(dataUrl, e)} src={dataUrl[0]} alt="img" style={{ width: '30px', height: '20px' }} /></span>);
                        }
                        const targetConfig = slaveConfig.gdsconfigformslave.filter(item2 => item2.sName === item.sName)[0];
                        const customColor = targetConfig.sColorTerms ? targetConfig.sColorTerms : '#000';
                        return (
                          <div className={iColValue === 24 ? 'singleItem' : (iColValue === 12 ? 'doubleItem' : 'treeItem')} style={{ marginBottom: '12px', color: customColor }}>
                            <Flex style={{ padding: 0, fontSize: '16px', alignItems: 'center' }} wrap={'wrap'} align='start'>
                              {
                                bNotViewTitle ?
                                  <><Flex.Item style={{ fontWeight: 'bold', paddingLeft: '0.5px' }}> {obj[item.sName]}</Flex.Item></>
                                  :
                                  <><div className='flexTitle'>{item.showName}</div> <div style={{ fontWeight: 'bold' }}>：</div> <Flex.Item style={{ paddingLeft: '0.5px' }}> {obj[item.sName]}</Flex.Item></>
                              }
                            </Flex>
                          </div>
                        );
                      } else {
                        return ('');
                      }
                    })}
                  </div>
                </div>
              </div> : ''
            }
          </li>
        </div>
      );
    };
    const BtnStyle = {
      type: 'default',
      color: 'red',
      border: 'none',
      backgroundColor: '#fff',
      fontSize: '15px',
    };
    const divStyle = {
      display: 'flex',
      justifyContent: 'flex-end',
      background: '#fff',
    };
    const stepProps = {
      ...this.props,
      sSlaveId: this.state.sSlaveId,
    };
    return (
      <div
        style={{
          position: 'absolute',
          top: '0',
          bottom: '0',
          overflow: 'hiddle',
          width: '100%',
        }}
      >
        <div
          style={{
            position: 'relative',
            top: '0',
          }}
        >
          <div
            style={{
              display: 'flex',
              // justifyContent: 'center',
              alignItems: 'flex-start',
              flexWrap: 'wrap',
            }}
          >
            {commonUtils.isEmptyArr(slaveTotal) ? '' : Object.keys(slaveTotal[0]).map((key) => {
              const iIndex = slaveConfig.gdsconfigformslave.findIndex(item => item.sName === key);
              if (iIndex > -1) {
                return (
                  <div style={{
                    width: '50%',
                    textAlign: 'center',
                    textOverflow: 'ellipsis',
                    overflow: 'hidden',
                    whiteSpace: 'nowrap',
                    padding: '0 15px',
                    fontSize: '14px',
                  }}
                  >
                    {`${slaveConfig.gdsconfigformslave[iIndex].showName}:${commonUtils.convertFixNum(commonUtils.convertStrToNumber(slaveTotal[0][key]), this.props.getFloatNum(key))}`}
                  </div>
                );
              } else {
                return ('');
              }
            })}
          </div>
          <div>
            <CommobileSearchComponent {...this.props} showScan="true" />
          </div>
        </div>
        <div className={styles.listViewStyle}>
          <ListView
            dataSource={slaveData}
            renderFooter={() => (
              <div style={{ padding: 30, textAlign: 'center' }}>
                {this.state.isLoading ? '加载中...' : '加载完毕'}
              </div>)}
            renderRow={row}
            renderSeparator={separator}
            style={{
              position: 'absolute',
              width: '100%',
              bottom: commonUtils.isEmptyObject(slaveConfig) ? 88 : 135,
              top: 0,
              overflow: 'auto',
            }}
            pageSize={commonConfig.pageSize}
            onScroll={() => { }}
            scrollRenderAheadDistance={500}
            onEndReached={this.onEndReached}
            onEndReachedThreshold={10}
          />
        </div>

        {
          commonUtils.isEmptyObject(slaveConfig) ? '' :
            true ?
              <div style={{
                position: 'fixed',
                bottom: '0',
                width: '100%',
                display: 'flex',
                justifyContent: 'flex-start',
                alignItem: 'center',
                background: '#fff',
                zIndex: '9999',
              }}
              >
                {/*<AgreeItem*/}
                {/*  data-seed="logId"*/}
                {/*  disabled // 暂时全选禁止*/}
                {/*  onChange={e => this.props.onSelectAllClick(e)}*/}
                {/*  style={{*/}
                {/*    background: '#fff',*/}
                {/*    zIndex: '99999',*/}
                {/*    width: '25%',*/}
                {/*    display: 'flex',*/}
                {/*    justifyContent: 'flex-start',*/}
                {/*    alignItems: 'cneter',*/}
                {/*  }}*/}
                {/*>*/}
                {/*  全选*/}
                {/*</AgreeItem>*/}
                <div className={styles.commobilelistToolBarBtn}>
                  <CommobileToolBar {...this.props} btnStyle={BtnStyle} divStyle={divStyle} onButtonClick={this.props.onButtonClick} />
                </div>
              </div> : ''
        }{f7 && commonUtils.isNotEmptyObject(this.state.sSlaveId) ?
          <Modal
            className="statusView"
            popup
            visible={this.state.partNameStatusVisible}
            // closable
            onClose={this.onClose('partNameStatusVisible')}
            animationType="fade"
            afterClose={() => { }}
          >
            <div className={styles.statusView_title}>
              {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
              <a style={{ float: 'left', fontSize: '1.5em' }} onClick={this.onClose('partNameStatusVisible')} >&lt;</a>
              工单状态
            </div>
            <CommonbileStep {...stepProps} />
          </Modal> : ''
        }
      </div>
    );
  }
}

const CommobilePadListComponent = (props) => {
  const { form, onReturnForm, formData = [], slaveConfig = {} } = props;
  if (!formData.length) return null;

  useEffect(() => {
    const slaveColumn = commonFunc.getHeaderConfig(slaveConfig);
    props.onSaveState({ slaveColumn });
  }, [])

  onReturnForm(form);

  const BtnStyle = {
    type: 'default',
    color: 'red',
    border: 'none',
    backgroundColor: '#fff',
    fontSize: '15px',
  };
  const divStyle = {
    display: 'flex',
    justifyContent: 'flex-end',
    background: '#fff',
  };

  return (
    <div>
      <div className={stylesNew.search}>
        <SearchComponent {...props} />
      </div>
      <div className={stylesNew.table}>
        <TableComponent {...props} tableName="slave" />
      </div>
      <div className={styles.commobilelistToolBarBtn}>
        <CommobileToolBar {...props} btnStyle={BtnStyle} divStyle={divStyle} onButtonClick={props.onButtonClick} />
      </div>
    </div>
  )
}

// 表格
const TableComponent = props => {
  const { tableName } = props;
  const baseProps = commonBusiness.getTableTypes(tableName, {
    ...props,
    noStorageColumn: true
  });
  const tableProps = {
    ...baseProps,
    // setOpterationColumn: "Y",
    tableProps: {
      // onChange: props.onTitleChange.bind(this, tableName),
    },
    fixedHeight: "calc(100vh - 230px)",
    showTableName: false,
    onSelectRowChange: (name, selectedRowKeys) => {
      props.onSaveState({ [`${name}SelectedRowKeys`]: selectedRowKeys });
    }
  };
  return <StaticEditTable {...tableProps} />;
};

const CommobileListComponent = createForm()(CommobileList);

export default CommobileBase(CommobileListEvent(CommobileListComponent));
