
/* *
*@params personApplyId
*@params setParentState
 */
import React, { Component } from 'react';
import { connect } from 'dva';
import { Button, Drawer, Form, Input, Modal, notification, message, Upload, Icon } from 'antd';
import PSelect from '../../../../components/Pro/PSelect';
import {
  publicCommonFileFilePreview, getBayBaseInfo, publicCommonFileUploadFile
} from '../../../../services/api';
import SelectContactByPerId from '../../../../components/contranct/SelectContactByPerId';
import BTable from '../../../../components/Pro/BTable';
import $modal from '../../../../utils/modal';
import $nModal from '../../../../utils/modal/nModal';
import {
  adapt_trainAdaptApplyMaterialApproveReject,
  adapt_trainAdaptApplyDealMaterialApprove,
  adapt_trainAdaptApplyInfo,
  adapt_trainAdaptApplyPersonApplyUpdate
} from '../../../../services/bkt/apis';

const formItemLayout = {
  labelCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 7
    }
  },
  wrapperCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 20
    },
    md: {
      span: 16
    }
  }
};
@connect(state => ({
  companyInfo: state.global.companyInfo
}))
@Form.create()
export default class SubDrawer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      oldPersonApplyId: '',
      comName: this.props.companyInfo.comName,
      info: null,  //申报详情
      refuseModal: false,  //拒绝的弹窗
      refuseReason: '',  //拒绝原因

      editUser: null,  //当前操作人信息

      comContractInfo: null, //修改合同选中的合同信息
      contractModal: false, //合同弹窗

      isEdit: false,
      fileList: [], //社保缴费凭证
    };
  }
  componentWillMount() {
    // this.__getDistrict();
  }
  componentDidMount() { }
  componentWillReceiveProps(nextProps) {
    if (!!nextProps.personApplyId && this.state.oldPersonApplyId != nextProps.personApplyId) {
      this.setState({ oldPersonApplyId: nextProps.personApplyId });
      this._getDetailInfo(nextProps.personApplyId);
      // 重置合同信息
      this.setState({
        comContractInfo: null
      });
    }
  }

  _getDetailInfo = (personApplyId) => {
    adapt_trainAdaptApplyInfo({ data: { personApplyId } }).then(res => {
      this.setState({
        info: res.data,
        fileList: [{
          url: res.data.socialSecurityProveUrl,
          status: 'done',
          name: res.data.socialSecurityProveUrl,
          uid: 1
        }]
      });
    });
  }

  _onSubmit = () => {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this._getUserInfo(() => {
          const materialApprovePerName = this.state.editUser.name;
          const materialApprovePerIdCardNo = this.state.editUser.idCardNo;
          const { personType } = this.state.info;
          const { personApplyId } = this.props;
          const { comContractInfo } = this.state;
          const comContractId = comContractInfo ? comContractInfo.comContractId : this.state.info.comContractId;
          if (!comContractId) {
            return $modal(res.msg, '');
          }
          const data = { ...values, materialApprovePerName, materialApprovePerIdCardNo, personType, personApplyId, comContractId };
          adapt_trainAdaptApplyPersonApplyUpdate({ data }).then(res => {
            $modal(res.msg, '', null, 'success');
            this._getDetailInfo(this.props.personApplyId);
            this.setState({ isEdit: false });
          });
        });
      }
    });
  }
  // 获取操作人信息
  _getUserInfo = (cb) => {
    if (this.state.editUser) {
      cb();
    } else {
      getBayBaseInfo().then(res => {
        this.setState({
          editUser: res.data
        }, cb);
      })
    }
  }
  render() {
    const { getFieldDecorator, setFieldsValue } = this.props.form;
    const { info, isEdit, comContractInfo } = this.state;
    return (
      <div>
        <Drawer
          title="报名详情"
          width={600}
          destroyOnClose={true}
          visible={!!this.props.personApplyId}
          // visible={true}
          onClose={() => {
            // 关闭弹窗
            this.props.setParentState({
              personApplyId: ''
            });
            this.setState({
              isEdit: false
            });
          }}
        >
          {info &&
            <div>
              <section style={{ display: isEdit ? 'none' : 'block', marginBottom: 15 }}>
                <Button
                  type="primary"
                  disabled={info.applyStatus == '3'} // 已撤销的不能操作
                  style={{ marginRight: 8 }}
                  onClick={() => this.setState({ isEdit: true })}
                >
                  编辑学员报名信息
                </Button>
                <Button
                  type="primary"
                  style={{ marginRight: 8 }}
                  onClick={() => {
                    const { personApplyId } = this.props;
                    const columns = [
                      {
                        title: '时间',
                        dataIndex: 'creationDate',
                        key: 'creationDate',
                      },
                      {
                        title: '操作人姓名',
                        dataIndex: 'modifyName',
                        key: 'modifyName',
                      },
                      {
                        title: '操作人身份证号',
                        dataIndex: 'modifyIdCardNo',
                        key: 'modifyIdCardNo',
                      },
                      {
                        title: '操作记录(点击蓝色文字可查看文件)',
                        dataIndex: 'number',
                        key: 'number',
                        render: (text, record) => {
                          let { content, newValue, oldValue } = record;
                          content = content.replace(/\[旧内容\]/, `<a style="marginRight: 10px;" href="${oldValue}" target="_blank">[旧内容]</a>`);
                          content = content.replace(/\[新内容\]/, `<a style="marginRight: 10px;"  href="${newValue}" target="_blank">[新内容]</a>`);
                          return (
                            <div style={{ maxWidth: 200 }}>
                              <p dangerouslySetInnerHTML={{ __html: content }}></p>
                              {/* <p>
                                {
                                oldValue && oldValue.indexOf('http') >= 0 &&
                                <a style={{marginRight: 10}}  href={oldValue} target="_blank">查看旧值</a>
                              }
                              {
                                newValue && newValue.indexOf('http') >= 0 &&
                                <a style={{marginRight: 10}} href={newValue} target="_blank">查看新值</a>
                              }
                              </p> */}
                            </div>
                          )
                        }
                      },
                    ];
                    const editParms = {
                      personApplyId,
                      pageNumber: 1,  // 页	
                      pageSize: 10  //条目
                    };
                    $nModal({
                      title: "修改记录",
                      footer: null,
                      width: 800,
                      content: (
                        <BTable
                          style={{ marginTop: 10 }}
                          columns={columns}
                          url="adapt_trainAdaptApplyInfoModifyLog"
                          pageParm={editParms}
                          // pageParm={this.state.editParms}
                          dateChange={(e) => { }}
                        />
                        // <TableContainer>
                        //   <Table
                        // columns={}
                        //     dataSource={this.state.editList}
                        //     // url="trainGradeApplyInfoModifyLog"
                        //   />
                        // </TableContainer>
                      )
                    });

                  }}
                >
                  修改记录
                </Button>
              </section>
              {
                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('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={!isEdit} style={{ width: '100%' }} type="residentType" />)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="户籍所在地">
                {getFieldDecorator('residentPlaceType', {
                  initialValue: info.residentPlaceType
                })(<PSelect disabled={!isEdit} style={{ width: '100%' }} type="residentPlaceType" />)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="户籍地址">
                {getFieldDecorator('householdAddress', {
                  initialValue: info.householdAddress
                })(<Input disabled={!isEdit} placeholder="" maxLength={30} />)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="现住地址">
                {getFieldDecorator('actualAddress', {
                  initialValue: info.actualAddress
                })(<Input placeholder="" maxLength={30} disabled={!isEdit} />)}
              </Form.Item>
              <Form.Item>
                <span style={{ marginRight: 8 }}>
                  {/* <em style={{ color: '#f5222d', marginRight: 4 }}>*</em> */}
                该人员在本企业连续3个月及以上社保缴费凭证:
              </span>
                {/* <a
                  onClick={() => {
                    if (info.socialSecurityProveUrl) {
                      publicCommonFileFilePreview({
                        url: info.socialSecurityProveUrl,
                        isLoad: '1'
                      })
                        .then(data => {
                          if (data.data) {
                            window.open(data.data);
                          }
                        });
                    } else {
                      notification.warning({
                        message: '该合同未上传附件！',
                        description: '请先上传合同文件，方可查看。'
                      });
                    }
                  }}
                >
                  点击查看
              </a> */}
              {
                !isEdit &&
                  <a
                    style={{ marginLeft: 15 }}
                    href={info.socialSecurityProveUrl}
                    target="_blank"
                    download
                  >
                    点击下载
                </a>
              }

                {getFieldDecorator('socialSecurityProveUrl', {
                  initialValue: this.state.info.socialSecurityProveUrl,
                  rules: [
                    {
                      required: true,
                      message: <span style={{ marginLeft: 78 }}>请上传该人员在本企业连续3个月及以上社保缴费凭证</span>
                    }
                  ]
                })(
                  <Input style={{ display: 'none' }} />
                )}
                {isEdit &&

                  <Upload
                    disabled={!isEdit}
                    showUploadList={true}
                    fileList={this.state.fileList}
                    onChange={info => {
                      const file = info.file;
                      if (!(file.name + '').toLocaleLowerCase().match(/(\.doc)|(\.docx)|(\.pdf)|(\.zip)|(\.rar)/)) {
                        message.error('请上传拓展名为.doc\.docx\.pdf\.zip\.rar的文件!');
                        return;
                      }
                      const formData = new FormData();
                      formData.append('xfile', file.originFileObj);
                      publicCommonFileUploadFile(formData).then(res => {
                        file.url = res.data;
                        file.status = 'done';

                        this.setState({
                          fileList: [file]
                        }, () => {
                          setFieldsValue({ socialSecurityProveUrl: res.data });
                        });
                      }).catch(ex => {
                        console.log(ex);
                      });
                    }}
                    onRemove={() => {
                      this.setState({ fileList: [] }, () => {
                        setFieldsValue({ socialSecurityProveUrl: '' });
                      });
                    }}
                  // beforeUpload={file => {
                  //   console.log(file, '>>>>')
                  // }}
                  >
                    <Button style={{ marginLeft: 10 }} ><Icon type="upload" />上传社保缴费凭证</Button><span style={{ marginLeft: 10 }}>支持拓展名：.doc\.docx\.pdf\.zip\.rar</span>
                  </Upload>
                }
                {/* {getFieldDecorator('contractUrl' , {
                initialValue: info.contractUrl
              })(
                <PFromUpload
                  key={moment().valueOf()}
                  disabled={true}
                  num={1}
                  disabled
                />
              )} */}
              </Form.Item>
              {/* --------------- */}
              <h3>
                合同信息
                {
                  isEdit &&
                  <Button onClick={() => {
                    this.setState({ contractModal: true });
                  }} type="primary" style={{ marginLeft: 10 }}>选择新合同</Button>
                }
              </h3>
              <Form.Item {...formItemLayout} label="合同名称">
                  <Input value={comContractInfo ? comContractInfo.contractName : info.contractName} placeholder="" maxLength={30} disabled />
                </Form.Item>
                <Form.Item {...formItemLayout} label="有效期">
                  <Input value={
                    comContractInfo ?
                      (comContractInfo.effectStartDate ? `${comContractInfo.effectStartDate}~${comContractInfo.effectEndDate}` : '') :
                      (info.effectStartDate ? `${info.effectStartDate}~${info.effectEndDate}` : '')
                  } placeholder="" maxLength={30} disabled />
                </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>
              <section>
                <span style={{
                  color: '#f5222d',
                  // text-indent  
                }}>*</span>
                  我司{info.learnName && <span>（ <span style={{ color: '#F59A23' }}>{info.learnName}</span> ）</span>}承诺，由我司报名代理人{info.agentName}（{info.agentIdCardNo.replace(/(\d{4}).*(\d{3})/, '$1***********$2')},{info.agentPhone}）提交的报名信息真实有效，对因填报信息错误造成不符合培训及补贴申报条件的，由本企业自行承担相应责任和损失。
              </section>
              {
                  (info.materialApproveStatus == '1' || info.materialApproveStatus == '2') &&
                  <section style={{ marginTop: 30 }}>
                    <h3>材料核对记录</h3>
                    <div>
                      <span>核对人：</span>
                      <span>
                        {info.materialApprovePerName}
                        {
                          info.materialApprovePerIdCardNo &&
                          `(${info.materialApprovePerIdCardNo})`
                        }
                      </span>
                    </div>
                    <div>
                      <span>核对时间：</span>
                      <span>{info.materialApproveDate}</span>
                    </div>
                  </section>
                }
            </Form>
          }


          {/* 底部提交按钮 */}
          {
            info &&
            <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={() => {
                  if (isEdit) {
                    this.setState({
                      isEdit: false,
                      comContractInfo: null //重置合同信息
                    });
                    this.props.form.resetFields();

                  } else {
                    // 关闭抽屉
                    this.props.setParentState({
                      personApplyId: ''
                    });
                  }
                }}
              >
                {isEdit ? '取消编辑' : '返回'}
              </Button>
              {
                !isEdit &&
                <>
                  <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 { personApplyId } = this.props;
                              adapt_trainAdaptApplyDealMaterialApprove({ data: { personApplyId, materialApprovePerName, materialApprovePerIdCardNo } }).then(res => {
                                this._getDetailInfo(this.props.personApplyId);
                                // 关闭抽屉
                                this.props.setParentState({
                                  // personApplyId: '',
                                  forceUpdate: true
                                }, () => {
                                  this.props.setParentState({
                                    forceUpdate: false
                                  });
                                });
                                // 提示
                                $modal('提交成功！', '', null, 'success');
                              });
                            }
                            // 获取人员基础信息
                            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>
                </>
              }
              {/* 编辑模式 */}
              {
                isEdit &&
                <>
                  <Button
                    type="primary"
                    disabled={info.applyStatus == '3'} // 已撤销的不能操作
                    style={{
                      marginRight: 8
                    }}
                    onClick={this._onSubmit}
                  >
                    提交修改
                  </Button>
                </>
              }
            </div>
          }

          <Modal
            title="材料核对不通过"
            visible={this.state.refuseModal}
            okText="确定"
            cancelText="取消"
            onCancel={() => {
              this.setState({
                refuseModal: false
              });
            }}
            onOk={() => {
              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;
                  adapt_trainAdaptApplyMaterialApproveReject({ data: { personApplyId, materialApproveFailReason, materialApprovePerName, materialApprovePerIdCardNo } }).then(res => {
                    $modal('提交成功！', '保安公司可查看不通过原因。', null, 'success');
                    this._getDetailInfo(this.props.personApplyId);
                    this.setState({
                      refuseModal: false,
                      refuseReason: ''
                    });
                    this.props.setParentState({
                      personApplyId: '',
                      forceUpdate: true
                    }, () => {
                      this.props.setParentState({
                        forceUpdate: false
                      });
                    });
                  });
                }
                // 获取人员基础信息
                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>
        </Drawer>


        {
          info &&
          <SelectContactByPerId
            perId={info.perId}
            onlySearchPerId="1"
            visibale={this.state.contractModal}
            onSelect={comContractList => {
              this.setState({
                comContractInfo: comContractList[0]
              });
              // this.setState({
              //   comContractList
              // });
            }}
            onClose={() => {
              this.setState({
                contractModal: false
              });
            }}
          />
        }
      </div>
    );
  }
}
