import React, { useEffect, useState, useCallback } from 'react';
import { Button, Icon, Form, Modal, Input, Select, message } from 'antd';
import Upload from '../../components/Upload';
import { unitType, natureOfWork, highestEducation, positionLevel, professionalType, reviewArea } from '../../static';
import { expertRegister, getCurrentExpert, getFile, expertUpdate } from '../../api';

import './index.scss';
import '../../index.scss';
const Option = Select.Option;

export default Form.create()(({ match, history, showNotification, form, current_user }) => {
  const { getFieldDecorator, validateFields, setFieldsValue } = form;
  const [cancelConfirmValue, setCancelConfirmValue] = useState(false);
  const [submitConfirmValue, setSubmitConfirmValue] = useState(false);
  const [expertRegisterValues, setExpertRegisterValues] = useState();
  const [lastRegister, setLastRegister] = useState();
  const [forbidden, setForbidden] = useState(false);

  const [resumeList, setResumeList] = useState([]);
  const [resumeIds, setResumeIds] = useState();

  const [titleCertList, setTitleCertList] = useState([]);
  const [titleCertIds, setTitleCertIds] = useState();

  const [achievementList, setAchievementList] = useState([]);
  const [achievementIds, setAchievementIds] = useState();

  const [honorList, setHonorList] = useState([]);
  const [honorIds, setHonorIds] = useState();

  const [reload, setReload] = useState();

  const [reviewAreaOne, setReviewAreaOne] = useState();
  const [reviewAreaTwo, setReviewAreaTwo] = useState();
  const [reviewAreaThree, setReviewAreaThree] = useState();

  // 获取列表
  useEffect(() => {
    let params = {};
    getCurrentExpert(params).then(async res => {
      if (res && res.data && res.data.length) {
        let lastRegister = res.data[0];
        if (res.data.length > 1 && res.data[0].status === 1) {
          lastRegister = res.data[1];
        }
        let params = {
          bankAccount: lastRegister.bankAccount || "",
          bankName: lastRegister.bankName || "",
          expertEmail: lastRegister.expertEmail || "",
          expertName: lastRegister.expertName || "",
          expertType: lastRegister.expertType || "",
          graduatedFrom: lastRegister.graduatedFrom || "",
          highestDegree: lastRegister.highestDegree || "",
          idNumber: lastRegister.idNumber || "",
          major: lastRegister.major || "",
          phone: lastRegister.phone || "",
          professionalTitle: lastRegister.professionalTitle || "",
          reviewAreaOne: lastRegister.reviewAreaOne || "",
          reviewAreaTwo: lastRegister.reviewAreaTwo || "",
          reviewAreaThree: lastRegister.reviewAreaThree || "",
          titleRank: lastRegister.titleRank || "",
          workNature: lastRegister.workNature || "",
          workplace: lastRegister.workplace || "",
          workplaceType: lastRegister.workplaceType || "",
        }

        setReviewAreaOne(lastRegister.reviewAreaOne);
        setReviewAreaTwo(lastRegister.reviewAreaTwo);
        setReviewAreaThree(lastRegister.reviewAreaThree);

        setFieldsValue(params);
        setExpertRegisterValues(params);
        setLastRegister(lastRegister);
        setForbidden(lastRegister && lastRegister.status === -1);

        // 回写文件
        if (lastRegister.resume) {
          setResumeList(lastRegister.resumeAttachments);
          setResumeIds(lastRegister.resume);
          
        }

        if (lastRegister.titleCertificate) {
          setTitleCertList(lastRegister.titleCertificateAttachments);
          setTitleCertIds(lastRegister.titleCertificate);
        }

        if (lastRegister.academicAchievements) {
          setAchievementList(lastRegister.academicAchievementsAttachments);
          setAchievementIds(lastRegister.academicAchievements);
        }

        if (lastRegister.honors) {
          setHonorList(lastRegister.honorsAttachments);
          setHonorIds(lastRegister.honors);
        }
      } else if(res && res.message=="未登录"){
        history.push('/403');
      }
      else {
        setForbidden(false);
      }
    });
  }, [reload]);

  function getFiles(ids) {
    let idArr = ids.split(',');
    let requireArr = idArr.map(i => {
      return new Promise((resolve) => {
        getFile(i).then((res) => {
          if (res) {
            res.data && resolve(res.data);
          }
        });
      });
    })
    return Promise.all(requireArr);
  }


  // 上传附件后得到的文件数组
  function uploadResume(fileList, files) {
    setResumeList(fileList);
    setResumeIds(files);
  }

  function uploadTitleCert(fileList, files) {
    setTitleCertList(fileList);
    setTitleCertIds(files);
  }

  function uploadAchievement(fileList, files) {
    setAchievementList(fileList);
    setAchievementIds(files);
  }

  function uploadHonor(fileList, files) {
    setHonorList(fileList);
    setHonorIds(files);
  }


  // form表单公共处理函数
  const helper = useCallback(
    (label, name, rules, widget) => (
      <Form.Item label={label}>
        {getFieldDecorator(name, { rules, validateFirst: true })(widget)}
      </Form.Item>
    ),
    []
  );

  //表单提交
  function expertRegisterSubmit(e) {
    form.validateFields((err, values) => {
      if (!err) {
        setSubmitConfirmValue(true);
        setExpertRegisterValues(values);
      }
    })
  }

  //注册
  function expertRegisterOk() {
    if (expertRegisterValues) {
      let params = {
        bankAccount: expertRegisterValues.bankAccount || "",
        bankName: expertRegisterValues.bankName || "",
        expertEmail: expertRegisterValues.expertEmail || "",
        expertName: expertRegisterValues.expertName || "",
        expertType: expertRegisterValues.expertType || "",
        graduatedFrom: expertRegisterValues.graduatedFrom || "",
        highestDegree: expertRegisterValues.highestDegree || "",
        idNumber: expertRegisterValues.idNumber || "",
        major: expertRegisterValues.major || "",
        phone: expertRegisterValues.phone || "",
        professionalTitle: expertRegisterValues.professionalTitle || "",
        reviewAreaOne: expertRegisterValues.reviewAreaOne || "",
        reviewAreaTwo: expertRegisterValues.reviewAreaTwo || "",
        reviewAreaThree: expertRegisterValues.reviewAreaThree || "",
        titleRank: expertRegisterValues.titleRank || "",
        workNature: expertRegisterValues.workNature || "",
        workplace: expertRegisterValues.workplace || "",
        workplaceType: expertRegisterValues.workplaceType || "",
        resume: resumeIds,
        titleCertificate: titleCertIds,
        academicAchievements: achievementIds,
        honors: honorIds,
        userId: current_user && current_user.user_id,
        status: -1,
      };

      if (lastRegister && [2, 3].includes(lastRegister.status)) {
        expertUpdate({
          ...params,
          id: lastRegister.id
        }).then(res => {
          dealBack(res);
        });
      } else {
        expertRegister(params).then(res => {
          dealBack(res)
        });
      }
    }
  }

  function draft() {
    form.validateFields((err, values) => {
      if (!err) {
        let params = {
          ...values,
          resume: resumeIds,
          titleCertificate: titleCertIds,
          academicAchievements: achievementIds,
          honors: honorIds,
          userId: current_user.user_id,
          status: 3
        };

        if (lastRegister && [2, 3].includes(lastRegister.status)) {
          expertUpdate({
            ...params,
            id: lastRegister.id
          }).then(res => {
            dealBack(res);
          });
        } else {
          expertRegister(params).then(res => {
            dealBack(res)
          });
        }
      }
    })
  }

  function dealBack(res) {
    if (res && res.message && (res.message.indexOf("成功") > -1 || res.message.indexOf("更新") > -1)) {
      message.success("保存成功")
      setSubmitConfirmValue(false);
      setReload(Math.random());
    } else {
      message.error(res && res.message || "保存失败");
    }
  }

  function cancel() {
    if (lastRegister && lastRegister.status === -1) {
      history.go(-1);
    } else {
      setCancelConfirmValue(true);
    }
  }

  return (
    <div className='register_right'>
      {
        lastRegister && lastRegister.status === -1 && <p className='advance checking'>
          <i className="iconfont icon-shijianicon font-15 mr10 ver-middle"></i>您的资料正在审核，请耐心等待！
        </p>
      }
      {
        lastRegister && lastRegister.status === 2 && <p className='advance fail'>
          <i className="iconfont icon-sousuo_shanchuicon font-15 mr10 ver-middle"></i>您提交的资料已被拒绝，请完善资料后重新提交
          {lastRegister.reviewerAdvice && <div className='ml25'>拒绝原因：{lastRegister.reviewerAdvice}</div>}
        </p>
      }
      {
        lastRegister && lastRegister.status === 1 && <p className='advance succeed'>
          <i className="iconfont icon-duigou font-15 mr10 ver-middle"></i>您的资料已审核通过，已成为专家！若修改资料，修改后需要管理员重新审核，审核过程中不会影响您的专家身份
        </p>
      }

      <div className='user-title'>专家资料</div>
      <Form className='register-form'>
        {
          helper('姓名',
            'expertName',
            [{ required: true, message: "姓名不能为空" },
            { max: 20, message: '长度不能超过20个字符' }],
            <Input
              placeholder="请输入您的姓名"
              disabled={forbidden}
            />
          )
        }
        {
          helper('最高学历',
            'highestDegree',
            [{ required: true, message: '请选择最高学历' }],
            <Select disabled={forbidden} placeholder="请选择" dropdownClassName="expert_register">
              {highestEducation.map(item => {
                return <Option key={item.value} value={item.value}>{item.label}</Option>
              })}
            </Select>
          )
        }
        {
          helper('手机号码',
            'phone',
            [{ required: true, message: "手机号码不能为空" },
            {
              validator: (rule, val, callback) => {
                const pattern = /^((\+)?86|((\+)?86)?)0?1[3456789]\d{9}$/;
                if (pattern.test(val)) {
                  callback();
                } else {
                  callback('请输入正确的手机号码！');
                }
              }
            }],
            <Input
              placeholder="请输入您的手机号码"
              disabled={forbidden}
            />
          )
        }
        {
          helper('工作单位',
            'workplace',
            [{ required: true, message: "工作单位不能为空" },
            { max: 50, message: '长度不能超过50个字符' }
            ],
            <Input
              placeholder="请输入您的工作单位"
              disabled={forbidden}
            />
          )
        }
        {
          helper('单位类别',
            'workplaceType',
            [{ required: true, message: "请选择单位类别" }],
            <Select disabled={forbidden} placeholder="请选择" dropdownClassName="expert_register">
              {unitType.map(item => {
                return <Option key={item.value} value={item.value}>{item.label}</Option>
              })}
            </Select>
          )
        }
        {
          helper('工作性质',
            'workNature',
            [{ required: true, message: "请选择工作性质" }],
            <Select disabled={forbidden} placeholder="请选择" dropdownClassName="expert_register">
              {natureOfWork.map(item => {
                return <Option key={item.value} value={item.value}>{item.label}</Option>
              })}
            </Select>
          )
        }
        {
          helper('专业职称',
            'professionalTitle',
            [{ required: true, message: "专业职称不能为空" },
            { max: 50, message: '长度不能超过50个字符' }],
            <Input
              placeholder="请输入您的专业职称"
              disabled={forbidden}
            />
          )
        }
        {
          helper('职称职级',
            'titleRank',
            [{ required: true, message: "请选择职称职级" }],
            <Select disabled={forbidden} placeholder="请选择" dropdownClassName="expert_register">
              {positionLevel.map(item => {
                return <Option key={item.value} value={item.value}>{item.label}</Option>
              })}
            </Select>
          )
        }
        {
          helper('专家类别',
            'expertType',
            [{ required: true, message: "请选择专家类别" }],
            <Select disabled={forbidden} placeholder="请选择" dropdownClassName="expert_register">
              {professionalType.map(item => {
                return <Option key={item.value} value={item.value}>{item.label}</Option>
              })}
            </Select>
          )
        }
        {
          helper('评审领域1',
            'reviewAreaOne',
            [{ required: true, message: "请选择评审领域" }],
            <Select
              disabled={forbidden}
              placeholder="请选择"
              dropdownClassName="expert_register"
              onChange={(value) => { setReviewAreaOne(value) }}
            >
              {reviewArea.map(item => {
                return <Option key={item.value} value={item.value}
                  disabled={item.value === reviewAreaTwo || item.value === reviewAreaThree}
                >{item.label}</Option>
              })}
            </Select>
          )
        }
        {
          helper('评审领域2',
            'reviewAreaTwo', [],
            <Select
              disabled={forbidden}
              placeholder="请选择"
              dropdownClassName="expert_register"
              onChange={(value) => { setReviewAreaTwo(value) }}
            >
              {reviewArea.map(item => {
                return <Option key={item.value} value={item.value}
                  disabled={item.value === reviewAreaOne || item.value === reviewAreaThree}
                >{item.label}</Option>
              })}
            </Select>
          )
        }
        {
          helper('评审领域3',
            'reviewAreaThree', [],
            <Select
              disabled={forbidden}
              placeholder="请选择"
              dropdownClassName="expert_register"
              onChange={(value) => { setReviewAreaThree(value) }}
            >
              {reviewArea.map(item => {
                return <Option key={item.value} value={item.value}
                  disabled={item.value === reviewAreaTwo || item.value === reviewAreaOne}
                >{item.label}</Option>
              })}
            </Select>
          )
        }
        {
          helper('毕业院校',
            'graduatedFrom', [{ max: 50, message: '长度不能超过50个字符' }],
            <Input
              placeholder="请输入您的毕业院校"
              disabled={forbidden}
            />
          )
        }
        {
          helper('院校专业',
            'major', [{ max: 50, message: '长度不能超过50个字符' }],
            <Input
              placeholder="请输入您的专业"
              disabled={forbidden}
            />
          )
        }
        {
          helper('身份证号',
            'idNumber', [{
              validator: (rule, val, callback) => {
                let _IDRe18 = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
                let _IDre15 = /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/
                // 校验身份证：
                if (!val) {
                  callback();
                  return
                }
                if (_IDRe18.test(val) || _IDre15.test(val)) {
                  callback();
                }
                else {
                  callback('请输入正确的身份证号码！');
                }
              }
            }],
            <Input
              placeholder="请输入您的身份证号码"
              disabled={forbidden}
            />
          )
        }
        {
          helper('邮箱地址',
            'expertEmail', [{
              validator: (rule, val, callback) => {
                const pattern = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
                if (!val) {
                  callback();
                  return;
                }
                if (pattern.test(val)) {
                  callback();
                } else {
                  callback('请输入正确的邮箱地址！');
                }
              }
            }],
            <Input
              placeholder="请输入您的常用邮箱地址"
              disabled={forbidden}
            />
          )
        }
        {
          helper('开户银行',
            'bankName', [{ max: 50, message: '长度不能超过50个字符' }],
            <Input
              placeholder="请输入您的开户银行"
              disabled={forbidden}
            />
          )
        }
        {
          helper('银行账号',
            'bankAccount', [{ max: 50, message: '长度不能超过50个字符' }],
            <Input
              placeholder="请输入您的银行卡号"
              disabled={forbidden}
            />
          )
        }
        <Form.Item className="upload-form" label="个人简介">
          <Upload
            load={uploadResume}
            size={100}
            showNotification={showNotification}
            fileList={resumeList}
            disabled={forbidden}
            count={1}
          />
        </Form.Item>
        <Form.Item className="upload-form" label="职称证明">
          <Upload
            load={uploadTitleCert}
            size={100}
            showNotification={showNotification}
            fileList={titleCertList}
            disabled={forbidden}
            count={1}
          />
        </Form.Item>
        <Form.Item className="upload-form" label="学术成果">
          <Upload
            load={uploadAchievement}
            size={100}
            showNotification={showNotification}
            fileList={achievementList}
            disabled={forbidden}
            count={1}
          />
        </Form.Item>
        <Form.Item className="upload-form" label="荣誉称号">
          <Upload
            load={uploadHonor}
            size={100}
            showNotification={showNotification}
            fileList={honorList}
            disabled={forbidden}
            count={1}
          />
        </Form.Item>
        <div className='hint'>提示：个人简介、职称证明、学术成果、荣誉称号都只能上传一个文件，建议上传zip或rar格式的压缩文件</div>
      </Form>
      <div className='buts'>
        {/* 专家： 修改，非专家： 提交 */}
        <Button className="but41_fill mr20" type="primary" disabled={forbidden} onClick={() => expertRegisterSubmit(true)}>{current_user.expert ? '修改' : '提交'}资料</Button>
        {(!lastRegister || lastRegister.status !== 1) && <Button className="but41_border mr20" disabled={forbidden} onClick={draft}>保存资料</Button>}
        <Button className="butE3_border" onClick={cancel}>&nbsp;&nbsp;取&nbsp;&nbsp;消&nbsp;&nbsp;</Button>

        <Modal
          title={`${lastRegister && lastRegister.status === 1 ? '修改' : '提交'}资料`}
          visible={submitConfirmValue}
          onOk={expertRegisterOk}
          onCancel={() => setSubmitConfirmValue(false)}
          wrapClassName="expert_modal submit"
          closeIcon={<Icon className='iconfont icon-guanbi1' />}
        >
          <p className=''>资料提交后无法修改，将等待管理员审核，</p>
          <p className=''>确认{lastRegister && lastRegister.status === 1 ? '修改' : '提交'}？</p>
        </Modal>

        <Modal
          title="提交资料"
          visible={cancelConfirmValue}
          onOk={() => { history.go(-1) }}
          onCancel={() => setCancelConfirmValue(false)}
          wrapClassName="expert_modal"
        >
          <p className='weight_bold warning'>有内容没有保存，确定退出编辑吗？</p>
          <p className='ml30'>退出编辑后，更新的内容不会自动保存</p>
        </Modal>
      </div>
    </div>
  )
})
