
/* *
*@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 } from 'antd';
import PSelect from '../../../../components/Pro/PSelect';
import { trainGradeApplyInfo } from '../../../../services/bkt/apis';
import { 
  // enterpriseComContractGetComContractById,
  systemPerCerBaseInfoFind,
  publicCommonFileFilePreview 
  } from '../../../../services/api';
import PFromUpload from '../../../../components/Pro/PFromUpload';
import InternshipRecord from './InternshipRecord';
import { $getFormItems } from '../AddCertificate/ImageFormItem';
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 SubDrawer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      comName: this.props.companyInfo.comName,
      info: null,  //申报详情
      // contracInfo: {},  //合同详情
      certInfo: {}, //证书详情
      imgs: [],
      recordShow: false //实习记录的显示
    };
  }
  componentWillMount() {
    // this.__getDistrict();
  }
  componentDidMount() { }
  componentWillReceiveProps(nextProps) {
    if (!!nextProps.personApplyId) {
      this.__getDetailInfo(nextProps.personApplyId);
    }
  }

  __getDetailInfo = (personApplyId) => {
    trainGradeApplyInfo({ data: { personApplyId } }).then(res => {
      this.setState({
        info: res.data
      });
      if (res.data) {
        const { comContractId, perCerId, personType } = res.data;
        // 获取合同信息
        // if (!!comContractId) {
        //   enterpriseComContractGetComContractById({ comContractId }).then(result => {
        //     if (result.data) {
        //       if(typeof result.data.effectStartDate == 'string') {
        //         result.data.effectStartDate = result.data.effectStartDate.split(' ')[0];
        //       }else {
        //         result.data.effectStartDate =  '';
        //       }
        //       if(typeof result.data.effectEndDate == 'string') {
        //         result.data.effectEndDate = result.data.effectEndDate.split(' ')[0];
        //       }else {
        //         result.data.effectEndDate = '';
        //       }
        //       this.setState({
        //         contracInfo: result.data
        //       });
        //     }
        //   });
        // }
        // 获取证书信息
        if (!!perCerId) {
          systemPerCerBaseInfoFind({ perCerId }).then(certRes => {
            if (certRes.data) {
              this.setState({
                certInfo: certRes.data
              });
            }
          });
        }
        // 重组图像文件（传入人员类型得到对应的图片数组）
        // const imgArr = $getFormItems(personType);
        // const avatar = {
        //   label: '两寸蓝底彩照',
        //   fieldsName: 'avatar',
        //   rules: [{
        //     required: true,
        //     message: `两寸蓝底彩照`
        //   }]
        // };
        // imgArr.unshift(avatar);
        const imgArr =[
          {
            label: '两寸蓝底彩照',
            fieldsName: 'avatar',
            rules: [{
              required: true,
              message: `两寸蓝底彩照`
            }]
          },
         {
            label: '身份证人像面',
            fieldsName: 'idCardNoFrontUrl',
            rules: [{
              required: true,
              message: `请上传身份证人像面`
            }]
          },{
            label: '身份证国徽面',
            fieldsName: 'idCardNoBackUrl',
            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
          ]);
        }
        this.setState({
          imgs: rows
        });
      }
    });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { info, certInfo } = this.state;
    return (
      <Drawer
        title="报名详情"
        width={600}
        visible={!!this.props.personApplyId}
        onClose={this.props.onClose}
      // 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('applyStatus', {
                initialValue: info.applyStatus
              })(<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('isMakeUp', {
                initialValue: info.isMakeUp||'0'
              })(<Select disabled style={{ minWidth: 150 }} >
                <Option value="0">否</Option>
                <Option value="1">是</Option>
              </Select>)}
            </Form.Item>
            <Form.Item {...formItemLayout} label="姓名">
              {getFieldDecorator('fullname', {
                initialValue: info.fullname
              })(<Input placeholder="" maxLength={30} disabled={true} />)}
            </Form.Item>

            <Form.Item {...formItemLayout} label="身份证号">
              {getFieldDecorator('identitynumber', {
                initialValue: info.identitynumber
              })(<Input placeholder="" maxLength={30} disabled={true} />)}
            </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>
            {
              info.isMakeUp=='1'&&
              <div><Form.Item {...formItemLayout} label="首次培训学校">
              {getFieldDecorator('trainOrganName', {
                initialValue: info.trainOrganName
              })(<Input placeholder="" maxLength={30} disabled={true} />)}
            </Form.Item><Form.Item {...formItemLayout} label="联系方式">
              {getFieldDecorator('trainOrganPhone', {
                initialValue: info.trainOrganPhone
              })(<Input placeholder="" maxLength={30} disabled={true} />)}
            </Form.Item>
                </div>
            }
            <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>


            {/* --------------- */}
            <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.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>
              {/* {getFieldDecorator('contractUrl' , {
                initialValue: info.contractUrl
              })(
                <PFromUpload
                  key={moment().valueOf()}
                  disabled={true}
                  num={1}
                  disabled
                />
              )} */}
            </Form.Item>

            {/* --------------- */}
            <h3>证书信息</h3>
            <Form.Item {...formItemLayout} label="证书类型">
              {getFieldDecorator('perCerType', {
                initialValue: certInfo.perCerType
              })(<PSelect disabled style={{ width: '100%' }} type="perCerType" />)}
            </Form.Item>
            <Form.Item {...formItemLayout} label="证书编号">
              {getFieldDecorator('cerNo', {
                initialValue: certInfo.cerNo
              })(<Input placeholder="" maxLength={30} disabled={true} />)}
            </Form.Item>
            <Form.Item {...formItemLayout} label="发证机关">
              {getFieldDecorator('licenceOrg', {
                initialValue: certInfo.licenceOrg
              })(<Input placeholder="" maxLength={30} disabled={true} />)}
            </Form.Item>
            <Form.Item {...formItemLayout} label="发证日期">
              {getFieldDecorator('licenceDate', {
                initialValue: certInfo.licenceDate
              })(<Input placeholder="" disabled disabled={true} />)}
            </Form.Item>
            {/* <Form.Item {...formItemLayout} label="培训单位">
              {getFieldDecorator('nation', {
                initialValue: ''
              })(<PSelect type="nation" disabled />)}
            </Form.Item> */}
            {
              certInfo.electronCerUrl && 
              <Form.Item {...formItemLayout} label="电子证">
                <a href={certInfo.electronCerUrl} target="_blank">点击查看</a>
              </Form.Item>
            }
            {
              !certInfo.electronCerUrl && 
              <Form.Item {...formItemLayout} label="电子证">
                
              </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} 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>
          </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>
        </div>
        {
          info &&
          <InternshipRecord
            visible={this.state.recordShow}
            name={info.fullname}
            uid={info.uid}
            onClose={() => {
              this.setState({
                recordShow: false
              });
            }}
          />
        }
      </Drawer>
    );
  }
}
