/**
 * Created by RaoMeng on 2018/11/14
 * Desc: 发布通知公告
 */

import React, {Component} from 'react'
import {Input, Button} from 'antd'
import 'css/announce.css'
import {Toast} from 'antd-mobile'
import TargetSelect from 'components/TargetSelect'
import UploadEnclosure from 'components/UploadEnclosure'
import {fetchGet, fetchPost,fetchPostObj} from "../../utils/fetchRequest";
import {_baseURL, API} from "../../configs/api.config";
import {getIntValue, getStrValue, isObjEmpty} from "../../utils/common";
import {connect} from 'react-redux'
import {clearListState} from 'action/listState'

const {TextArea} = Input

class AnnounceRelease extends Component {

    constructor() {
        super()

        this.state = {
            announceTitle: '',
            announceContent: '',

            previewVisible: false,
            previewImage: '',
            fileList: [],
            targetList: [],
            targetCount: 0,
            targetData: [],
        }
    }

    componentDidMount() {
        document.title = '发布通知公告'

        // this.getOrganization()
    }

    componentWillUnmount() {
        Toast.hide()

        clearTimeout(this.backTask)
    }

    render() {
        const {announceTitle, announceContent, targetCount, targetList, fileList, targetData} = this.state
        /*const targetProps = {
            targetData: targetData,
            targetValues: targetList,
            title: '通知对象',
            targetCount: targetCount,
            onTargetChange: this.onTargetChange.bind(this),
            onTargetFocus: this.onTargetFocus.bind(this)
        }

        const defaultTargetProps = {
            targetData: [],
            targetValues: targetList,
            title: '通知对象',
            targetCount: targetCount,
            onTargetChange: this.onTargetChange.bind(this),
            onTargetFocus: this.onTargetFocus.bind(this)
        }*/
        return (
            <div className='common-column-layout'>
                {/*<div className='gray-line'></div>
                {targetData.length > 0 ? <TargetSelect {...targetProps}/>
                    : <TargetSelect {...defaultTargetProps}/>}*/}
                <div className='gray-line'></div>
                <input className='titleInput' placeholder='请输入通知标题'
                       value={announceTitle} onChange={this.titleChange}/>
                <div className='gray-line' style={{height: '1px'}}></div>
                <TextArea className='contentInput' placeholder='请输入通知内容'
                          autosize={{minRows: 6, maxRows: 12}} value={announceContent}
                          onChange={this.contentChange}/>
                <div className='gray-line'></div>
                <UploadEnclosure
                    action={API.UPLOAD_FILE}
                    fileList={fileList}
                    count={9}
                    multiple={true}
                    beforeUpload={this.beforeUpload.bind(this)}
                    handleChange={this.handleChange.bind(this)}
                />

                <Button className='commonButton' type='primary' style={{margin: '35px',borderRadius:30}}
                        onClick={this.releaseAnnounce}>发布</Button>

                {/*<span className='announce-release-history'>历史发布</span>*/}
            </div>
        )
    }

    getOrganization = () => {
        Toast.loading('', 0)

        fetchGet(API.getClazzByTeacherId, {
            teacherId: this.props.userInfo.user.userFunId,
        }).then(response => {
            Toast.hide()
            const {targetData} = this.state
            targetData.length = 0
            if (response && response.data) {
                response.data.forEach((dataObj, data_index) => {
                    const stusDOSArray = dataObj.studentDOS
                    const teacherDOSArray = dataObj.teacherDOS
                    if (!isObjEmpty(stusDOSArray)) {
                        const classData = []
                        stusDOSArray.forEach((stuObj, index) => {
                            if (stuObj) {
                                classData.push({
                                    title: getStrValue(stuObj, 'stuName'),
                                    userId: getIntValue(stuObj, 'stuId'),
                                    userPhone: getStrValue(stuObj, 'userPhone'),
                                    value: `2-${data_index}-${index}-` + getStrValue(stuObj, 'stuName'),
                                    key: `2-${data_index}-${index}`,
                                })
                            }
                        })

                        targetData.push({
                            title: dataObj.gradeName + dataObj.clazzName + '全体学生',
                            value: `2-${data_index}-` + dataObj.gradeName + dataObj.clazzName + '全体学生',
                            key: `2-${data_index}`,
                            children: classData,
                        })
                    }

                    if (!isObjEmpty(teacherDOSArray)) {
                        const teacherData = []
                        teacherDOSArray.forEach((teacherObj, index) => {
                            if (teacherObj) {
                                teacherData.push({
                                    title: getStrValue(teacherObj, 'teacherName'),
                                    userId: getIntValue(teacherObj, 'teacherId'),
                                    userPhone: getStrValue(teacherObj, 'userPhone'),
                                    value: `0-${data_index}-${index}-` + getStrValue(teacherObj, 'teacherName'),
                                    key: `0-${data_index}-${index}`,
                                })
                            }
                        })

                        targetData.push({
                            title: dataObj.gradeName + dataObj.clazzName + '全体老师',
                            value: `0-${data_index}-` + dataObj.gradeName + dataObj.clazzName + '全体老师',
                            key: `0-${data_index}`,
                            children: teacherData,
                        })
                    }
                })
            }
            this.setState({
                targetData,
            })
        }).catch(error => {
            Toast.hide()

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

    releaseAnnounce = () => {
        if (this.isRequesting == true) {
            return
        }

        const {announceTitle, announceContent, fileList} = this.state

        if (isObjEmpty(announceTitle)) {
            Toast.fail('请输入通知标题')
            return
        }
        if (isObjEmpty(announceContent)) {
            Toast.fail('请输入通知内容')
            return
        }
        // if (isObjEmpty(this.checkNodes)) {
        //     Toast.fail('请选择通知对象')
        //     return
        // }

        if (announceTitle.length > 50) {
            Toast.fail('通知标题过长')
            return
        }

        const fileUrls = []
        if (fileList) {
            fileList.forEach((value, index) => {
                if (value.status === 'uploading') {
                    Toast.fail('有附件正在上传，请稍候')
                    return
                }

                if (value.status === 'done') {
                    fileUrls.push(value.picUrl)
                }
            })
        }
        // const stuList = [], teacherList = []
        // if (!isObjEmpty(this.checkNodes)) {
        //     this.checkNodes.forEach((node, index) => {
        //         if (node.value.startWith('0')) {
        //             teacherList.push(node.userId)
        //         } else if (node.value.startWith('2')) {
        //             stuList.push(node.userId)
        //         }
        //     })
        // }

        const paramObj = {
          /*  notifyTitle: announceTitle,
            notifyType: 3,
            notifyDetails: announceContent,
            notifyCreator: this.props.userInfo.user.userFunId,
            notifyStatus: 1,
            notifyFiles: JSON.stringify(fileUrls),
            notifyRemarks: '',*/
            // notifyTeacher: JSON.stringify(teacherList),
            // notifyStu: JSON.stringify(stuList),

            notify_title:announceTitle,
            notify_details:announceContent,
            notify_status:1,
            notify_creator:this.props.userInfo.user.userFunId,
            creator:this.props.userInfo.user.userName,
            notify_files:JSON.stringify(fileUrls)
        }

        console.log(paramObj)

        this.isRequesting = true
        Toast.loading('正在发布...', 0)
        fetchPostObj(API.NOTIFY_CREATE,
            JSON.stringify(paramObj),
            {"Content-Type": 'application/json;charset=UTF-8'}).then(response => {
            Toast.hide()
            Toast.success('发布成功', 1)
            clearListState()()

            this.setState({
                announceTitle: '',
                announceContent: '',
                fileList: []
            })
            this.backTask = setTimeout(() => {
                this.props.history.goBack()
            }, 1000)
        }).catch(error => {
            this.isRequesting = false
            Toast.hide()
            if (typeof error === 'string') {
                Toast.fail(error, 2)
            } else {
                Toast.fail('请求异常', 2)
            }
        })
    }

    onTargetFocus = (e) => {
        if (isObjEmpty(this.state.targetData)) {
            this.getOrganization()
        }
    }

    onTargetChange = (value, label, checkNodes, count) => {
        this.checkNodes = checkNodes
        this.setState({
            targetList: value,
            targetCount: count
        });
    }

    titleChange = e => {
        this.setState({
            announceTitle: e.target.value
        })
    }

    contentChange = e => {
        this.setState({
            announceContent: e.target.value
        })
    }

    beforeUpload = (file, fileList) => {

    }

    handleChange = fileList => {
        if (fileList) {
            this.setState({fileList})
        }
    }
}

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

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

export default connect(mapStateToProps, mapDispatchToProps)(AnnounceRelease)