
import React, { Component } from 'react';
import { connect } from 'dva';
// import st from 'styled-components';
import moment from 'moment';
import { Button, Drawer, Form, Input, Row, Col, Select, Modal, message } from 'antd';
// import videojs from 'video.js';
import {
   getBayBaseInfo
} from '../../../../services/api';
import PFromUpload from '../../../../components/Pro/PFromUpload';
import $modal from '../../../../utils/modal';
import {
  grade_trainInternInternLineInfo,
  grade_trainInternLineApprovePass,
  grade_trainInternLineApproveFail,
} from '../../../../services/bkt/apis';
import 'video.js/dist/video-js.min.css';
const { Option } = Select;
const warnColor = '#F59A23';
const okColor = '#4B7902';
const errColor = '#D9001B';
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 = {
      oldPersonInternLineId: '',
      comName: this.props.companyInfo.comName,
      info: null,  //详情
      imgs: [],
      // refuseModal: false,  //拒绝的弹窗
      // refuseReason: '',  //拒绝原因

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

    };
  }
  componentDidMount() { }
  componentWillReceiveProps(nextProps) {
    if (!!nextProps.personInternLineId && this.state.oldPersonInternLineId != nextProps.personInternLineId) {
      this.setState({ oldPersonInternLineId: nextProps.personInternLineId });
      this._getDetailInfo(nextProps.personInternLineId);
    }
  }

  _getDetailInfo = (personInternLineId) => {
    grade_trainInternInternLineInfo({ data: { personInternLineId } }).then(res => {
      const { approveStatus, trainApproveStatus } = res.data;
      let disabled = true;
      // 保安公司审核通过
      if(approveStatus == '1') {
        // 培训公司已经审核
        if(trainApproveStatus == '1' || trainApproveStatus == '2') {
          disabled = true;
        }else {
          disabled = false;
        }
      }else {// 保安公司未审核或未审核通过
        disabled= true;
      }
      res.data.disabled = disabled;
      this.setState({
        info: res.data
      });
      if (res.data) {
        // 重组图像文件
        const imgArr = [];
        if(res.data.wearUrl) {
          imgArr.push({
            label: '穿戴保安服照',
            fieldsName: 'wearUrl',
            types: ['image/jpeg', 'image/jpg'],
            rules: [{
              required: true,
              message: `穿戴保安服照`
            }]
          });
        }
        if(res.data.internAddressUrl) {
          imgArr.push({
            label: '实习地点照片',
            fieldsName: 'internAddressUrl',
            types: ['image/jpeg', 'image/jpg'],
            rules: [{
              required: true,
              message: `实习地点照片`
            }]
          });
        }
        if(res.data.internProcessUrl) {
          imgArr.push({
            label: '实习过程照片',
            fieldsName: 'internProcessUrl',
            types: ['image/jpeg', 'image/jpg'],
            rules: [{
              required: true,
              message: `实习过程照片`
            }]
          });
        }
        if(res.data.internProcessVideo) {
          imgArr.push({
            label: '实习过程视频',
            fieldsName: 'internProcessVideo',
            types: ['video/*'],
            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]
          ]);
        }
        this.setState({
          imgs: rows
        });
      }
    });
  }

  _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 data = { ...values, materialApprovePerName, materialApprovePerIdCardNo, personType, personApplyId, comContractId };
        //   trainGradeApplyPersonApplyUpdate({ data }).then(res => {
        //     $modal(res.msg, '', null, 'success');
        //     this._getDetailInfo(this.props.personApplyId);
        //   });
        // });
      }
    });
  }
  // 获取操作人信息
  _getUserInfo = (cb) => {
    if (this.state.editUser) {
      cb();
    } else {
      getBayBaseInfo().then(res => {
        this.setState({
          editUser: res.data
        }, cb);
      })
    }
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const { info } = this.state;
    return (
      <div>
        <Drawer
          title="实习详情"
          width={600}
          visible={!!this.props.personInternLineId}
          destroyOnClose={true}
          onClose={() => {
            this.props.onClose();
          }}
        >
          {/* form表单 */}
          {
            info &&
            <div>
              <Form onSubmit={this._onSubmit} 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('organName', {
                    initialValue: info.organName
                  })(<Input placeholder="" maxLength={30} disabled={true} />)}
                </Form.Item>
                <Form.Item {...formItemLayout} label="实习日期">
                  {getFieldDecorator('internDate', {
                    initialValue: info.internDate
                  })(<Input placeholder="" maxLength={30} disabled={true} />)}
                </Form.Item>
                <Form.Item {...formItemLayout} label="签到时间">
                  {getFieldDecorator('signInDate', {
                    initialValue: info.signInDate
                  })(<Input placeholder="" maxLength={30} disabled={true} />)}
                </Form.Item>
                <Form.Item {...formItemLayout} label="签到地点">
                  {getFieldDecorator('signInAddress', {
                    initialValue: info.signInAddress
                  })(<Input placeholder="" maxLength={30} disabled={true} />)}
                </Form.Item>
                <Form.Item {...formItemLayout} label="签退时间">
                  {getFieldDecorator('signOutDate', {
                    initialValue: info.signOutDate
                  })(<Input placeholder="" maxLength={30} disabled={true} />)}
                </Form.Item>
                <Form.Item {...formItemLayout} label="签退地点">
                  {getFieldDecorator('signOutAddress', {
                    initialValue: info.signOutAddress
                  })(<Input placeholder="" maxLength={30} disabled={true} />)}
                </Form.Item>
                <Form.Item {...formItemLayout} label="实习时长">
                  {/* {getFieldDecorator('internMinute', {
                    initialValue: ''
                  })(<Input placeholder="" maxLength={30} disabled={true} />)} */}
                  {`${Math.floor(info.internMinute / 60)}小时${info.internMinute % 60}分钟`}
                </Form.Item>
                <Form.Item {...formItemLayout} label="实习内容">
                  {getFieldDecorator('internContent', {
                    initialValue: info.internContent
                  })(<Input placeholder="" maxLength={30} disabled={true} />)}
                </Form.Item>
                <br />
                <Form.Item {...formItemLayout} label="保安公司审核状态">
                  {/* {getFieldDecorator('identitynumber', {
                    initialValue: info.identitynumber
                  })(<Input placeholder="" maxLength={30} disabled={true} />)} */}
                  {(() => {
                    let text = '未审核';
                    let color = warnColor;
                    const value = info.approveStatus;
                    switch (true) {
                      case value == 0:
                        color = warnColor;
                        text = '未审核';
                        break;
                      case value == 1:
                        color = okColor;
                        text = '审核通过';
                        break;
                      case value == 2:
                        color = errColor;
                        text = '审核不通过';
                    }
                    return (
                      <span style={{ color }}>{text}</span>
                    );
                  })()}
                </Form.Item>
                {
                  info.approveStatus == 2 &&
                  <Form.Item {...formItemLayout} label="不通过原因">
                    <span style={{color: errColor}}>{info.comments}</span>
                  </Form.Item>
                }
                <Form.Item {...formItemLayout} label="保安公司审核人">
                  {/* {getFieldDecorator('approveFullName', {
                    initialValue: info.approveFullName + info.approvePerIdCardNo?`(${info.approvePerIdCardNo})` : ''
                  })(<Input placeholder="" disabled={true} />)} */}
                  <Input placeholder="" value={info.approveFullName + (info.approvePerIdCardNo?`(${info.approvePerIdCardNo.replace(/(\d{4}).*(\d{3})/, '$1***********$2')})` : '')} disabled={true} />
                </Form.Item>
                {
                  info.trainApproveStatus !=0 &&
                  <>
                    <Form.Item {...formItemLayout} label="培训机构审核状态">
                    {(() => {
                        let text = '未审核';
                        let color = warnColor;
                        const value = info.trainApproveStatus;
                        switch (true) {
                          case value == 0:
                            color = warnColor;
                            text = '未审核';
                            break;
                          case value == 1:
                            color = okColor;
                            text = '审核通过';
                            break;
                          case value == 2:
                            color = errColor;
                            text = '审核不通过';
                        }
                        return (
                          <span style={{ color }}>{text}</span>
                        );
                      })()}
                    </Form.Item>
                    {
                      info.trainApproveStatus == 2 &&
                      <Form.Item {...formItemLayout} label="不通过原因">
                        <span style={{color: errColor}}>{info.comments}</span>
                      </Form.Item>
                    }
                    <Form.Item {...formItemLayout} label="培训机构审核人">
                      {/* {getFieldDecorator('trainApprovePerName', {
                        initialValue: info.trainApprovePerName + (info.trainApprovePerIdCardNo?`(${info.trainApprovePerIdCardNo})` : '')
                      })(<Input placeholder="" disabled={true} />)} */}
                      <Input placeholder="" value={info.trainApprovePerName + (info.trainApprovePerIdCardNo?`(${info.trainApprovePerIdCardNo.replace(/(\d{4}).*(\d{3})/, '$1***********$2')})` : '')} disabled={true} />
                    </Form.Item>
                  </>
                }
                {(() => {
                    let text = '';
                    let color = warnColor;
                    const value = info.lineStatus;
                    switch (true) {
                      case value == 0:
                        color = warnColor;
                        text = '未审核';
                        break;
                      case value == 1:
                        color = okColor;
                        text = '审核通过';
                        break;
                      case value == 2:
                        color = errColor;
                        text = '审核不通过';
                    }
                    if(text) {
                      return (
                        <Form.Item {...formItemLayout} label="实习记录状态">
                          <span style={{ color }}>{text}</span>
                        </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}>
                                {
                                  item.fieldsName == 'internProcessVideo'&&
                                  <>
                                    <p style={{textAlign: 'center'}}>{item.label}</p>
                                    <video 
                                      style={{width: '100%'}} 
                                      key={idex + moment().valueOf()}
                                      id="video"
                                      className="video-js"
                                      controls
                                      name="media"
                                    >
                                      <source src={info[item.fieldsName]}/>
                                      您的浏览器不支持 video 标签。
                                    </video>
                                  </>
                                }
                                {
                                  item.fieldsName != 'internProcessVideo'&&
                                  <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
                                        num={1}
                                        types={item.types}
                                        size={item.size}
                                        sizeErrMsg={item.sizeErrMsg}
                                      />
                                    )}
                                  </Form.Item>
                                }
                              </Col>
                            )
                          })
                        }
                      </Row>
                    );
                  })
                }
              </Form>
            </div>
          }


          {/* 底部提交按钮 */}
          {
            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={() => {
                  // 关闭抽屉
                  this.props.onClose();
                }}
              >
                返回
              </Button>
              {/* <Button
                type="primary"
                // 保安公司审核通过，并且培训公司未审核
                disabled={true}
                style={{
                  marginRight: 8
                }}
                onClick={() => {
                  $modal(
                    '确定提交',
                    '',
                    [{
                      text: '确定', type: 'primary', onPress: () => {
                        const subFun = () => {
                          // const trainApprovePerId = this.state.editUser.perId;
                          const trainApprovePerName = this.state.editUser.name;
                          const trainApprovePerIdCardNo = this.state.editUser.idCardNo;
                          const { personInternLineId } = this.props;
                          grade_trainInternLineApprovePass({ data: { personInternLineId, trainApprovePerName, trainApprovePerIdCardNo } }).then(res => {
                            this._getDetailInfo(this.props.personInternLineId);
                            this.props.updateTable();
                            // 提示
                            $modal('提交成功！', '', null, 'success');
                          });
                        }
                        // 获取人员基础信息
                        this._getUserInfo(subFun);
                      }
                    }, { text: '取消' }],
                    'success'
                  );
                }}
              >
                审核通过
              </Button>
              <Button
                type="danger"
                disabled={true}
                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 comments = this.state.refuseReason;
              if (comments) {
                const subFun = () => {
                  const trainApprovePerName = this.state.editUser.name;
                  const trainApprovePerIdCardNo = this.state.editUser.idCardNo;
                  const { personInternLineId } = this.props;
                  grade_trainInternLineApproveFail({ data: { personInternLineId, comments, trainApprovePerName, trainApprovePerIdCardNo } }).then(res => {
                    $modal('提交成功！', '保安公司可查看不通过原因。', null, 'success');
                    this.setState({
                      refuseModal: false,
                      refuseReason: ''
                    });
                    this._getDetailInfo(this.props.personInternLineId);
                    this.props.updateTable();
                  });
                }
                // 获取人员基础信息
                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>

      </div>
    );
  }
}
