import React, { Component } from 'react';
import { connect } from 'dva';
import { withRouter } from 'dva/router';
import {
  Input,
  Button,
  Select,
  Alert,
  DatePicker,
  Modal
} from 'antd';
import RreactDom from 'react-dom';
import store from 'store';
import moment from 'moment';
import tablePage from '../../../../../utils/hoc/tablePage';
import columnFun from './columns';
import { qualify_CourseroleGetTrackId } from '../../../../../services/bkt/qualify';
import SubDrawer from './SubDrawer';
import { Btns } from '../style';
import '../style.less';
import $nModal from '../../../../../utils/modal/nModal';
const { RangePicker } = DatePicker;
const { Option } = Select;
const dateFormat = 'YYYY-MM-DD';
@connect(state => ({
  global: state.global,
  companyInfo: state.global.companyInfo
}))
@tablePage({ type: 'bkt' })
@withRouter
export default class StudentList extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      //抽屉
      drawerVisble: false,
      personApplyId: '',  //当前选中的id
      dataListAreaCode: '',//表格数据属于哪个区域
    };
  }

  componentDidMount() {

  }
  checkAreaCode() {
    return this.state.dataListAreaCode && this.state.dataListAreaCode.indexOf('6106') == 0
  }

  // 判断是否是北京地区(北京地区隐藏劳动合同、户籍类型、户籍所在地三个字段)
  checkBeijinCode() {
    let regProvince = String(this.props.companyInfo.regProvince);
    return regProvince && regProvince.indexOf('110') == 0
  }
  // 判断是否为商洛地区
  checkSRAreaCode = () => {
    let regCity = String(this.props.companyInfo.regCity);
    return regCity && regCity.indexOf('611000') == 0
  }

  // 表格渲染
  renderOrderList = () => {
    const columns = columnFun.call(this);
    const { PageTable, isInit } = this.props;
    if (this.checkAreaCode()) {
      columns.splice(
        7, 0,
        {
          title: '指纹状态',
          dataIndex: 'fingerprintStatus',
          key: 'fingerprintStatus',
          render: value => {
            let text = '查询中';
            let color = '';
            switch (true) {
              case value == '0':
                text = '查询中';
                color = '#F59A23';
                break;
              case value == '1':
                text = '已录入';
                color = '#4B7902';
                break;
              case value == '2':
                text = '未录入';
                color = '#D9001B';
                break;
            }
            return (
              <span style={{ color }}>{text}</span>
            );
          }
        },
      )
    }
    if (!isInit) return;
    return (
      <PageTable
        style={{ marginTop: 20 }}
        columns={columns}
        url="qualify_NaturalTrainPage"
        scroll={{ x: '1400px' }}
        dateChange={(data) => {
          this.setState({
            dataListAreaCode: data.userData ? data.userData.areaCode : ''
          })
        }}
      />
    );
  };

  __renderModalContent = () => {
    return (
      <div>
        <h3>保安员资格考试自然人报名指南</h3>
        <h4>申请材料:</h4>
        <div>申领保安员证应当符合下列条件:</div>
        <div>（一）年满18周岁的中国公民；</div>
        <div>（二）身体健康，品行良好；</div>
        <div>（二）身体健康，品行良好；</div>
        <div>（四）参加保安员证考试，成绩合格；</div>
        <div>有下列情形之一的，不得担任保安员：</div>
        <div>（一）曾被收容教育、强制隔离戒毒、劳动教养或者3次以上行政拘留的；</div>
        <div>（二）曾因故意犯罪被刑事处罚的；</div>
        <div>（三）被吊销保安员证未满3年的；</div>
        <div>（四）曾两次被吊销保安员证的。</div>
        <h4>报考流程：</h4>
        <div>1、自然人可通过北京政务网，查看可承接“自然人报考保安员证业务”的培训单位名单及联系方式；</div>
        <div>2、自然人选择培训单位并电话联系；</div>
        <div>3、培训单位将该自然人录入到本企业组织架构中，并通知该自然人下载App完成实名认证；</div>
        <div>4、自然人完成实名认证后，培训单位为其提交报名材料；</div>
        <div>5、系统自动对自然人报名信息进行背景筛查；</div>
        <div>6、背景筛查通过后，培训单位通过系统为自然人确认缴费并支付平台服务费；</div>
        <div>7、缴费成功后系统自动完成资格证课程授权，该自然人即可通过App在线学习课程；</div>
        <div>8、自然人课程学习完成后，培训单位可在考试安排里选择该自然人并为其安排考试；</div>
        <div>9、考试完成――确认成绩――生成电子证书――系统发送短信告知自然人到银行办理联名卡；</div>
        <div>10、结束。</div>
      </div>
    )
  }
  render() {
    const { SearchForm, Form } = this.props;
    const { getFieldDecorator } = this.props.form;
    return (
      <div style={{ padding: '0 24px' }}>
        <Alert
          message={<div style={{ color: '#333' }}>
            <span>人员若存在申报中/申报通过的报名记录，则无法再重新报名；申报不通过的需要重新提交报名申报。</span> <br />
            <span>报名前请仔细阅读
              <a onClick={() => {
                Modal.info({
                  className: 'anbao-modal',
                  maskClosable: true,
                  // title: '保安员资格考试报名办理指南',
                  content: (
                    this.__renderModalContent()
                  ),
                  okText: '知道了'
                });
              }}>《保安员资格考试报名办理指南》</a>，了解相关章程及规定。</span>
          </div>}
          type="warning"
          showIcon
          style={{ marginBottom: '15px' }}
        />
        <SearchForm
          arrange={values => {
            // values
            const { pay, applyDate } = values;
            // 报名时间
            if (applyDate.length == 2) {
              values.applyStartDate = moment(applyDate[0]).format(dateFormat);
              values.applyEndDate = moment(applyDate[1]).format(dateFormat);
            } else {
              values.applyStartDate = '';
              values.applyEndDate = '';
            }
            // 缴费时间
            if (pay.length == 2) {
              values.payStartDate = moment(pay[0]).format(dateFormat);
              values.payEndDate = moment(pay[1]).format(dateFormat);
            } else {
              values.payStartDate = '';
              values.payEndDate = '';
            }
            Reflect.deleteProperty(values, 'applyDate');
            Reflect.deleteProperty(values, 'pay');
            return values;
          }}
        >
          <>
            <Form.Item label="关键词">
              {getFieldDecorator('keyword', {
                initialValue: ''
              })(
                <Input style={{ width: 200 }} placeholder="请输入姓名/手机号码/身份证" />
              )}
            </Form.Item>
            <Form.Item label="申报状态">
              {getFieldDecorator('applyStatus', {
                initialValue: ''
              })(
                <Select style={{ minWidth: 150 }} >
                  <Option value="">全部</Option>
                  <Option value="0">申报中</Option>
                  <Option value="1">申报通过</Option>
                  <Option value="2">申报不通过</Option>
                  <Option value="3">已撤销</Option>
                </Select>
              )}
            </Form.Item>
            <Form.Item label="背景筛查状态">
              {getFieldDecorator('backgroundStatus', {
                initialValue: ''
              })(
                <Select style={{ minWidth: 150 }} >
                  <Option value="">全部</Option>
                  <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 label="报名时间">
              {getFieldDecorator('applyDate', {
                initialValue: []
              })(
                <RangePicker
                  format={dateFormat}
                />
              )}
            </Form.Item>
            <Form.Item label="缴费时间">
              {getFieldDecorator('pay', {
                initialValue: []
              })(
                <RangePicker
                  format={dateFormat}
                />
              )}
            </Form.Item>
            {
              this.checkAreaCode() && <Form.Item label="指纹状态">
                {getFieldDecorator('fingerprintStatus', {
                  initialValue: ''
                })(
                  <Select style={{ minWidth: 150 }} >
                    <Option value="">全部</Option>
                    <Option value="0">查询中</Option>
                    <Option value="1">已录入</Option>
                    <Option value="2">未录入</Option>
                  </Select>
                )}
              </Form.Item>
            }
            <Form.Item label="部门">
              {getFieldDecorator('departName', {
                initialValue: ''
              })(
                <Input style={{ width: 200 }} placeholder="请输入部门名称" />
              )}
            </Form.Item>
          </>
        </SearchForm>
        <Btns> 
          {/* <Popover content={<div style={{padding: 10}}>搜索后可导出结果</div>}> */}
          {this.checkBeijinCode()?'':
            <Button type="primary" style={{ marginRight: 15 }} onClick={() => {
              this.props.history.push({
                pathname: '/Printing/SignUp/FillIn',
                checkAreaCodeValue: this.checkAreaCode()
              });
            }}>新增报名</Button>
          }
          <Button
            // disabled={!this.props.clicked}
            type="primary"
            onClick={() => {
              qualify_CourseroleGetTrackId().then(res => {
                console.log(res)
                if (res.retType == '0' && res.data.trackInfo) {
                  if (res.data.trackInfo.length == 1) {
                    this.props.history.push({
                      pathname: '/Printing/SignUp/Pay',
                      state: {
                        trackId: res.data.trackInfo[0].trackId,
                        organId: res.data.organId
                      }
                    });
                  } else {
                    $nModal({
                      width: 800,
                      title: '选择下单缴费课程',
                      footer: null,
                      content: (
                        <ul>
                          {
                            res.data.trackInfo.map(item => {
                              return <li>
                                <span style={{ marginRight: '10px' }}>课程名称：{item.trackName}</span>
                                <Button type="primary" onClick={() => {
                                  //先删除模态框，在跳转下单缴费列表
                                  const divs = document.getElementsByClassName('n_modal');
                                  Reflect.apply(Array.prototype.forEach, divs, [item => {
                                    RreactDom.unmountComponentAtNode(item);
                                    document.body.removeChild(item);
                                  }]);
                                  this.props.history.push({
                                    pathname: '/Printing/SignUp/Pay',
                                    state: {
                                      trackId: item.trackId,
                                      organId: res.data.organId
                                    }
                                  });
                                }}>下单缴费</Button></li>
                            })
                          }
                        </ul>
                      ),
                    });
                  }
                }
              })
            }}
          >
            下单缴费
            </Button>
          <Button
            // disabled={!this.props.clicked}
            type="primary"
            onClick={() => {
              const { searchData } = this.props;
              let queryStr = '';
              Object.keys(searchData).forEach(key => {
                queryStr += `${key}=${searchData[key]}&`;
              });
              queryStr = '?' + queryStr.slice(0, -1);
              window.open('/bkt_api/train/qualify/apply/export/naturalTrain/apply' + queryStr + '&sessionId=' + store.get('saas')['sessionId']);
            }}
          >
            导出数据
            </Button>
          {/* </Popover> */}
        </Btns>
        {/* 表格 */}
        {this.renderOrderList()}

        {/* 修改弹窗 */}
        <SubDrawer
          personApplyId={this.state.personApplyId}
          checkAreaCodeValue={this.checkAreaCode()}
          onClose={() => {
            this.setState({
              personApplyId: ''
            });
          }}
        />
      </div >
    );
  }
}