
/* *
*@params personApplyId
*@params onClose
*@陕西延安的资格证材料审核页面
 */
import React, { Component } from 'react';
import { connect } from 'dva';
import axios from 'axios';
import moment from 'moment';
import { Button, Drawer, Form, Input, Row, Col, Select, notification, Modal } from 'antd';
import PSelect from '../../../../../components/Pro/PSelect';
import { qualify_applyInfo, qualify_applyDealMaterialApprove, qualify_applyMaterialApproveReject } from '../../../../../services/bkt/qualify';
import {
  // enterpriseComContractGetComContractById,
  systemPerCerBaseInfoFind,
  publicCommonFileFilePreview,
  getBayBaseInfo
} from '../../../../../services/api';
import PFromUpload from '../../../../../components/Pro/PFromUpload';
import $modal from '../../../../../utils/modal';
import InternshipRecord from './InternshipRecord';
const { TextArea } = Input;
const { Option } = Select;
const formItemLayout = {
  labelCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 7
    }
  },
  wrapperCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 20
    },
    md: {
      span: 16
    }
  }
};
const formItemLayout1 = {
  labelCol: {
    span: 24
  },
  wrapperCol: {
    span: 24
  }
};
@connect(state => ({
  companyInfo: state.global.companyInfo
}))
@Form.create()
export default class SXSubDrawer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      comName: this.props.companyInfo.comName,
      info: null,  //申报详情
      // contracInfo: {},  //合同详情
      certInfo: {}, //证书详情
      imgs: [],
      recordShow: false, //实习记录的显示
      hospitalExamProveUrlRows: [],  //体检证明材料
    };
  }
  componentWillMount() {
    // this.__getDistrict();
  }
  componentDidMount() {}
  componentWillReceiveProps(nextProps) {
    if (!!nextProps.personApplyId) {
      this._getDetailInfo(nextProps.personApplyId);
    }
  }
  // 获取操作人信息
  _getUserInfo = (cb) => {
    if (this.state.editUser) {
      cb();
    } else {
      getBayBaseInfo().then(res => {
        this.setState({
          editUser: res.data
        }, cb);
      })
    }
  }
  _getDetailInfo = (personApplyId) => {
    qualify_applyInfo({ data: { personApplyId } }).then(res => {
      this.setState({
        info: res.data
      });
      if (res.data) {
        const { comContractId, perCerId, personType } = res.data;


        // 获取证书信息
        // if (!!perCerId) {
        //   systemPerCerBaseInfoFind({ perCerId }).then(certRes => {
        //     if (certRes.data) {
        //       this.setState({
        //         certInfo: certRes.data
        //       });
        //     }
        //   });
        // }
        const imgArr = [
          {
            label: '一寸免冠白底彩照',
            fieldsName: 'avatar',
            rules: [{
              required: true,
              message: `一寸免冠白底彩照`
            }],
            faceCheckType: res.data.faceCheckType
          },
          {
            label: '身份证人像面',
            fieldsName: 'idCardNoFrontUrl',
            rules: [{
              required: true,
              message: `身份证人像面`
            }]
          },
          {
            label: '身份证国徽面',
            fieldsName: 'idCardNoBackUrl',
            rules: [{
              required: true,
              message: `身份证国徽面`
            }]
          },
          {
            label: '初中以上学历证明原件',
            fieldsName: 'educationUrl',
            rules: [{
              required: true,
              message: `初中以上学历证明原件`
            }]
          },
        ];
        const rows = [];
        const length = Math.ceil(imgArr.length / 3);
        for (let i = 0; i < length; i++) {
          rows.push([
            imgArr[i * 3],
            imgArr[i * 3 + 1],
            imgArr[i * 3 + 2]  //有可能是undefined
          ]);
        }

        const hospitalExamProveUrlRows = [];
        if (typeof res.data.medicalUrl == 'string') {
          const hospitalExamProveUrls = res.data.medicalUrl.split(',').map((url, index) => {
            log(url);
            const fieldsName = 'medicalUrl' + index;
            this.setState({
              info: {
                ...this.state.info,
                [fieldsName]: url
              }
            });
            return {
              label: '',
              fieldsName,
              rules: [{
                required: false,
                message: `医院出具的体检证明`
              }]
            }
          });
          const hospitalExamProveUrlLength = Math.ceil(hospitalExamProveUrls.length / 3);
          for (let i = 0; i < hospitalExamProveUrlLength; i++) {
            hospitalExamProveUrlRows.push([
              hospitalExamProveUrls[i * 3],
              hospitalExamProveUrls[i * 3 + 1],
              hospitalExamProveUrls[i * 3 + 2]  //有可能是undefined
            ]);
          }
        }
        this.setState({
          imgs: rows,
          hospitalExamProveUrlRows
        });
      }
    });
  }
  //不合格原因弹框
  unqualifiedModal = () => {
    Modal.info({
      title: '不合格原因',
      width: 700,
      content: (
        <div>
          {
            this.state.info.checkFailContent ?
              this.state.info.checkFailContent.map(item => {
                return (
                  <div style={{ display: "flex" }}>
                    <p style={{ whiteSpace: "nowrap", marginRight: "5px" }}>{item.date} | </p>
                    <p>{item.content}</p>
                  </div>
                )
              }) : ""
          }
          <div>
            <p>备注：</p>
            <p>（1）学员基本信息不合格需由培训学校通过编辑学员报名信息进行修改更新；</p>
            <p>（2）学习记录不合格需要通知学员登录App重新学习对应的章节课程；</p>
          </div>
        </div>
      ),
      onOk() { },
    });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { info, certInfo } = this.state;
    const { checkAreaCodeValue } = this.props
    return (
      <Drawer
        title="报名详情"
        width={600}
        visible={!!this.props.personApplyId}
        onClose={() => {
          this.props.setParentState({
            personApplyId: ''
          });
        }}
      // visible={true}
      >
        {info &&
          <div>
            {
              info.materialApproveStatus == '2' &&
              <p style={{ color: '#D9001B', marginLeft: 21 }}>材料核对不通过原因: {info.materialApproveFailReason}</p>
            }
            {
              info.approveStatus == '2' &&
              <p style={{ color: '#D9001B', marginLeft: 21 }}>审核不通过原因: {info.approveFailReason}</p>
            }
          </div>
        }
        {/* form表单 */}
        {
          info &&
          <Form style={{ marginBottom: '50px' }} layout="horizontal">
            <Form.Item {...formItemLayout} label="材料核对状态">
              {getFieldDecorator('materialApproveStatus', {
                initialValue: info.materialApproveStatus
              })(<Select disabled style={{ minWidth: 150 }} >
                <Option value="0">核对中</Option>
                <Option value="1">核对通过</Option>
                <Option value="2">核对不通过</Option>
              </Select>)}
            </Form.Item>
            {/* <Form.Item {...formItemLayout} label="背景筛查状态">
              {getFieldDecorator('backgroundStatus', {
                initialValue: info.backgroundStatus || '0'
              })(<Select disabled style={{ minWidth: 150 }} >
                <Option value="0">审核中</Option>
                <Option value="1">正常</Option>
                <Option value="2">关注</Option>
                <Option value="3">申诉通过</Option>
                <Option value="4">申诉不通过</Option>
                <Option value="5">申诉中</Option>
              </Select>)}
            </Form.Item>
            <Form.Item {...formItemLayout} label="申报状态">
              {getFieldDecorator('applyStatus', {
                initialValue: info.applyStatus || '0'
              })(<Select disabled style={{ minWidth: 150 }} >
                <Option value="0">申报中</Option>
                <Option value="1">申报通过</Option>
                <Option value="2">申报不通过</Option>
                <Option value="3">已撤销</Option>
              </Select>)}
            </Form.Item>
            <Form.Item {...formItemLayout} label="缴费状态">
              {getFieldDecorator('orderStatus', {
                initialValue: info.orderStatus
              })(<Select disabled style={{ minWidth: 150 }} >
                <Option value="0">未缴费</Option>
                <Option value="1">已缴费</Option>
              </Select>)}
            </Form.Item> */}
            {
              info.checkStatus == "0" || info.checkStatus == null ? "" :
                <Form.Item {...formItemLayout} label="协会抽查结果">
                  {
                    info.checkStatus == "1" ?
                      <div>
                        <span>合格</span>
                      </div> :
                      <div>
                        <span>不合格</span>
                        <Button type="link" onClick={this.unqualifiedModal}>查看不合格原因</Button>
                      </div>
                  }
                </Form.Item>
            }
            {
              info.examName &&
              <>
                <h3>考试信息</h3>
                <Form.Item {...formItemLayout} label="考试名称">
                  {getFieldDecorator('examName', {
                    initialValue: info.examName
                  })(<Input placeholder="" maxLength={30} disabled={true} />)}
                </Form.Item>
                <Form.Item {...formItemLayout} label="考试时间">
                  {getFieldDecorator('examDate', {
                    initialValue: info.examDate
                  })(<Input placeholder="" maxLength={30} disabled={true} />)}
                </Form.Item>
                <Form.Item {...formItemLayout} label="考试地址">
                  {getFieldDecorator('examAddress', {
                    initialValue: info.examAddress
                  })(<Input placeholder="" maxLength={30} disabled={true} />)}
                </Form.Item>
                <Form.Item {...formItemLayout} label="考试状态">
                  {getFieldDecorator('testStateName', {
                    initialValue: info.testStateName
                  })(<Input placeholder="" maxLength={30} disabled={true} />)}
                </Form.Item>
              </>
            }

            <h3>报名基础信息</h3>
            <Form.Item {...formItemLayout} label="姓名">
              {getFieldDecorator('fullName', {
                initialValue: info.fullname
              })(<Input placeholder="" maxLength={30} disabled={true} />)}
            </Form.Item>
            <Form.Item {...formItemLayout} label="手机号码">
              {getFieldDecorator('mobile', {
                initialValue: info.mobile
              })(<Input placeholder="" maxLength={30} disabled={true} />)}
            </Form.Item>

            {/* <Form.Item {...formItemLayout} label="是否有人口库照片">
                {getFieldDecorator('faceCheckType', {
                  initialValue: info.faceCheckType
                })(
                  info.faceCheckType=='0'?<div>无（请核对图片材料中的一寸白底照片）</div>:<div>有（该人员有人口库照片，无需再核对照片）</div>
                )}
              </Form.Item> */}

            <Form.Item {...formItemLayout} label="身份证号">
              {getFieldDecorator('identitynumber', {
                initialValue: info.identitynumber
              })(<Input placeholder="" maxLength={30} disabled={true} />)}
            </Form.Item>
            {/* <Form.Item {...formItemLayout} label="出生年月">
              {getFieldDecorator('birthDate', {
                initialValue: info.birthDate
              })(<Input placeholder="" maxLength={30} disabled={true} />)}
            </Form.Item> */}
            <Form.Item {...formItemLayout} label="性别">
              {getFieldDecorator('sex', {
                initialValue: info.sex
              })(<Select disabled>
                <Option value="1">男</Option>
                <Option value="2">女</Option>
              </Select>)}
            </Form.Item>
            <Form.Item {...formItemLayout} label="身高(cm)">
              {getFieldDecorator('height', {
                initialValue: info.height
              })(<Input placeholder="" maxLength={30} disabled={true} />)}
            </Form.Item>

            <Form.Item {...formItemLayout} label="文化程度">
              {getFieldDecorator('education', {
                initialValue: info.education
              })(<PSelect disabled type="education" />)}
            </Form.Item>
            <Form.Item {...formItemLayout} label="民族">
              {getFieldDecorator('nation', {
                initialValue: info.nation
              })(<PSelect disabled type="nation" />)}
            </Form.Item>

            <Form.Item {...formItemLayout} label="户籍类型">
              {getFieldDecorator('residentType', {
                initialValue: info.residentType
              })(<PSelect disabled style={{ width: '100%' }} type="residentType" />)}
            </Form.Item>


            {/* <Form.Item {...formItemLayout} label="户籍所在地">
              {getFieldDecorator('residentPlaceType', {
                initialValue: info.residentPlaceType
              })(<PSelect disabled style={{ width: '100%' }} type="residentPlaceType" />)}
            </Form.Item> */}
            <Form.Item {...formItemLayout} label='户籍地址'>
              {getFieldDecorator('householdAddress', {
                initialValue: info.householdAddress
              })(<TextArea placeholder="" disabled={true} autosize={{ minRows: 1, maxRows: 3 }} />)}
            </Form.Item>
            <Form.Item {...formItemLayout} label="现住地址">
              {getFieldDecorator('actualAddress', {
                initialValue: info.actualAddress
              })(<TextArea placeholder="" disabled={true} autosize={{ minRows: 1, maxRows: 3 }} />)}
            </Form.Item>
            {/* <Form.Item {...formItemLayout} label="“本职业工作年限">
              <div style={{display: 'flex', alignItems: 'center'}}>
                {getFieldDecorator('workYear', {
                  initialValue: info.workYear
                })(<Input placeholder="" maxLength={30} disabled={true} />)}
                <span style={{marginLeft: 8}}>年</span>
              </div>
            </Form.Item> */}


            {/* --------------- */}
            {/* {
              !checkAreaCodeValue&&<>
                <h3>合同信息</h3>
                <Form.Item {...formItemLayout} label="合同名称">
                  {getFieldDecorator('contractName', {
                    initialValue: info.contractName
                  })(<Input placeholder="" maxLength={30} disabled={true} />)}
                </Form.Item>
                <Form.Item {...formItemLayout} label="有效期">
                  {getFieldDecorator('effectStartDate', {
                    initialValue: info.effectStartDate?`${info.effectStartDate}~${info.effectEndDate}`:''
                  })(<Input placeholder="" maxLength={30} disabled={true} />)}
                </Form.Item>
                <Form.Item {...formItemLayout} label="合同文件">
                  <a
                    onClick={() => {
                      if (info.contractUrl) {
                        publicCommonFileFilePreview({
                          url: info.contractUrl,
                          isLoad: '1'
                        })
                          .then(data => {
                            if (data.data) {
                              window.open(data.data);
                            }
                          });
                      } else {
                        notification.warning({
                          message: '该合同未上传附件！',
                          description: '请先上传合同文件，方可查看。'
                        });
                      }
                    }}
                  >
                    点击查看
                  </a>
                  <a
                    style={{ marginLeft: 15 }}
                    href={info.contractUrl}
                    target="_blank"
                    download
                  >
                    点击下载
                  </a>
                </Form.Item>
              </>
            } */}


            <h3>图像材料</h3>
            {
              this.state.imgs.map((row, index) => {
                return (
                  <Row gutter={16} key={index}>
                    {
                      row.map((item, idex) => {
                        if (!item) {
                          return '';
                        }
                        return (
                          <Col span={8}>
                            <Form.Item key={idex + moment().valueOf()} style={{ textAlign: 'center' }} {...formItemLayout1} layout="vertical" label={<em style={{ display: 'block', textAlign: 'center', paddingRight: 16 }}>{item.label}</em>}>
                              {getFieldDecorator(item.fieldsName, {
                                initialValue: info[item.fieldsName]
                              })(
                                item.fieldsName == 'avatar' && item.faceCheckType == '1' ?
                                  <img src={require('../../../../../assets/images/person-photo.jpg')} style={{ width: '102px', height: '102px' }}></img>
                                  : <PFromUpload
                                    key={idex + moment().valueOf()}
                                    disabled={true}
                                    types={['image/jpeg', 'image/jpg', 'image/png']}
                                    size={1}
                                    disabled
                                  />
                              )}
                            </Form.Item>
                          </Col>
                        )
                      })
                    }
                  </Row>
                );
              })
            }

            {
              this.state.hospitalExamProveUrlRows.length > 0 &&
              <>
                <h3>县级以上医院出具的体检证明</h3>
                {
                  this.state.hospitalExamProveUrlRows.map((row, index) => {
                    return (
                      <Row gutter={16} key={index + moment().valueOf()}>
                        {
                          row.map((item, idex) => {
                            if (!item) {
                              return '';
                            }
                            return (
                              <Col span={8}>
                                <Form.Item key={idex + moment().valueOf()} style={{ textAlign: 'center' }} {...formItemLayout1} layout="vertical" label={<em style={{ display: 'block', textAlign: 'center', paddingRight: 16 }}>{item.label}</em>}>
                                  {getFieldDecorator(item.fieldsName, {
                                    initialValue: info[item.fieldsName]
                                  })(
                                    <PFromUpload
                                      key={idex + moment().valueOf()}
                                      disabled={true}
                                      types={['image/jpeg', 'image/jpg', 'image/png']}
                                      size={1}
                                      disabled
                                    />
                                  )}
                                </Form.Item>
                              </Col>
                            )
                          })
                        }
                      </Row>
                    );
                  })
                }
              </>
            }
            {/* <section>
                <span style={{
                  color: '#f5222d',
                  // text-indent  
                }}>*</span>
                我司（ <span style={{ color: '#F59A23' }}>{info.learnName||this.props.companyInfo.comName}</span> ）承诺，由我司报名代理人{info.agentName}（{info.agentIdCardNo},{info.agentPhone}）提交的报名信息真实有效，对因填报信息错误造成不符合培训及补贴申报条件的，由本企业自行承担相应责任和损失。
              </section> */}
            {/* <Button style={{marginTop: 15}} type="primary" onClick={() => {
              this.setState({
                recordShow: true
              });
            }}>查看实习记录</Button> */}
            <h3>企业报名人员</h3>
            <Form.Item {...formItemLayout} label="姓名">
              <Input defaultValue={info.agentName} placeholder="" maxLength={30} disabled={true}  />
            </Form.Item>
            <Form.Item {...formItemLayout} label="手机号">
              <Input defaultValue={info.agentPhone} placeholder="" maxLength={30} disabled={true}  />
            </Form.Item>

            <h3>材料核对记录</h3>
            <Form.Item {...formItemLayout} label="核对人">
              {getFieldDecorator('materialApprovePerName', {
                initialValue: info.materialApprovePerName ? info.materialApprovePerIdCardNo ? info.materialApprovePerName + '(' + info.materialApprovePerIdCardNo + ')' : info.materialApprovePerName : ''
              })(<Input placeholder="" maxLength={30} disabled={true} />)}
            </Form.Item>
            <Form.Item {...formItemLayout} label="核对时间">
              {getFieldDecorator('materialApproveDate', {
                initialValue: info.materialApproveDate
              })(<Input placeholder="" maxLength={30} disabled={true} />)}
            </Form.Item>
          </Form>
        }


        {/* 底部提交按钮 */}
        <div
          style={{
            position: 'absolute',
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e8e8e8',
            padding: '10px 16px',
            textAlign: 'left',
            left: 0,
            background: '#fff',
            borderRadius: '0 0 4px 4px'
          }}
        >
          <Button
            style={{
              marginRight: 8
            }}
            onClick={this.props.onClose}
          >
            返回
          </Button>
          {
            info &&
            <>
              <Button
                type="primary"
                disabled={info.materialApproveStatus == '1' || info.materialApproveStatus == '2'} // 0未核对，1通过，2不通过
                style={{
                  marginRight: 8
                }}
                onClick={() => {
                  $modal(
                    '确定提交',
                    '',
                    [{
                      text: '确定', type: 'primary', onPress: () => {
                        const subFun = () => {
                          const materialApprovePerName = this.state.editUser.name;
                          const materialApprovePerIdCardNo = this.state.editUser.idCardNo;
                          const perId = this.state.editUser.perId;
                          const { personApplyId } = this.props;
                          qualify_applyDealMaterialApprove({ data: { personApplyId, materialApprovePerName, materialApprovePerIdCardNo,perId } }).then(res => {
                            this._getDetailInfo(this.props.personApplyId);
                            // 关闭抽屉
                            this.props.updateTable();
                            this.props.onClose();
                            // 提示
                            // $modal('提交成功！', '', null, 'success');
                            notification.success({
                              message: '提交成功！'
                            });
                          });
                        }
                        // 获取人员基础信息
                        this._getUserInfo(subFun);
                      }
                    }, { text: '取消' }],
                    'success'
                  );
                }}
              >
                材料核对通过
              </Button>
              <Button
                type="danger"
                disabled={info.materialApproveStatus == '1' || info.materialApproveStatus == '2'} // 0未核对，1通过，2不通过
                onClick={() => {
                  this.setState({
                    refuseModal: true
                  });
                }}
              >
                材料核对不通过
              </Button>
            </>
          }
        </div>


        <Modal
          title="材料核对不通过"
          visible={this.state.refuseModal}
          okText="确定"
          cancelText="取消"
          onCancel={() => {
            this.setState({
              refuseModal: false
            });
          }}
          onOk={() => {
            // $modal('班级取消成功！','已发送取消通知到相关人员。', null, 'success');

            const materialApproveFailReason = this.state.refuseReason;
            if (materialApproveFailReason) {
              const subFun = () => {
                const materialApprovePerName = this.state.editUser.name;
                const materialApprovePerIdCardNo = this.state.editUser.idCardNo;
                const { personApplyId } = this.props;
                qualify_applyMaterialApproveReject({ data: { personApplyId, materialApproveFailReason, materialApprovePerName, materialApprovePerIdCardNo } }).then(res => {
                  $modal('提交成功！', '保安公司可查看不通过原因。', null, 'success');
                  this.setState({
                    refuseModal: false,
                    refuseReason: ''
                  });
                  this._getDetailInfo(this.props.personApplyId);
                  this.props.updateTable();
                  this.props.onClose();
                });
              }
              // 获取人员基础信息
              this._getUserInfo(subFun);
            } else {
              message.error("请输入不通过原因及修改意见")
            }
          }}
        >
          <label><span style={{ color: 'red' }}>*</span>不通过原因:</label>
          <Input.TextArea value={this.state.refuseReason} onChange={e => {
            this.setState({
              refuseReason: e.target.value
            });
          }} placeholder="请输入不通过原因及修改意见。" />
        </Modal>
        {
          info &&
          <InternshipRecord
            visible={this.state.recordShow}
            name={info.fullname}
            uid={info.uid}
            onClose={() => {
              this.setState({
                recordShow: false
              });
            }}
          />
        }
      </Drawer>
    );
  }
}
