import React, { Component } from "react";
import { Button,Message } from "antd";
import API from "@/api";
import { baseMatch, perMatch } from "./matchData";
import { backgroundOptions } from "@/data";
import "./index.scss";
import store from "@/store";

export default class UploadResume extends Component {
    state={
        fileName:''
    }
    getOptionsRegStr(options,key){
        let regStr = options.reduce((accumulator, cur) => {
            if(key==='department') return `${accumulator.name || accumulator}|${cur.name}`;
            else return `${accumulator}|${cur}`;
        });

        return "(" + regStr + ")+";
    }
    getMatchRegs(){
        return {
            phone: /1(3|4|5|7|8)\d{9}/i,
            email: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/i,
            department: this.getOptionsRegStr(store.departmentList,'department'),
            education: this.getOptionsRegStr(backgroundOptions,'education'),
            time: /(\d)+((-|—|至)(\d+))?/i,
            sex: /男|女/i,
            sallary: /(\d)+k(-(\d+)k)?/i,
            age:/(\d+)岁/
        };
    }
    //加强匹配
    enhanceMatch(cont, info, perInfo) {
        this.matchBase(cont, info, perInfo);
        this.matchEdu(cont, info, perInfo);
    }
    matchBase(cont, info, perInfo) {
        let matches = this.getMatchRegs()
        let checks = ['phone','email','department','sex','sallary','age']

        for (let i =0;i<checks.length;i++) {
            let key = checks[i]
            let res = cont.match(matches[key]);
            if (!res) continue
            if(key==='age'){perInfo.dateOfBirth=(new Date()).getFullYear()-res[0].replace('岁','')}
            else info[key] = res[0];
        }
    }
    matchEdu(cont, info, perInfo) {
        if (!info.edu) return;
        let matches = this.getMatchRegs()
        let checks = ['education','time']
        let eduExperience = {};
        
        for (let i =0;i<checks.length;i++) {
            let key = checks[i]
            let res = info.edu.match(matches[key]);
            if (!res) continue;
            switch (key) {
                case "education":
                    eduExperience[key] = backgroundOptions.indexOf(res[0]);
                    break;
                case "time":
                    let arr = res[0].split(/-|—|至/);
                    eduExperience["startDate"] = arr[0];
                    arr[1] && (eduExperience["endDate"] = arr[1]);
                    break;
                default:
                    break;
            }
        }

        let arr = info.edu.split(/学院|学校/);
        eduExperience.school = arr[0];
        if (arr[1]) {
            let arr2 = arr[1].split(/专业|技术/);
            eduExperience.major = arr2[0];
        }

        info.eduExperience[0] = eduExperience;
    }
    parseResume(cont) {
        cont = cont.replace(/↵|\s/g, "");
        let regStr =
            Object.keys(baseMatch).join("|") +
            "|" +
            Object.keys(perMatch).join("|");
        let reg = new RegExp("(" + regStr + ")+");
        let contArr = cont.split(reg);
        let info = {
                eduExperience: [
                    {
                        education: 0
                    }
                ]
            },
            perInfo = {};

        for (let i = 0; i < contArr.length - 1; i++) {
            let item = contArr[i];
            if (!item) continue;

            if (perMatch[item]) {
                !this.props.info.personalInfo[perMatch[item]] && (perInfo[perMatch[item]] = contArr[i + 1])
            } else if (baseMatch[item]) {
                !this.props.info[baseMatch[item]] && (info[baseMatch[item]] = contArr[i + 1])
            }
            item && console.log(item);
        }
        this.enhanceMatch(cont, info, perInfo);
        info.personalInfo = perInfo;
        this.props.transferMsgState(info);
        console.log("info",info,perInfo)
    }

    async uploadResume(files) {
        let curFile = files[0]

        if(!/\.(txt|docx|doc|pdf)$/.test(curFile.name)){
            Message.error('仅支持*.docx,.doc,txt,pdf格式文件上传')
            return
        }

        const isLt2M = curFile.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            Message.error("上传简历大小必须小于2M");
        }

        this.setState({'fileName':curFile.name})

        let formData = new FormData();
            formData.append("filedata", curFile);

            this.props.transferMsgState({resumeData:formData});
            try {
                let {data} = await API.upload.upLoadResume(formData);
                console.log("upLoadResume data",data)
                this.parseResume(data);
            } catch (e) {
                console.log(e);
            }
    }

    render() {
        return (
            <div className="upload-resume">
                <div className="btn-upload">
                    <Button type="primary" size="small">
                        简历上传
                    </Button>
                    <input
                        type="file"
                        onChange={e => {
                            this.uploadResume(e.target.files);
                        }}
                    />
                </div>
                <p className="tip">
                    {
                        (this.state.fileName && `（已选择${this.state.fileName}）`)  ||
                        (this.props.info.resume && <span>（已上传<a href={this.props.info.resume} target={'_blank'}>简历</a>）</span>)
                    }
                    支持*.docx,doc,txt,pdf格式
                </p>
            </div>
        );
    }
}
