import React, {Component} from 'react'
import './information.scss'
import PhotoInfo from '@/component/PhotoInfo'
import EmploymentInfo from '@/component/EmploymentInfo'
import PersonalInfo from '@/component/PersonalInfo'
import CommunicationInfo from '@/component/CommunicationInfo'
import EducationInfo from '@/component/EducationInfo'
import WorkInfo from '@/component/WorkInfo'
import SelfDescriptionInfo from '@/component/SelfDescriptionInfo'
import Agreement from '@/component/Agreement'
import UploadResume from '@/ui-component/UploadResume'
import { Button,Message,Spin } from 'antd'
import Param from '@/util/param'
import Rule from '@/util/rule'
import fyForm from '@/util/fy'
import store from "@/store";
import {dataURItoBlob} from '@/util'
import API from '@/api'

let originPhoto = {
    idPhoto:"", //证件照
    lifePhoto:"" //生活照
}
export default class Information extends Component {
    constructor(){
        super()
        this.initState()

        window.onbeforeunload=function(e){   
            e=window.event||e;
            e.returnValue=("确定离开当前页面吗？"); 
        }
    }
    state = {
        department : "", //应聘岗位
        name : "",  //姓名
        sallary : "",  //期望薪资
        idPhoto:"", //证件照
        lifePhoto:"", //生活照
        personalInfo: {
            curStatus : 0,  //目前状态
            sex : 1,  //性别[1:男,0:女]
            nation : 0,  //民族
            belief : "",  //宗教信仰
            healthy : "",  //健康状况
            diseases : "",  //重大疾病史
            nativePlace : "",  //籍贯
            politics : 0,  //政治面貌
            marriage : 0,  //婚姻状况
            registration : "",  //户口所在地
            accountCharacter : 0,  //户口性质
            address : "",  //家庭详细住址
            dateOfBirth : null,  //出生日期
            height : null,  //身高
            foreign : "",  //外语及程度
            skillCertificate : "",  //技能证书
            skillType : "",  //职称及类别
            fristWork : null,  //首次参加工作时间
          },
        identity : "",  //身份证号
        phone : "",  //手机号码
        urgentPhone : "",  //紧急联系人[姓名_电话_关系]
        email : "",  //个人邮箱
        eduExperience : [{
            education:0
        }],  //教育经历
        workExperience : {},  //工作经历
        plan: "",  //三年内职业规划
        description: "",  //自我评价
        agree:true,
        npProvince:'北京市',//籍贯-省
        npCity: 0,//籍贯-市
        loading: false,
        resume:"", //简历地址
        resumeData:null
    }

    transferMsg(key,val){
        if(this.state.hasOwnProperty(key)){
            this.setState({
                [key]: val
            })
        }
    }

    transferMsgState(obj){
        if(obj.personalInfo) {
            obj.personalInfo = Object.assign(this.state.personalInfo,obj.personalInfo)
        }
        this.setState(Object.assign(this.state,obj))
    }

    async initState(){
        let userId = store.userId
        
        if(!userId) return
        try {
            let {data} = await API.user.find({userId:userId})
            let assginData = {}
            for(let i in data){
                if(data[i] && this.state.hasOwnProperty(i)){
                    //工作经验
                    if((i==="workExperience" || i==="eduExperience" || i==="personalInfo")) {
                        try {
                            let info = JSON.parse(data[i])
                            assginData[i] = info
    
                            if(i==="personalInfo" && info.nativePlace){
                                let arr = info.nativePlace.split("-")
                                assginData['npProvince'] = arr[0]
                                assginData['npCity'] = arr[1]
                            }
                        } catch (error) {
                            break
                        }
                    } else {
                        assginData[i] = data[i]
                        if(i==="idPhoto" || i=== "lifePhoto" ) originPhoto[i] = data[i]
                    }
                    
                }
            }

            this.setState(Object.assign(this.state,assginData))
        } catch (error) {
            console.log(error)
        }
    }

    getFormRules(){
        let state = this.state

        let rules = {
            department : [state.department,'require'], //应聘岗位
            sallary : [state.sallary,'require',Rule.Reg_Int],    //期望薪资
            idPhoto:[state.idPhoto,'require'], //证件照
            lifePhoto:[state.lifePhoto], //生活照
            name : [state.name,'require'],  //姓名
            personalInfo:[state.personalInfo,this.checkPersonalInfo.bind(this)],
            identity : [state.identity,'require',Rule.Reg_Identity],  //身份证号
            phone : [state.phone,'require',Rule.Reg_Phone],  //手机号码
            email : [state.email,'require',Rule.Reg_Email],  //个人邮箱
            urgentPhone : [state.urgentPhone],  //紧急联系人[姓名_电话_关系]
            eduExperience : [state.eduExperience,this.checkEduExperience.bind(this)],  //教育经历
            workExperience : [state.workExperience],  //工作经历
            plan: [state.plan,'require','length_1-200'],  //三年内职业规划
            description: [state.description,'require','length_1-200'],  //自我评价
            resume : [state.resume]
        }

        return rules
    }

    async checkForm(){
        let state = this.state
        let pInfo = this.state.personalInfo

        if(this.state.loading) return Promise.reject(new Error(""))
        pInfo.nativePlace = `${this.state.npProvince}-${this.state.npCity}`
        this.setState({personalInfo:pInfo})
        
        let rules = this.getFormRules()

        let param = new Param(rules)
        if(!param.checkParams()) {
            return Promise.reject(new Error(param.error))
        }

        if(!state.agree){
            return Promise.reject(new Error("提交资料请同意以上声明"))
        }

        for(let i in originPhoto){
            let imageUrl = this.state[i]
            if(originPhoto[i] !== imageUrl){
                let formData = new FormData();
                formData.append("img", dataURItoBlob(imageUrl));

                try {
                    let res = await API.upload.upLoadImg(formData)
                    if (res.data.code === 0) {
                        originPhoto[i] = res.data.url
                        this.setState({
                            [i]: res.data.url
                        })
                    }else{
                        return Promise.reject(new Error(res.data.msg))
                    }
                } catch (err) {
                    return Promise.reject(err)
                }
            }
        }

        if(this.state.resumeData!==null){
            try {
                let res = await API.upload.upLoadFile(this.state.resumeData);
                this.setState({
                    resume: res.data.url
                })
            } catch (err) {
                return Promise.reject(err)
            }
        }
        return Promise.resolve(true)
    }
    async submitForm(){
        try{
            await this.checkForm()
        }catch(err){
            this.setState({loading:false})
            if(err.message) Message.error(err.message)
            return
        }

        let rules = this.getFormRules()
        let state = this.state
        let submitData = {}
        for(let i in rules){
            if((i==="workExperience" || i==="eduExperience" || i==="personalInfo") && state[i]) {
                //工作经验
                submitData[i] = JSON.stringify(state[i])
            } else {
                submitData[i] = state[i]
            }
        }

        try {
            this.setState({loading:true})
            await API.user.create(submitData)
            Message.success("提交成功")
        } catch (e) {
            Message.error(e.message)
        }
        this.setState({loading:false})
    }

    //校验个人信息
    checkPersonalInfo(){
        let state = this.state
        let mergeInfo = ["curStatus","sex","nation","healthy","diseases","nativePlace","politics","marriage","registration","accountCharacter","address"]

        for(let j=0;j<mergeInfo.length;j++){
            let type = mergeInfo[j]
            let val = state.personalInfo[type] === undefined ? "" : state.personalInfo[type]
            let flag = Rule.Reg_Require.test(val)
            if(!flag) {
                Message.error(`${fyForm[type] || type}不能为空`)
                return false
            }
        }
        return true
    }

    //校验教育经历
    checkEduExperience(){
        let state = this.state
        let mergeInfo =["startDate","endDate","school","education","major","educationBg"]
        
        for(let i=0; i<state.eduExperience.length;i++){
            for(let j=0;j<mergeInfo.length;j++){
                let type = mergeInfo[j]
                let val = state.eduExperience[i][type] === undefined ? "" : state.eduExperience[i][type]
                let flag = Rule.Reg_Require.test(val)
                if(!flag) {
                    Message.error(`${fyForm[type] || type}不能为空`)
                    return false
                }
            }
        }
        return true
    }

    render(){
        return (
            <div className="mod-information">
                <UploadResume
                    transferMsgState={(obj)=>{this.transferMsgState(obj)}} 
                    info={this.state}>
                </UploadResume>
                <EmploymentInfo transferMsg={(key,value)=>{this.transferMsg(key,value)}} info={this.state}></EmploymentInfo>
                <PhotoInfo transferMsg={(key,value)=>{this.transferMsg(key,value)}} info={this.state}></PhotoInfo>
                <PersonalInfo transferMsg={(key,value)=>{this.transferMsg(key,value)}} info={this.state}></PersonalInfo>
                <CommunicationInfo transferMsg={(key,value)=>{this.transferMsg(key,value)}} info={this.state}></CommunicationInfo>
                <EducationInfo transferMsg={(key,value)=>{this.transferMsg(key,value)}} info={this.state}></EducationInfo>
                <WorkInfo transferMsg={(key,value)=>{this.transferMsg(key,value)}} info={this.state}></WorkInfo>
                <SelfDescriptionInfo transferMsg={(key,value)=>{this.transferMsg(key,value)}} info={this.state}></SelfDescriptionInfo>
                <Agreement transferMsg={(key,value)=>{this.transferMsg(key,value)}} info={this.state}></Agreement>
                <Button className="btn-submit" type="primary" size="large" onClick={this.submitForm.bind(this)}>
                    提交{this.state.loading && <Spin />}
                </Button>
            </div>
        )
    }
}