// 新增报名页面
import React, { Component } from 'react';
import style from 'styled-components';
import moment from 'moment';
import Uploader from '../../../../components/form/upload/Uploader';
import { connect } from 'dva';
import {
  Breadcrumb,
  Alert,
  Form,
  Row,
  Col,
  Input,
  Table,
  message,
  Button,
  Modal,
  Checkbox,
  Upload,
  Icon
} from 'antd';
import { Link } from 'dva/router';
import {
  // adapt_validateExistsPersonApply,
  adapt_trainAdaptApplyPersonApply, // 岗前新增报名
} from '../../../../services/bkt/apis';
import {
  getBayGwsyxBaseInfo,
  getBayBaseInfo,
  publicCommonFileUploadFile
} from '../../../../services/api';
import PSelect from '../../../../components/Pro/PSelect';
import { withRouter } from 'dva/router';
import { gup } from '../../../../utils/utils';
import $perModal from '../../../../utils/modal/perModal';
// import ImageFormItem from './ImageFormItem';
import QCertificate from './QCertificate';
import ContranctModal from './ContranctModal';
import { formItemLayout, formLayout, formLayout1 } from './formLayout';
import contranctCol from './contranctCol';

@connect(state => ({
  companyInfo: state.global.companyInfo
}))
@Form.create()
@withRouter
export default class AddCertificate extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      isAddOrEdit: true, //编辑或者是新增页面（true是新增，false是编辑，默认是新增页面）
      perInfo: {},  //saas返回的人员信息（保安资格证信息）
      buttonStatus: false, //提交按钮是否置灰
      clicked: false,  //按钮是否点击，点击以后校验字段
      key: 0, //用来重置图片的路径用
      // contractList: [],
      // 合同更新
      forceUpdate: false,
      // 合同列表模态框
      contractModal: false,
      // 选中的合同id
      comContractList: [],
      perId: '', //选中的人员id

      checked: false,  //是否勾选报名承诺,没有勾选不让提交

      fileList: [], //社保缴费凭证
    };
  }
  componentWillMount() {
    const perId = gup('id');
    if (perId) {
      this.setState({
        isAddOrEdit: false
      });
    }
    this._getAgentInfo();
  }
  componentDidMount() {

  }

  // 获取代理人信息
  _getAgentInfo = () => {
    return getBayBaseInfo().then(res => {
      this.setState({
        agentInfo: res.data
      });
    })
  }
  //提交（跟提交并添加）
  _submit = (e, type) => {
    this.setState({
      clicked: true
    });
    e && e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (err) return;

      const { perId } = this.state;
      if (!perId) {
        Modal.error({
          title: '请先选择人员',
          okText: '确定'
        });
        return;
      }
      const { comContractId } = this.state.comContractList[0] || {};
      if (!comContractId) {
        Modal.error({
          title: '需关联一份有效期为1年以上的合同。',
          okText: '确定'
        });
        return;
      }
      values.perCerId = this.state.perInfo.perCerId;
      values.perId = perId;
      values.comContractId = comContractId;
      this.setState({ buttonStatus: true });
      adapt_trainAdaptApplyPersonApply({ data: values }).then(res => {
        this.setState({
          buttonStatus: false
        });
        // 提交并继续提交
        if (type == 1) {
          Modal.success({
            title: '提交成功！',
            content: '您可以在报名列表查看该人员的报名信息。',
            okText: '继续',
            onOk: () => {
              this.setState({
                comContractList: [],
                perInfo: {},
                perId: ''
              }, () => {
                this.props.form.resetFields();
                this.setState({
                  fileList: [],
                  key: Math.random(),
                  clicked: false
                });
              });
            }
          });
        } else {
          Modal.success({
            title: '提交成功！',
            content: '您可以在报名列表查看该人员的报名信息。',
            okText: '确定',
            onOk: () => {
              this.setState({ clicked: false });
              this.props.history.replace('/PoliceDeclare/adapt');
            }
          });

        }
      }).catch(() => {
        this.setState({
          buttonStatus: false
        });
      });


    });

  }
  //验证手机号码
  _checkPhone = (rule, value, callback) => {
    if (value && !/^1[0-9]{10}$/.test(value)) {
      callback('请输入正确的手机号码！');
    } else {
      callback();
    }
  };
  //验证证件号
  _checkIdCardNo = (rule, value, callback) => {
    const { form } = this.props;
    const cardNoValue = form.getFieldValue('idCardType');
    if (
      cardNoValue === '1' &&
      value &&
      !/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)
    ) {
      callback('请输入正确的身份证号码！');
    } else {
      callback();
    }
  };
  //通过身份证计算出年龄
  // _getAge(idCardNo) {
  //   const len = idCardNo.length;
  //   if (len == 0) {
  //     return '';
  //   } else {
  //     if ((len != 15) && (len != 18))//身份证号码只能为15位或18位其它不合法
  //     {
  //       return '';
  //     }
  //   }
  //   let strBirthday = "";
  //   if (len == 18)//处理18位的身份证号码从号码中得到生日和性别代码
  //   {
  //     strBirthday = idCardNo.substr(6, 4) + "/" + idCardNo.substr(10, 2) + "/" + idCardNo.substr(12, 2);
  //   }
  //   if (len == 15) {
  //     strBirthday = "19" + idCardNo.substr(6, 2) + "/" + idCardNo.substr(8, 2) + "/" + idCardNo.substr(10, 2);
  //   }
  //   //时间字符串里，必须是“/”
  //   var birthDate = new Date(strBirthday);
  //   var nowDateTime = new Date();
  //   var age = nowDateTime.getFullYear() - birthDate.getFullYear();
  //   //再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
  //   if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) {
  //     age--;
  //   }
  //   return age;
  //   // if(idCardNo){
  //   //   const date = new Date();
  //   //   const year = date.getFullYear(); 
  //   //   const birthday_year = parseInt(idCardNo.substr(6,4));
  //   //   const userage= year - birthday_year;
  //   //   return userage
  //   // }else{
  //   //   return ''
  //   // }    
  // }
  render() {
    const { getFieldDecorator,
      setFieldsValue,
      getFieldValue
    } = this.props.form;
    const columns = contranctCol.call(this);
    columns.push({
      title: '操作',
      dataIndex: 'op',
      key: 'op',
      render: () => {
        return (
          <a onClick={() => {
            this.setState({
              comContractList: []
            });
          }}>移除关联</a>
        )
      }
    });

    return (
      <Box style={{ margin: '16px 0 8px 24px' }}>
        <Breadcrumb>
          <Breadcrumb.Item>
            <Link to="/PoliceDeclare/adapt">报名记录</Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            {this.state.isAddOrEdit ? '新增报名' : '修改报名'}
          </Breadcrumb.Item>
        </Breadcrumb>
        <Alert
          message={
            <div style={{ color: '#333' }}>
              {/* <span>
                1、请根据页面提示完成报名信息录入，若报名数量较多的，可通知相应保安员通过App自行报名，减少管理员工作量；
              </span>
              <br /> */}
              <span>
                人员若存在待提交/待审批/审批中/审批通过的报名记录，则无法再重新报名；审核不通过的需要重新提交报名申报。
              </span>
            </div>
          }
          type="warning"
          showIcon
          style={{ marginBottom: 15, marginTop: 10 }}
        />
        {/* form表单 */}
        <Form style={{ paddingRight: 15 }}>
          <div className="basic_container">
            <h3>报名基础信息</h3>
            <Row gutter={16}>
              <Col span={7}>
                <Form.Item {...formItemLayout} label="所属企业">
                  <Input
                    placeholder="请输入"
                    // maxLength={30}
                    value={this.props.companyInfo.comName}
                    disabled
                  />
                </Form.Item>
              </Col>
              <Col span={7} >
                {
                  !this.state.perId &&
                  <Form.Item
                    extra={<span style={{ color: 'orange' }}>
                      请从组织架构选择人员。每人仅可提交一次报名记录。
                    </span>}
                    {...formItemLayout} label={<em style={{ paddingLeft: -10 }}>
                      <span style={{ color: '#f5222d' }}>*</span>
                      选择人员</em>}>
                    {getFieldDecorator('perId', {
                      // rules: [
                      //   {
                      //     // required: true,
                      //     message: '请先选择人员'
                      //   }
                      // ]
                    })(
                      <Input
                        placeholder="点击选择人员"
                        maxLength={30}
                        readOnly
                        onClick={() => {
                          $perModal({
                            type: 'radio',
                            onOk: (values, close) => {
                              const { 
                                // idCardNo, 
                                perId } = values[0];
                              getBayGwsyxBaseInfo({ perId }).then((res) => {
                                this.setState({
                                  perId
                                });
                                setFieldsValue({
                                  fullName: res.data.name,
                                  mobile: res.data.mobilePhone,
                                  idCardNo: res.data.idCardNo
                                });
                                close();
                              });
                              // const age = this._getAge(idCardNo);
                              // if (age === '') {
                              //   return message.warning("该人员信息不完整")
                              // }
                              // if ((age > 19 || age == 19) && (age < 60 || age == 60)) {
                                
                              // } else {
                              //   message.error("根据监管要求，保安等级证报名人员年龄要在19~60（含）之间。")
                              // }
                            }
                          });
                        }}
                      />
                    )}
                  </Form.Item>
                }
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={7}>
                <Form.Item {...formItemLayout} label="姓名">
                  {getFieldDecorator('fullName', {
                    initialValue: this.state.perInfo.name,
                    rules: [
                      {
                        required: true,
                        message: '请输入姓名'
                      }
                    ]
                  })(<Input placeholder="请输入" disabled={true} />)}
                </Form.Item>
              </Col>
              <Col span={7} >
                <Form.Item {...formItemLayout} label="手机号码">
                  {getFieldDecorator('mobile', {
                    initialValue: this.state.perInfo.mobilePhone,
                    rules: [
                      {
                        required: true,
                        message: '请输入手机号码'
                      }
                    ]
                  })(<Input placeholder="请输入" disabled={true} />)}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={7}>
                <Form.Item {...formItemLayout} label="身份证号">
                  {getFieldDecorator('idCardNo', {
                    initialValue: this.state.perInfo.idCardNo,
                    rules: [
                      {
                        required: true,
                        message: '请输入身份证号'
                      }
                    ]
                  })(<Input placeholder="请输入" disabled={true} />)}
                </Form.Item>
              </Col>
              <Col span={7} >
                <Form.Item {...formItemLayout} label="户籍类型">
                  {getFieldDecorator('residentType', {
                    initialValue: '',
                    rules: [
                      {
                        required: true,
                        message: '请选择'
                      }
                    ]
                  })(<PSelect style={{ width: '100%' }} type="residentType" />)}
                </Form.Item>
              </Col>

            </Row>

            <Row gutter={16}>
              <Col span={7} >
                <Form.Item {...formItemLayout} label="户籍所在地">
                  {getFieldDecorator('residentPlaceType', {
                    initialValue: this.state.perInfo.education,
                    rules: [
                      {
                        required: true,
                        message: '请选择文化程度'
                      }
                    ]
                  })(<PSelect style={{ width: '100%' }} type="residentPlaceType" />)}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={14}>
                <Form.Item {...formLayout} label="户籍地址" extra={<span style={{ color: 'orange', display: 'block' }}>
                  注：地址信息请勿重复填写省市区，以免证书打印的时候出现重复。
                    </span>}>
                  {getFieldDecorator('householdAddress', {
                    initialValue: this.state.perInfo.residenceAddress,
                    rules: [
                      {
                        required: true,
                        message: '请输入'
                      }
                    ]
                  })(
                    <Input style={{ width: '100%' }} />
                  )}
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={14}>
                <Form.Item {...formLayout} label="现住地址" extra={<span style={{ color: 'orange', display: 'block' }}>
                  注：地址信息请勿重复填写省市区，以免证书打印的时候出现重复。
                    </span>}>
                  {getFieldDecorator('actualAddress', {
                    initialValue: this.state.perInfo.domicileAddress,
                    rules: [
                      {
                        required: true,
                        message: '请输入'
                      }
                    ]
                  })(
                    <Input style={{ width: '100%' }} />
                  )}
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={14} style={{ marginBottom: 20 }}>
                <Form.Item style={{ marginLeft: 34 }}>
                <span><em style={{ color: '#f5222d', marginRight: 4 }}>*</em>该人员在本企业连续3个月及以上社保缴费凭证:</span>
                {getFieldDecorator('socialSecurityProveUrl', {
                  // initialValue: this.state.perInfo.socialSecurityProveUrl,
                  initialValue: 'https://bcxin-saas-test.obs.cn-north-1.myhuaweicloud.com:443/upload%2F2020-04-27%2F1587950933805738476.docx',
                  rules: [
                    {
                      required: true,
                      message: <span style={{marginLeft: 78}}>请上传该人员在本企业连续3个月及以上社保缴费凭证</span>
                    }
                  ]
                })(
                 <Uploader 
                  suffix={'doc,docx,pdf,zip,rar'} 
                  /> 
                )}
                </Form.Item>
              </Col>
            </Row>

            {/* test end */}

            <QCertificate perInfo={this.state.perInfo} />


            <h3>合同信息  <Button
              onClick={() => {
                const { perId } = this.state;
                if (!perId) {
                  return Modal.error({ title: '您还没有选择人员！', content: '请选择人员', okText: '确定' });
                }
                this.setState({
                  contractModal: true
                });
              }}
              type="primary" style={{ margin: '0 15px' }}>关联合同</Button>
              <span style={{ color: 'orange', fontSize: 14 }}>
                请关联一份有效期为1年以上且有效状态的合同；合同附件必须有员工本人亲自签名的页面，对因劳动合同真实性 （如非本人签署）问题导致的补贴申请问题由企业自行承担责任和损失，审计出现问题的追回补贴资金并接受相应处罚。
              </span>
            </h3>
            <ContranctModal
              perId={this.state.perId}
              visibale={this.state.contractModal}
              onSelect={comContractList => {
                this.setState({
                  comContractList
                });
              }}
              onClose={() => {
                this.setState({
                  contractModal: false
                });
              }}
            />
            <NotFootTable>
              <Table
                dataSource={this.state.comContractList} footer={null} columns={columns}
              />
            </NotFootTable>

            <h3>报名承诺</h3>
            <Row gutter={16} style={{ marginBottom: 20 }}>
              <Col span={20}>

                <span style={{
                  color: '#f5222d', marginLeft: '2em',
                  // text-indent  
                }}>*</span>
                <Checkbox onChange={e => {
                  this.setState({
                    checked: e.target.checked
                  });
                }}>
                  我司（ <span style={{ color: '#F59A23' }}>{this.props.companyInfo.comName}</span> ）承诺，由我司报名代理人
              {this.state.agentInfo && getFieldDecorator('agentName', {
                  initialValue: this.state.agentInfo.name || '',
                  rules: [
                    {
                      required: true,
                      message: '请输入姓名'
                    }
                  ]
                })(
                  <Input style={{ width: 150, border: (this.state.clicked && !getFieldValue('agentName')) ? '1px solid #f5222d' : '1px solid #d9d9d9' }} type="text" placeholder="请输入姓名" />
                )}
                （
              {this.state.agentInfo && getFieldDecorator('agentIdCardNo', {
                  initialValue: this.state.agentInfo.idCardNo || '',
                  rules: [
                    {
                      required: true,
                      message: '请输入身份证号'
                    },
                    {
                      validator: this._checkIdCardNo
                    }
                  ]
                })(
                  <Input style={{ width: 200, border: (this.state.clicked && !getFieldValue('agentIdCardNo')) ? '1px solid #f5222d' : '1px solid #d9d9d9' }} type="text" placeholder="请输入身份证号" />
                )}
                ，
              {this.state.agentInfo && getFieldDecorator('agentPhone', {
                  initialValue: this.state.agentInfo.mobilePhone || '',
                  rules: [
                    {
                      required: true,
                      message: '请输入手机号码'
                    },
                    { validator: this._checkPhone }
                  ]
                })(
                  <Input style={{ width: 150, border: (this.state.clicked && !getFieldValue('agentPhone')) ? '1px solid #f5222d' : '1px solid #d9d9d9' }} type="text" placeholder="请输入手机号码" />
                )}
                ）
                提交的报名信息真实有效，对因填报信息错误造成不符合培训及补贴申报条件的，由本企业自行承担相应责任和损失。
                </Checkbox>

              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={20}>
                <div className="sumbitButtom" style={{ textAlign: 'center' }}>
                  <Button
                    type="primary"
                    style={{ margin: '0 20px' }}
                    disabled={this.state.buttonStatus || !this.state.checked}
                    onClick={(e) => {
                      this._submit(e, 1)
                    }}
                  >
                    提交并继续添加
                  </Button>
                  {/* <Button
                    type="primary"
                    style={{ margin: '0 20px' }}
                    disabled={this.state.buttonStatus}
                    onClick={() => {
                      this.setState({
                        buttonStatus: true
                      });
                      this._submit();
                    }}
                  >
                    暂存
                  </Button> */}
                  <Button
                    type="primary"
                    disabled={this.state.buttonStatus || !this.state.checked}
                    style={{ margin: '0 20px' }}
                    onClick={this._submit}
                  >
                    提交
                  </Button>
                </div>
              </Col>
            </Row>
          </div>
        </Form>
      </Box>
    );
  }
}

const Box = style.div`{
  .import_salary{
            margin:16px 0 8px 24px;
        }
  .miniLabelWidth .ant-form-item-label{
            width:10%;
        }
  .noUpload{
    .anticon - plus,.ant - upload - text{
            display: none;
        }
      }
    }`;
const NotFootTable = style.div`
  .ant-table-pagination{
    display:none;
  }
`;