/**
 * Created by RaoMeng on 2019/1/15
 * Desc: 通讯录搜索页面
 */

import React, {Component} from 'react'
import PhonesBean from 'model/PhonesBean'
import {getStrValue, isObjEmpty} from "../../utils/common";
import RefreshLayout from "../../components/RefreshLayout";
import PhonesItem from "../../components/PhonesItem";
import {Toast, SearchBar} from "antd-mobile";
import {List, Skeleton} from 'antd'
import {_baseURL, API} from "../../configs/api.config";
import {fetchGet, fetchPost} from "../../utils/fetchRequest";
import {connect} from 'react-redux'

const mPageSize = 10
let mPageIndex = 0
let mSearchKey = ''

class PhonesSearch extends Component {

    constructor() {
        super()

        this.state = {
            isRefreshing: false,
            phonesList: [],
            isLoading: false,
            searchKey: '',
            searchText: '',
        }
    }

    componentWillMount() {
        this.mType = this.props.match.params.type
        if (this.mType === 'teacher') {
            this.title = '搜索老师'
        } else if (this.mType === 'parent') {
            this.title = '搜索学生'
        }
    }

    componentDidMount() {
        this.searchInput.focus()

        document.title = this.title
    }

    componentWillUnmount() {

    }

    render() {
        const {phonesList, isRefreshing, isLoading, searchText} = this.state

        return (
            <div className='phone-select-root' style={{height: '100%'}}>
                <SearchBar placeholder={this.title} maxLength={20}
                           ref={ref => this.searchInput = ref}
                           value={searchText} onSubmit={this.searchSubmit}
                           onChange={this.searchChange} onClear={this.searchClear}
                           onCancel={this.searchClear}/>

                <RefreshLayout
                    refreshing={isRefreshing}
                    onRefresh={this.loadPhones}>
                    <Skeleton loading={isLoading} active paragraph={{rows: 3}}>
                        <List className='phones-list-layout'
                              dataSource={phonesList}
                              renderItem={phonesBean => (
                                  <List.Item>
                                      <PhonesItem phonesBean={phonesBean}/>
                                  </List.Item>
                              )}/>
                    </Skeleton>
                </RefreshLayout>
            </div>
        )
    }

    searchChange = (value) => {
        mSearchKey = value
        this.setState({
            searchText: value
        })
    }


    searchClear = (e) => {
        mPageIndex = 0
        this.setState({
            isLoading: true,
            isRefreshing: false,
            searchText: '',
            searchKey: ''
        }, () => {
            this.loadPhones()
        })
    }

    searchSubmit = (value) => {
        mPageIndex = 0
        this.setState({
            isLoading: true,
            isRefreshing: false,
            searchKey: value
        }, () => {
            this.loadPhones()
        })
    }

    loadPhones = () => {
        try {
            this.setState({
                isRefreshing: true
            })
        } catch (e) {
        }

        if (this.mType == 'parent') {
            this.url = API.GET_PARENT_PHONES_BYTEACHER
            this.params = {
                teacherId: this.props.userInfo.user.userFunId
            }
            this.getPhones()
        } else if (this.mType == 'teacher') {
            this.url = API.TEACHER_PHONES_LIST
            this.params = {
                teacherId: this.props.userInfo.user.userFunId
            }
            this.getPhones()
        } else {
            Toast.hide()
            this.setState({
                isRefreshing: false
            })
        }
    }

    getPhones = () => {
        mPageIndex++
        console.log(mPageIndex)

        const {phonesList, searchKey} = this.state
        if (mPageIndex === 1) {
            phonesList.length = 0
        }

        fetchPost(this.url, {
            pageIndex: mPageIndex,
            pageSize: mPageSize,
            selectKey: searchKey,
            ...this.params
        }).then(response => {
            Toast.hide();

            if (response && response.data) {
                if (this.mType == 'teacher') {
                    response.data.forEach((item, index) => {
                        let phoneBean = new PhonesBean()

                        phoneBean.icon = require('imgs/ic_head' + (index % 15 + 1) + '.png')
                        phoneBean.icon = _baseURL + getStrValue(item, 'teacherPhoto')
                        phoneBean.name = getStrValue(item, 'teacherName')
                        phoneBean.phone = [getStrValue(item, 'userPhone')]
                        // phoneBean.claName = getStrValue(item, 'schName')
                        phoneBean.children = ['']

                        phonesList.push(phoneBean)
                    })
                } else if (this.mType == 'parent') {
                    let studentList = []
                    response.data.forEach((item, index) => {
                        if (item.studentDOS) {
                            studentList = studentList.concat(item.studentDOS)
                        }
                    })

                    if (!isObjEmpty(studentList)) {
                        studentList.forEach((item, index) => {
                            let phoneBean = new PhonesBean()
                            let phones = []
                            phoneBean.icon = require('imgs/ic_head' + (index % 15 + 1) + '.png')
                            phoneBean.icon = _baseURL + getStrValue(item, 'stuPhoto')
                            phoneBean.name = getStrValue(item, 'stuName')
                            phoneBean.claName = this.title

                            if (item.parentsDOS && item.parentsDOS.length > 0) {
                                item.parentsDOS.forEach((ite, ind) => {
                                    phoneBean.children.push(getStrValue(ite, 'parentsName'))
                                    phones.push(getStrValue(ite, 'userPhone'))
                                })
                            }

                            // if (phones.length > 0) {
                            phoneBean.phone = phones
                            // }

                            phonesList.push(phoneBean)
                        })
                    }

                }
            } else {
                if (mPageIndex > 1) {
                    mPageIndex--
                }
            }

            this.setState({
                phonesList,
                isLoading: false,
                isRefreshing: false,
            })
        }).catch(error => {
            Toast.hide()

            if (mPageIndex > 1) {
                mPageIndex--
            }
            if (typeof error === 'string') {
                Toast.fail(error, 2)
            } else {
                Toast.fail('请求异常')
            }

            this.setState({
                isLoading: false,
                isRefreshing: false,
            })
        })
    }
}

let mapStateToProps = (state) => ({
    userInfo: {...state.redUserInfo},
})

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

export default connect(mapStateToProps, mapDispatchToProps)(PhonesSearch)
