/**
 * Created by RaoMeng on 2020/2/17
 * Desc: 审批功能首页
 */

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import { TabBar } from 'antd-mobile'
import { List, Icon, Skeleton, message } from 'antd'
import './approval.css'
import Swiper from 'swiper/js/swiper.min'
import 'swiper/css/swiper.min.css'
import RefreshLayout from '../../components/RefreshLayout'
import { isObjEmpty } from '../../utils/common'
import { fetchGet } from '../../utils/fetchRequest'
import { connect } from 'react-redux'
import {
  clearHomeState,
  clearNewState,
  clearReceiveState,
  clearSendState,
  freshHomeState,
  saveNewState,
  saveReceiveState,
  saveSendState,
} from '../../redux/actions/homeState'
import CustomIcon from '../../utils/CustomIcon'
import ApprovalItem from '../../components/approvalItem/ApprovalItem'

let mMaster = 'UAS_DEV'
const mPageSize = 20
let mTodoIndex = 0
let mDoneIndex = 0
let mSendIndex = 0

let mBaseUrl = window.location.origin
  // && 'http://29226oq576.qicp.vip/uas/'

class ApprovalHome extends Component {

  constructor () {
    super()

    this.state = {
      pageVisible: false,
      tabHidden: false,
      isNewMenuLoading: true,
      isReceiveTodoLoading: true,
      isReceiveDoneLoading: true,
      isReceiveTodoRefresh: false,
      isReceiveDoneRefresh: false,
      receiveHeight: document.documentElement.clientHeight,
      sendHeight: document.documentElement.clientHeight,
      isSendRefresh: false,
      isSendLoading: true,
    }
  }

  componentDidMount () {
    setTimeout(() => {
      this.setState({
        pageVisible: true,
      })
    }, 100)
    // 用于刷新组建确认高度
    if (ReactDOM.findDOMNode(this.contain)) {
      const hei = this.state.receiveHeight -
        ReactDOM.findDOMNode(this.contain).offsetTop - 50
      this.setState({
        receiveHeight: hei,
      })
    }
    if (ReactDOM.findDOMNode(this.sendList)) {
      const hei = this.state.sendHeight -
        ReactDOM.findDOMNode(this.sendList).offsetTop - 50
      this.setState({
        sendHeight: hei,
      })
    }
    document.title = '审批'

    const { homeState } = this.props
    const { newState, receiveState, sendState, selectedTab } = homeState

    this.initSwiper(receiveState)

    switch (selectedTab) {
      case 0: {
        this.initNew(newState)
        break
      }
      case 1: {
        this.initReceive(receiveState)
        break
      }
      case 2: {
        this.initSend(sendState)
        break
      }
      default:
        break
    }
  }

  initSwiper (receiveState) {
    this.mySwiper = new Swiper('.swiper-container', {
      autoplay: false,
      loop: false,
      noSwiping: false,
      initialSlide: receiveState.tabIndex,
      on: {
        slideChangeTransitionEnd: function () {
          saveReceiveState({
            tabIndex: this.activeIndex,
          })()
        },
      },
    })
  }

  initNew (newState) {
    if (!isObjEmpty(newState.newMenuList)) {
      this.setState({
        isNewMenuLoading: false,
      }, () => {
        ReactDOM.findDOMNode(this.newList).scrollTop =
          newState.scrollTop
      })
    } else {
      this.getNewMenuData()
    }
  }

  initReceive (receiveState) {
    if (receiveState && receiveState.tabIndex >= 0) {
      this.mySwiper.slideTo(receiveState.tabIndex, 0, false)
    }

    if (receiveState && !isObjEmpty(receiveState.listData)) {
      this.setState({
        isReceiveTodoLoading: false,
      }, () => {
        ReactDOM.findDOMNode(this.todoTab).scrollTop =
          receiveState.scrollTop
      })
      mTodoIndex = receiveState.pageIndex
    } else {
      mTodoIndex = 0
      this.loadTodoList()
    }

    if (receiveState && !isObjEmpty(receiveState.listData2)) {
      this.setState({
        isReceiveDoneLoading: false,
      }, () => {
        ReactDOM.findDOMNode(this.doneTab).scrollTop =
          receiveState.scrollTop2
      })
      mDoneIndex = receiveState.pageIndex2
    } else {
      mDoneIndex = 0
      this.loadDoneList()
    }
  }

  initSend (sendState) {
    if (!isObjEmpty(sendState.sendList)) {
      this.setState({
        isSendLoading: false,
      }, () => {
        ReactDOM.findDOMNode(this.sendList).scrollTop =
          sendState.scrollTop
      })
    } else {
      mSendIndex = 0
      this.loadSendList()
    }
  }

  componentWillUnmount () {
    // clearHomeState()()
  }

  render () {
    return (
      <div className={this.state.pageVisible ? 'home-root' : 'visibleHidden'}>
        <TabBar
          unselectedTintColor="#949494"
          tintColor="#33A3F4"
          barTintColor="white"
          prerenderingSiblingsNumber={2}
          hidden={this.state.tabHidden}
        >
          {this.getNewTab()}
          {this.getReceiveTab()}
          {this.getSendTab()}
        </TabBar>
      </div>
    )
  }

  /**
   * 【新建】
   * @returns {*}
   */
  getNewTab = () => {
    return (
      <TabBar.Item
        title="新建"
        key="New"
        icon={<CustomIcon type="icon-new"/>}
        selectedIcon={<CustomIcon type="icon-new-selected"/>}
        selected={this.props.homeState.selectedTab === 0}
        // badge={''}
        onPress={this.onTab1Selected}
      >
        {this.renderNewTab()}
      </TabBar.Item>
    )
  }

  /**
   * 【我审批的】
   * @returns {*}
   */
  getReceiveTab = () => {
    return (
      <TabBar.Item
        title="我审批的"
        key="Receive"
        icon={<CustomIcon type='icon-receive'/>}
        selectedIcon={<CustomIcon type="icon-receive-selected"/>}
        selected={this.props.homeState.selectedTab === 1}
        // badge={''}
        onPress={this.onTab2Selected}
      >
        {this.renderReceiveTab()}
      </TabBar.Item>
    )
  }

  /**
   * 【我发起的】
   * @returns {*}
   */
  getSendTab = () => {
    return (
      <TabBar.Item
        title="我发起的"
        key="Send"
        icon={<CustomIcon type="icon-send"/>}
        selectedIcon={<CustomIcon type="icon-send-selected"/>}
        selected={this.props.homeState.selectedTab === 2}
        // badge={''}
        onPress={this.onTab3Selected}
      >
        {this.renderSendTab()}
      </TabBar.Item>
    )
  }

  onTab1Selected = () => {
    const { isNewMenuLoading } = this.state
    const { homeState: { newState, selectedTab } } = this.props
    if (selectedTab === 0) {
      // 刷新页面
      if (!isNewMenuLoading) {
        this.setState({
          isNewMenuLoading: true,
        })
        clearNewState()()
        this.getNewMenuData()
      }
    } else {
      if (isObjEmpty(newState.newMenuList)) {
        this.setState({
          isNewMenuLoading: true,
        })
        this.getNewMenuData()
      } else {
        this.setState({
          isNewMenuLoading: false,
        }, () => {
          // ReactDOM.findDOMNode(this.newList).scrollTop =
          //   newState.scrollTop
        })
      }
    }
    freshHomeState({
      selectedTab: 0,
    })()
  }

  onTab2Selected = () => {
    const { isReceiveTodoLoading, isReceiveDoneLoading } = this.state
    const { homeState: { receiveState, selectedTab } } = this.props
    if (selectedTab === 1) {
      // 刷新页面
      clearReceiveState()()
      this.mySwiper.slideTo(0, 0, false)
      if (!isReceiveTodoLoading) {
        this.setState({
          isReceiveTodoLoading: true,
        })
        mTodoIndex = 0
        this.loadTodoList()
      }
      if (!isReceiveDoneLoading) {
        this.setState({
          isReceiveDoneLoading: true,
        })
        mDoneIndex = 0
        this.loadDoneList()
      }
    } else {
      if (isObjEmpty(receiveState.listData)) {
        this.setState({
          isReceiveTodoLoading: true,
        })
        mTodoIndex = 0
        this.loadTodoList()
      } else {
        this.setState({
          isReceiveTodoLoading: false,
        }, () => {
          // ReactDOM.findDOMNode(this.todoTab).scrollTop =
          //   receiveState.scrollTop
        })
        mTodoIndex = receiveState.pageIndex
      }
      if (isObjEmpty(receiveState.listData2)) {
        this.setState({
          isReceiveDoneLoading: true,
        })
        mDoneIndex = 0
        this.loadDoneList()
      } else {
        this.setState({
          isReceiveDoneLoading: false,
        }, () => {
          // ReactDOM.findDOMNode(this.doneTab).scrollTop =
          //   receiveState.scrollTop2
        })
        mDoneIndex = receiveState.pageIndex2
      }
    }
    freshHomeState({
      selectedTab: 1,
    })()
  }

  onTab3Selected = () => {
    const { isSendLoading } = this.state
    const { homeState: { sendState, selectedTab } } = this.props
    if (selectedTab === 2) {
      // 刷新页面
      clearSendState()()
      if (!isSendLoading) {
        this.setState({
          isSendLoading: true,
        })
        mSendIndex = 0
        this.loadSendList()
      }
    } else {
      if (isObjEmpty(sendState.sendList)) {
        this.setState({
          isSendLoading: true,
        })
        mSendIndex = 0
        this.loadSendList()
      } else {
        this.setState({
          isSendLoading: false,
        }, () => {
          // ReactDOM.findDOMNode(this.sendList).scrollTop =
          //   sendState.scrollTop
        })
      }
    }
    freshHomeState({
      selectedTab: 2,
    })()
  }

  renderNewTab = () => {
    return (
      <div
        ref={el => {
          this.newList = el
        }}
        id='newMenu-root'>
        <Skeleton loading={this.state.isNewMenuLoading} active
                  paragraph={{ rows: 4 }}>
          {this.getNewMenu()}
        </Skeleton>
      </div>
    )
  }

  renderReceiveTab = () => {
    const { isReceiveTodoLoading, isReceiveDoneLoading } = this.state
    const { homeState: { receiveState: { tabIndex } } } = this.props
    const todoItems = this.renderReceiveTodoItems()
    const doneItems = this.renderReceiveDoneItems()
    return (
      <div className='receive-root'>
        <div className='line'></div>
        <div className='identity-select'>
          <div className={tabIndex === 0 ?
            'identity-item-select' : 'identity-item-normal'}
               onClick={() => {
                 if (tabIndex === 0) {
                   if (!isReceiveTodoLoading) {
                     this.setState({
                       isReceiveTodoLoading: true,
                     })
                     saveReceiveState({
                       scrollTop: 0,
                     })()
                     mTodoIndex = 0
                     this.loadTodoList()
                   }
                 } else {
                   saveReceiveState({
                     tabIndex: 0,
                   })()
                   this.mySwiper.slideTo(0, 300, false)
                 }
               }}>待审批
          </div>
          <div className={tabIndex === 1 ?
            'identity-item-select' : 'identity-item-normal'}
               onClick={() => {
                 if (tabIndex === 1) {
                   if (!isReceiveDoneLoading) {
                     this.setState({
                       isReceiveDoneLoading: true,
                     })
                     saveReceiveState({
                       scrollTop2: 0,
                     })()
                     mDoneIndex = 0
                     this.loadDoneList()
                   }
                 } else {
                   saveReceiveState({
                     tabIndex: 1,
                   })()
                   this.mySwiper.slideTo(1, 300, false)
                 }
               }}>已审批
          </div>
        </div>
        <div className="swiper-container"
             ref={el => {
               this.contain = el
             }}>
          <div className="swiper-wrapper">
            <div className="swiper-slide">
              {todoItems}
            </div>
            <div className="swiper-slide">
              {doneItems}
            </div>
          </div>
        </div>
      </div>
    )
  }

  renderSendTab = () => {
    return (
      <div className='receive-content-root'>
        <RefreshLayout
          ref={el => {
            this.sendList = el
          }}
          refreshing={this.state.isSendRefresh}
          onRefresh={this.loadSendList}
          height={this.state.sendHeight}>
          <Skeleton loading={this.state.isSendLoading} active
                    paragraph={{ rows: 4 }}>
            <List split={false}
                  dataSource={this.props.homeState.sendState.sendList}
                  renderItem={(item, index) => (
                    <ApprovalItem approval={item}
                                  type={3}
                                  onItemClick={this.onSendItemClick.bind(this)}
                                  index={index}/>
                  )}/>
          </Skeleton>
        </RefreshLayout>
      </div>
    )
  }

  renderReceiveTodoItems = () => (
    <div className='receive-content-root'>
      <RefreshLayout
        ref={el => {
          this.todoTab = el
        }}
        refreshing={this.state.isReceiveTodoRefresh}
        onRefresh={this.loadTodoList}
        height={this.state.receiveHeight}>
        <Skeleton loading={this.state.isReceiveTodoLoading} active
                  paragraph={{ rows: 4 }}>
          <List split={false}
                dataSource={this.props.homeState.receiveState.listData}
                renderItem={(item, index) => (
                  <ApprovalItem approval={item}
                                type={1}
                                onItemClick={this.onReceiveItemClick.bind(this)}
                                index={index}/>
                )}/>
        </Skeleton>
      </RefreshLayout>
    </div>
  )

  renderReceiveDoneItems = () => (
    <div className='receive-content-root'>
      <RefreshLayout
        ref={el => {
          this.doneTab = el
        }}
        refreshing={this.state.isReceiveDoneRefresh}
        onRefresh={this.loadDoneList}
        height={this.state.receiveHeight}>
        <Skeleton loading={this.state.isReceiveDoneLoading} active
                  paragraph={{ rows: 4 }}>
          <List split={false}
                dataSource={this.props.homeState.receiveState.listData2}
                renderItem={(item, index) => (
                  <ApprovalItem approval={item}
                                type={2}
                                onItemClick={this.onReceiveItemClick.bind(this)}
                                index={index}/>
                )}/>
        </Skeleton>
      </RefreshLayout>
    </div>
  )

  getNewMenu = () => {
    const { homeState } = this.props
    let newMenu = []
    if (!isObjEmpty(homeState.newState.newMenuList)) {
      homeState.newState.newMenuList.
        forEach((groupItem, groupIndex) => {
          if (groupIndex !== 0) {
            newMenu.push(<div className='gray-line'></div>)
          }
          newMenu.push(<MenuGroup groupIcon={groupItem.groupIcon}
                                  groupText={groupItem.st_name}/>)

          const funcList = groupItem.serves
          if (!isObjEmpty(funcList)) {
            funcList.forEach((funcItem, funcIndex) => {
              newMenu.push(<FuncItem funcObj={funcItem}
                                     onFuncClick={this.onFuncClick}/>)
            })
          }
        })
    }
    return newMenu
  }

  onFuncClick = (obj) => {
    this.cacheScrollState()
    this.props.history.push('/approvalAdd/' + obj.sv_caller + '/' + mMaster)
  }

  onReceiveItemClick = (index, approval) => {
    this.cacheScrollState()
    saveReceiveState({
      itemIndex: index,
    })()
    let jp_form = approval.JP_FORM
    let currentmaster = approval.CURRENTMASTER
    if (!isObjEmpty(jp_form) && !isObjEmpty(currentmaster) &&
      (jp_form.indexOf(currentmaster) != -1)) {

    } else {
      currentmaster = mMaster
    }
    this.props.history.push('/approval/%7B%22' +
      'master%22%3A%22' + currentmaster
      + '%22%2C%22nodeId%22%3A' + approval.JP_NODEID
      + '%2C%22type%22%3A' + 0
      + '%2C%22baseUrl%22%3A%22' + encodeURIComponent(mBaseUrl)
      + '%22%7D')
  }

  onSendItemClick = (index, approval) => {
    this.cacheScrollState()
    let jp_form = approval.JP_FORM
    let currentmaster = approval.CURRENTMASTER
    if (!isObjEmpty(jp_form) && !isObjEmpty(currentmaster) &&
      (jp_form.indexOf(currentmaster) != -1)) {

    } else {
      currentmaster = mMaster
    }
    this.props.history.push('/approval/%7B%22' +
      'master%22%3A%22' + currentmaster
      + '%22%2C%22nodeId%22%3A' + approval.JP_NODEID
      + '%2C%22type%22%3A' + 1
      + '%2C%22baseUrl%22%3A%22' + encodeURIComponent(mBaseUrl)
      + '%22%7D')
  }

  cacheScrollState () {
    // console.log('raomeng', ReactDOM.findDOMNode(this.newList).scrollTop)
    // console.log('raomeng', ReactDOM.findDOMNode(this.todoTab).scrollTop)
    // console.log('raomeng', ReactDOM.findDOMNode(this.doneTab).scrollTop)
    // console.log('raomeng', ReactDOM.findDOMNode(this.sendList).scrollTop)
    saveNewState({
      scrollTop: ReactDOM.findDOMNode(this.newList).scrollTop,
    })()
    saveReceiveState({
      scrollTop: ReactDOM.findDOMNode(this.todoTab).scrollTop,
      scrollTop2: ReactDOM.findDOMNode(this.doneTab).scrollTop,
    })()
    saveSendState({
      scrollTop: ReactDOM.findDOMNode(this.sendList).scrollTop,
    })()
  }

  getNewMenuData = () => {
    this.setState({
      isNewMenuLoading: true,
    })

    fetchGet(mBaseUrl + '/api/serve/mainPage/getServices.action', {
      kind: 'appweb',
    }).then(response => {
      this.setState({
        isNewMenuLoading: false,
      })
      let configs = response.configs

      if (isObjEmpty(configs)) {
        message.warn('菜单数据为空')
      } else {
        saveNewState({
          newMenuList: configs,
        })()
      }
    }).catch(error => {
      this.setState({
        isNewMenuLoading: false,
      })
      if (typeof error === 'string') {
        message.error(error)
      } else {
        message.error('菜单数据获取失败')
      }
    })
  }

  loadTodoList = () => {
    let { homeState: { receiveState: { listData } } } = this.props
    if (isObjEmpty(listData)) {
      mTodoIndex = 0
    }
    mTodoIndex++
    if (!this.state.isReceiveTodoLoading) {
      this.setState({
        isReceiveTodoRefresh: true,
      })
    }

    if (mTodoIndex === 1) {
      listData.length = 0
    }

    fetchGet(mBaseUrl + '/common/desktop/process/uapproval/toDo.action', {
      pageSize: mPageSize,
      page: mTodoIndex,
    }).then(response => {
      this.setState({
        isReceiveTodoLoading: false,
        isReceiveTodoRefresh: false,
      })
      console.log('raomeng', response)
      if (response && !isObjEmpty(response.data)) {
        listData = listData.concat(response.data)
      } else {
        if (mTodoIndex > 1) {
          mTodoIndex--
        }
      }
      saveReceiveState({
        listData,
        pageIndex: mTodoIndex,
      })()
    }).catch(error => {
      if (mTodoIndex > 1) {
        mTodoIndex--
      }
      saveReceiveState({
        listData,
        pageIndex: mTodoIndex,
      })()
      this.setState({
        isReceiveTodoLoading: false,
        isReceiveTodoRefresh: false,
      })
      if (typeof error === 'string') {
        message.error(error)
      } else {
        message.error('待审批列表请求异常')
      }
    })
  }

  loadDoneList = () => {
    let { homeState: { receiveState: { listData2 } } } = this.props
    if (isObjEmpty(listData2)) {
      mDoneIndex = 0
    }
    mDoneIndex++
    if (!this.state.isReceiveDoneLoading) {
      this.setState({
        isReceiveDoneRefresh: true,
      })
    }

    if (mDoneIndex === 1) {
      listData2.length = 0
    }

    fetchGet(mBaseUrl + '/common/desktop/process/uapproval/alreadyDo.action', {
      pageSize: mPageSize,
      page: mDoneIndex,
      isMobile: 1,
      _do: 1,
    }).then(response => {
      this.setState({
        isReceiveDoneLoading: false,
        isReceiveDoneRefresh: false,
      })
      console.log('raomeng', response)
      if (response && !isObjEmpty(response.data)) {
        listData2 = listData2.concat(response.data)
      } else {
        if (mDoneIndex > 1) {
          mDoneIndex--
        }
      }
      saveReceiveState({
        listData2,
        pageIndex: mDoneIndex,
      })()
    }).catch(error => {
      if (mDoneIndex > 1) {
        mDoneIndex--
      }
      saveReceiveState({
        listData2,
        pageIndex: mDoneIndex,
      })()
      this.setState({
        isReceiveDoneLoading: false,
        isReceiveDoneRefresh: false,
      })
      if (typeof error === 'string') {
        message.error(error)
      } else {
        message.error('待审批列表请求异常')
      }
    })
  }

  loadSendList = () => {
    let { homeState: { sendState: { sendList } } } = this.props
    if (isObjEmpty(sendList)) {
      mSendIndex = 0
    }
    mSendIndex++
    if (!this.state.isSendLoading) {
      this.setState({
        isSendRefresh: true,
      })
    }

    if (mSendIndex === 1) {
      sendList.length = 0
    }

    fetchGet(mBaseUrl + '/common/desktop/process/uapproval/alreadyLaunch.action',
      {
        pageSize: mPageSize,
        page: mSendIndex,
        isMobile: 1,
        _do: 1,
      }).then(response => {
      this.setState({
        isSendLoading: false,
        isSendRefresh: false,
      })
      console.log('raomeng', response)
      if (response && !isObjEmpty(response.data)) {
        sendList = sendList.concat(response.data)
      } else {
        if (mSendIndex > 1) {
          mSendIndex--
        }
      }
      saveSendState({
        sendList,
        pageIndex: mSendIndex,
      })()
    }).catch(error => {
      if (mSendIndex > 1) {
        mSendIndex--
      }
      saveSendState({
        sendList,
        pageIndex: mSendIndex,
      })()
      this.setState({
        isSendLoading: false,
        isSendRefresh: false,
      })
      if (typeof error === 'string') {
        message.error(error)
      } else {
        message.error('列表请求异常')
      }
    })
  }
}

class MenuGroup extends Component {
  render () {
    return (
      <div className='newMenu-group-layout'>
        {/*<img className='newMenu-group-icon' src={this.props.groupIcon}/>*/}
        <span className='newMenu-group-text'>{this.props.groupText}</span>
      </div>
    )
  }
}

class FuncItem extends Component {
  render () {
    const { funcObj } = this.props

    return (
      isObjEmpty(funcObj) ?
        <div></div> :
        <div className='newMenu-func-root' onClick={this.onFuncClick}>
          <div className='newMenu-func-layout'>
            <img className='newMenu-func-icon'
                 src={funcObj.sv_logourl ? funcObj.sv_logourl.mobile : ''}/>
            <span className='newMenu-func-text'>{funcObj.sv_name}</span>
          </div>
        </div>
    )
  }

  onFuncClick = () => {
    if (this.props.onFuncClick) {
      this.props.onFuncClick(this.props.funcObj)
    }
  }
}

let mapStateToProps = (state) => ({
  homeState: { ...state.redHomeState },
})

let mapDispatchToProps = (dispatch) => ({})

export default connect(mapStateToProps, mapDispatchToProps)(ApprovalHome)
