import React, { Component } from "react";
import { Divider, Button, Modal, message } from "antd";
import EduExperienceItem from "./EduExperienceItem";
import WorkExperience from "./WorkExperience";
import axios from "axios";
import { getImageUrl, getUploadActionUrl } from "educoder";
import qs from "qs";
import { Link } from "react-router-dom";
import Nav from "../util/Nav";
class ResumeDetails extends Component {
  constructor(props) {
    super(props);
    this.state = {
      resumeData: {
        name: "",
        sex: "",
        user_name: "",
        logo_url: "",
        mobile: "",
        age: 0,
        last_edu_1: "",
        last_edu_2: "",
        job_position: [],
        job_city: [],
        city: [],
        salary: "",
        job_category: "",
        education: [],
        experience: [],
        evaluate: "",
        attachment_url: "",
        attachment_name: "",
        work_year: "",
      },
      modalVisible: false,
    };
  }
  componentDidMount() {
    const { user } = this.props;
    if (user && !user.profile_completed) {
      this.setState({
        modalVisible: true,
        okText: "立即完善",
        modalContent: "您需要去完善您的个人资料，才能使用此功能",
        onOk: () => {
          this.props.history.push("/account/profile/edit");
        },
        // cancelText: "稍后完善",
        // onCancel:()=>{
        //   this.props.history.push("/");
        // }
      });
    } else {
      this.fetchResumeDetail();
    }
  }
  fetchResumeDetail = () => {
    let url;
    const { id } = qs.parse(this.props.location.search.substr(1));
    // 带ID的为招聘者查看求职者详情，请求不同的接口，不带id的直接请求用户的简历详情
    if (id) {
      url = `/resumes/${id}/preview.json`;
    } else {
      url = `/users/resume.json`;
    }
    axios
      .get(url)
      .then((response) => {
        if (response.data.status === -2) {
          this.setState({
            modalVisible: true,
            okText: "创建简历",
            modalContent: "暂无简历，请新建简历",
            onOk: () => {
              this.props.history.push("/recruitment/addresume");
            },
            cancelText: "取消",
            onCancel:()=>{
              this.props.history.push("/");
            }
          });
          // Modal.info({
        } else {
          if (url === `/users/resume.json`) {
            this.setState({
              resumeData: response.data,
            });
          } else {
            this.setState({
              resumeData: response.data.user,
            });
          }
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };
  updateResume = (attachmentId) => {
    const url = "/users/update_resume.json";
    const data = {
      attachment_id: attachmentId,
    };
    axios
      .put(url, data)
      .then((response) => {
        console.log(response);
        if (response.status === 200) {
          this.fetchResumeDetail();
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };
  render() {
    //发布职位权限 跟招聘列表的一样
    let authJobs = false;
    if (this.props.user) {
      const { admin, business, is_teacher, identity } = this.props.user;
      authJobs = admin || business || is_teacher || identity === "professional";
    }
    const search = this.props.location.search.substr(1);
    const { id, from } = qs.parse(search);
    //有权限且是跳转过来查看详情的，hasAuth=true ，展示查看简历按钮和职位名称
    this.hasAuth = authJobs && id;
    const { resumeData } = this.state;
    const {
      name,
      sex,
      user_name,
      logo_url,
      age,
      mobile,
      last_edu_1,
      last_edu_2,
      job_position,
      job_city,
      city,
      salary,
      job_category,
      education,
      experience,
      evaluate,
      attachment_name,
      attachment_url,
      work_year,
    } = resumeData;
    const props = {
      accept: ".pdf,.doc,.docx,.ppt,.pptx,.png,.jpg,.jpeg",
      name: "file",
      action: `${getUploadActionUrl()}`,
      headers: {
        authorization: "authorization-text",
      },
      onChange: (info) => {
        if (info.file.status !== "uploading") {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === "done") {
          message.success("上传成功");
          const { id } = info.file.response;
          this.updateResume(id);
        } else if (info.file.status === "error") {
          //message.error(`${info.file.name} file upload failed.`);
        }
      },
      beforeUpload: (file) => {
        const isLt10M = file.size / 1024 / 1024 < 10;
        if (!isLt10M) {
          message.error("简历大小超过10MB!");
        }
        return isLt10M;
      },
    };
    const myNav = (
      <Nav
        breadcrunmb={[<Link to="/recruitment">求职招聘</Link>, "我的简历"]}
        history={this.props.history}
        back={() => this.props.history.goBack()}
      />
    );
    return (
      <div className="clearfix mt25" style={{ marginBottom: 120 }}>
        {this.hasAuth && (
          <div>
            <Nav
              breadcrunmb={[
                <Link to="/recruitment?tab=1">职位管理</Link>,
                <Link
                  to="/"
                  onClick={() => {
                    this.props.history.goBack();
                  }}
                >
                  投递列表
                </Link>,
                "投递者详情",
              ]}
              history={this.props.history}
              back={() => this.props.history.goBack()}
            />
            <div
              className="educontent mt10 pb20 w1200s"
              style={{ background: "#ffffff", padding: 30 }}
            >
              职位名称：{name}
            </div>
          </div>
        )}
        {from && myNav}
        <div
          className="educontent pb20 w1200s"
          style={{ background: "#ffffff", padding: 30, marginTop: 1 }}
        >
          <div className="clearfix color-white">
            {/* src={data && `${getImageUrl('images/'+data.avatar_url)}`} */}
            <p className="myPhoto mr20 fl">
              <img
                alt="头像"
                src={getImageUrl(logo_url)}
                style={{ width: 110, height: 110, borderRadius: "50%" }}
              />
            </p>
            <div className="fl">
              <p className="clearfix mt20">
                {/* {data && data.name} */}
                <span
                  className="task-hide"
                  style={{ maxWidth: "370px", color: "#000000", fontSize: 20 }}
                >
                  {name || user_name}
                </span>
                <span
                  className="task-hide ml30"
                  style={{ maxWidth: "370px", color: "#000000" }}
                >
                  {mobile}
                </span>
                {/*{*/}
                {/*data && is_current == false && data.identity =="学生" ? "" : */}
                {/*<span className="userpost"><label>{data && data.identity}</label></span>*/}
                {/*}*/}
              </p>
              <div
                className="mt20"
                style={{ display: "flex", color: "#888888" }}
              >
                <div className="mr5">{sex}</div>|
                <div className="ml5 mr5">{age}岁</div>|
                <div className="ml5 mr5">{last_edu_1}</div>
                <div className="ml5 mr5">
                  {work_year ? `| ${work_year}年工作经验` : ""}
                </div>
              </div>
            </div>
            <div className="fr">
              <span className="fl mt35 ml60">
                {this.hasAuth ? (
                  <div>
                    <Button
                      style={{
                        backgroundColor: "#4CADFF",
                        color: "#ffffff",
                        display: attachment_url ? "block" : "none",
                      }}
                      size="large"
                      href={attachment_url}
                      target="_blank"
                    >
                      下载附件简历
                    </Button>
                    <div
                      onMouseOver={() => this.setState({ mouseover: true })}
                      onMouseLeave={() => this.setState({ mouseover: false })}
                      style={{
                        display: !attachment_url ? "inline-block" : "none",
                        marginRight: 30,
                        color: this.state.mouseover ? "#a5a5a5" : null,
                        cursor: "default",
                      }}
                    >
                      求职者未上传简历
                    </div>
                  </div>
                ) : (
                  <Link
                    style={{ color: "#4CADFF", marginRight: 30 }}
                    to="/recruitment/editresume"
                  >
                    <i
                      className="iconfont icon-bianji3  mr5"
                      style={{ color: "#4CACFF" }}
                    ></i>
                    编辑
                  </Link>
                )}
              </span>
            </div>
          </div>
        </div>
        <div
          className="educontent mt10 pb20 w1200s"
          style={{ background: "#ffffff", padding: 30 }}
        >
          <div style={{ fontSize: 16, fontWeight: "700", color: "#333333" }}>
            求职意向
          </div>
          <div style={{ display: "flex", marginTop: 30 }}>
            <p style={{ color: "#888888" }}>期望职位：</p>
            <p style={{ color: "#333333", width: 300 }}>
              {job_position ? job_position.join("、") : ""}
            </p>
            <p style={{ color: "#888888", marginLeft: 120 }}>工作城市：</p>
            <p style={{ color: "#333333" }}>
              {job_city ? job_city.join("、") : city ? city.join("、") : ""}
            </p>
          </div>
          <div style={{ display: "flex", marginTop: 15 }}>
            <p style={{ color: "#888888" }}>薪资要求：</p>
            <p style={{ color: "#333333", width: 300 }}>{salary}</p>
            <p style={{ color: "#888888", marginLeft: 120 }}>工作性质：</p>
            <p style={{ color: "#333333" }}>
              {job_category ? job_category.join("、") : ""}
            </p>
          </div>
          <Divider />
          <div style={{ fontSize: 16, fontWeight: "700", color: "#333333" }}>
            教育经历
          </div>
          {education.map((item, index) => (
            <EduExperienceItem
              {...this.props}
              data={item}
              key={item.begin_on + item.end_on + index}
            />
          ))}
          <Divider />
          <div style={{ fontSize: 16, fontWeight: "700", color: "#333333" }}>
            工作经历
          </div>
          {experience.map((item, index) => (
            <WorkExperience
              {...this.props}
              data={item}
              key={item.begin_on + item.end_on + index}
            />
          ))}
          <Divider />
          <div style={{ fontSize: 16, fontWeight: "700", color: "#333333" }}>
            自我评价
          </div>
          <div
            className="mt25 mb25"
            style={{ whiteSpace: "pre-wrap", lineHeight: "2" }}
          >
            {evaluate}
          </div>
          {!this.hasAuth && (
            <div>
              <Divider />
              <div
                style={{
                  width: "100%",
                  fontSize: 16,
                  fontWeight: "700",
                  color: "#333333",
                }}
              >
                附件简历
              </div>
              <div className="mt25">
                {attachment_name ? (
                  <a href={attachment_url} target="_blank" style={{ color: "#4CACFF" }}>
                    <i
                      className="iconfont icon-lianjie"
                      style={{ fontSize: 12, marginRight: 5 }}
                    ></i>
                    {attachment_name}
                  </a>
                ) : (
                  "暂无"
                )}
              </div>
            </div>
          )}
        </div>
        <Modal
          keyboard={false}
          title="提示"
          visible={this.state.modalVisible}
          closable={false}
          footer={null}
          destroyOnClose={true}
          centered={true}
          width="530px"
        >
          <div className="task-popup-content">
            <p className="task-popup-text-center font-16">
              {this.state.modalContent}
            </p>
            <div className="clearfix mt30 edu-txt-center">
             
                <a
                  className="task-btn mr30"
                  onClick={this.state.onCancel}
                  style={{display:this.state.cancelText?'inline-block':'none'}}
                >
                  { this.state.cancelText}
                </a>
              
              <a
                className="task-btn task-btn-orange"
                onClick={this.state.onOk}
              >
                {this.state.okText}
              </a>
            </div>
          </div>
        </Modal>
      </div>
    );
  }
}

export default ResumeDetails;
