import React, { Component } from 'react';
import st from 'styled-components';
import { connect } from 'dva';
import { withRouter } from 'dva/router';
import {
  Input,
  Button,
  Table,
  Select,
  Alert,
  DatePicker,
  notification,
  Modal,
  Popover
} from 'antd';
import store from 'store';

import tablePage from '../../../../utils/hoc/tablePage';
import columnFun from './columns';
import SubDrawer from './SubDrawer';
import { getConfigBayzgzSb } from '../../../../services/api';
import '../../declaration.less';
import moment from 'moment';
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 Submitted extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      //抽屉
      drawerVisble: false,
      personApplyId: '',  //当前选中的id
      dataListAreaCode: '',//表格数据属于哪个区域
      isNanNiCode:false,//是否是南宁地区码
    };
  }

  /**
   * 6106是陕西的
   * 后面又增加南宁的特殊字段需求，往下传isNanNiCode值，在非陕西的页面中做判断
   */
  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
  }

  componentDidMount() {
    this.__getConfigBayzgzSb();
  }

  //获取保安员指南
  __getConfigBayzgzSb() {
    getConfigBayzgzSb().then(
      res => {
        if (res.retType === '0') {
          this.setState({
            declareNotice: res.data.declareNotice
          })
        }
      }
    )
  }
  // 表格渲染
  _renderList = () => {
    const columns = columnFun.call(this);
    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>
            );
          }
        },
      )
      columns.splice(
        9, 0,
        {
          title: '缴费金额（元）',
          dataIndex: 'payAmount',
          key: 'payAmount',
          render: value => value || '-'
        },
      )
    }
    const { PageTable, isInit } = this.props;
    if (!isInit) return;
    return (
      <PageTable
        style={{ marginTop: 20 }}
        columns={columns}
        url="qualify_trainQualifyApplyLearnPage"
        scroll={{ x: '2000px' }}
        dateChange={(data) => {
          this.setState({
            dataListAreaCode: data.userData? data.userData.areaCode:'',
            isNanNiCode: data.userData? data.userData.areaCode.indexOf('4501') == 0 : false,
          })
        }}
      />
    );
  };

  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: (
                    <div dangerouslySetInnerHTML={{
                      __html: this.state.declareNotice
                    }} />
                  )
                });
              }}>《保安员资格考试报名办理指南》</a>，了解相关章程及规定。</span>
          </div>}
          type="warning"
          showIcon
          style={{ marginBottom: '15px' }}
        />
        {/* <SearchForm
          onSearch={this._search}
        /> */}
        <SearchForm
          arrange={values => {
            // values
            const { date, examDate,confirmDate } = values;
            // 报名时间
            console.log(date, 'date');
            if (date.length == 2) {
              values.applyStartDate = moment(date[0]).format(dateFormat);
              values.applyEndDate = moment(date[1]).format(dateFormat);
            } else {
              values.applyStartDate = '';
              values.applyEndDate = '';
            }
            if (examDate.length == 2) {
              values.examStartDate = moment(examDate[0]).format(dateFormat);
              values.examEndDate = moment(examDate[1]).format(dateFormat);
            } else {
              values.examStartDate = '';
              values.examEndDate = '';
            }
            // 确认成绩时间
            if (confirmDate.length == 2) {
              values.confirmStartDate = moment(confirmDate[0]).format(dateFormat);
              values.confirmEndDate = moment(confirmDate[1]).format(dateFormat);
            } else {
              values.confirmStartDate = '';
              values.confirmEndDate = '';
            }
            Reflect.deleteProperty(values, 'date');
            Reflect.deleteProperty(values, 'examDate');
            Reflect.deleteProperty(values, 'confirmDate');
            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('organName', {
                initialValue: ''
              })(
                <Input style={{ width: 200 }} placeholder="请输入机构名称" />
              )}
            </Form.Item>
            <Form.Item label="缴费状态">
              {getFieldDecorator('orderStatus', {
                initialValue: ''
              })(
                <Select style={{ minWidth: 150 }} >
                  <Option value="">全部</Option>
                  <Option value="0">未缴费</Option>
                  <Option value="1">已缴费</Option>
                </Select>
              )}
            </Form.Item>
            <Form.Item label="材料核对状态">
              {getFieldDecorator('materialApproveStatus', {
                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('date', {
                initialValue: []
              })(
                <RangePicker
                  format={dateFormat}
                />
              )}
            </Form.Item>
            <Form.Item label="学习状态">
              {getFieldDecorator('trackLearnStatus', {
                initialValue: ''
              })(
                <Select style={{ minWidth: 150 }} >
                  <Option value="">全部</Option>
                  <Option value="0">未完成</Option>
                  <Option value="1">已完成</Option>
                </Select>
              )}
            </Form.Item>
            <Form.Item label="部门">
              {getFieldDecorator('departName', {
                initialValue: ''
              })(
                <Input style={{ width: 200 }} placeholder="请输入部门名称" />
              )}
            </Form.Item>
            <Form.Item label="考试结果">
              {getFieldDecorator('testState', {
                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('examDate', {
                initialValue: []
              })(
                <RangePicker
                  format={dateFormat}
                />
              )}
            </Form.Item>
            <Form.Item label="课程名称">
              {getFieldDecorator('trackName', {
                initialValue: ''
              })(
                <Input style={{ width: 200 }} placeholder="请输入课程名称" />
              )}
            </Form.Item>
            <Form.Item label="确认成绩时间">
              {getFieldDecorator('confirmDate', {
                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('payAmount', {
                  initialValue: ''
                })(
                  <Select style={{ minWidth: 150 }} >
                    <Option value="">全部</Option>
                    <Option value="80">80元</Option>
                    <Option value="280">280元</Option>
                    <Option value="480">480元</Option>
                    <Option value="680">680元</Option>
                  </Select>
                )}
              </Form.Item>
            </>
            }
          </>
        </SearchForm>
        <Btns>
        {this.checkBeijinCode()?'':
            <Button style={{ marginRight: 15 }} onClick={() => {
              if (this.checkAreaCode()) {
                this.props.history.push('/PoliceDeclare/sign-up/sx-fill-in');
              } else {
                this.props.history.push({
                  pathname:'/PoliceDeclare/sign-up/fill-in',
                  isNanNiCode:this.state.isNanNiCode
                });
              }
            }} type="primary">新增报名</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/learn/apply' + queryStr + '&sessionId=' + store.get('saas')['sessionId']);
            }}
          >
            导出数据
            </Button>
          {/* </Popover> */}
        </Btns>
        {/* 表格 */}
        {this._renderList()}

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

const Btns = st.div`
  margin-top: 15px;
  button {
    margin-right: 15px;
  }
`;