import React, { Component } from 'react';
import st from 'styled-components';
import { connect } from 'dva';
import { withRouter } from 'dva/router';
import {
  Button, Alert, Popover, Form,
  Tabs, Icon, Upload, message, Modal
} from 'antd';
import BTable from '../../../../components/Pro/BTable';

import SearchForm from './SearchForm';
import columnFun from './columns';
import SubDrawer from './SubDrawer';
import { grade_importIdentityTemplate } from '../../../../services/bkt/apis';
// import $nModal from '../../../../utils/modal/nModal';
import $loading from '../../../../utils/loading';
// import Uploader from '../../../../components/form/upload/Uploader';
import store from 'store';

const formItemLayout = {
  labelCol: {
    span: 7
  },
  wrapperCol: {
    span: 17
  }
};
const { TabPane } = Tabs;
@connect(state => ({
  global: state.global
}))
@withRouter
@Form.create()
export default class StudentManagement extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      uploadVisible: false, //导入等级证数据模态框
      fileList: [],
      forceUpdate: false, //刷新数据
      // 搜索部分
      searchData: {  // 表格数据请求参数
        pageNumber: 1,  // 页	
        pageSize: 10  //条目
      },

      //抽屉
      drawerVisble: false,
      personApplyId: '',  //当前选中的id
    };
  }

  componentDidMount() {
    //获取部门树数据
    // this.__getDepart();
    // this.__getTable(this.state.searchData, data => {
    // });
  }
  _search = values => {
    this.setState({
      searchData: {
        ...this.state.searchData,
        ...values
      },
      isInit: true
    });
  }
  _updateTable = () => {
    this.setState({
      forceUpdate: true
    }, () => {
      this.setState({
        forceUpdate: false
      });
    });
  }
  // 表格渲染
  renderOrderList = () => {
    const columns = columnFun.call(this);
    if (!this.state.isInit) return;
    return (
      <BTable
        style={{ marginTop: 20 }}
        columns={columns}
        url="trainGradeApplyTrainPage"
        pageParm={this.state.searchData}
        forceUpdate={this.state.forceUpdate}
        scroll={{ x: '250%' }}
        dateChange={(e) => { }}
      />
    );
  };

  render() {

    return (
      <div style={{ margin: 15 }}>
        <Tabs>
          <TabPane tab="等级证学员管理" key="1" />
        </Tabs>
        <Alert
          message={<div style={{ color: '#333' }}>
            材料核对：您需要为每一条报名记录核对材料信息；若核对不通过，将终止该学员继续学习课程；若核对通过，则该学员可以继续学习。
          </div>}
          type="warning"
          showIcon
          style={{ marginBottom: '15px' }}
        />
        <SearchForm
          onSearch={this._search}
        />
        <Btns>
          {/* <ExcelButtonOline butto
              params={this.state.pageParm}
              apiurl={'/train/grade/export/train/apply'} 
              downloadname={'等级证人员数据'}
            >
              导出人员数据数据
            </ExcelButtonOline> */}
          <Popover content={<p style={{ padding: 10 }}>搜索后可导出搜索结果</p>} title="温馨提示：">
            <Button
              type="primary"
              onClick={() => {
                const { searchData } = this.state;
                let queryStr = '';
                Object.keys(searchData).forEach(key => {
                  queryStr += `${key}=${searchData[key]}&`;
                });
                queryStr = '?' + queryStr.slice(0, -1);
                console.log(queryStr)
                window.open('/bkt_api/train/grade/apply/export/train/apply' + queryStr + '&sessionId=' + store.get('saas')['sessionId']);
              }}
            >
              导出人员数据
              </Button>
          </Popover>
          <Button
            type="primary"
            onClick={() => {
              this.setState({
                uploadVisible: true
              });
            }}
          >
            导入鉴定数据
          </Button>
        </Btns>
        {/* 表格 */}
        {this.renderOrderList()}

        {/* 修改弹窗 */}
        <SubDrawer
          // visible={!!this.state.personApplyId}
          personApplyId={this.state.personApplyId}
          setParentState={this.setState.bind(this)}
        // onClose={() => {
        //   this.setState({
        //     personApplyId: ''
        //   });
        // }}
        />

        <Modal
          visible={this.state.uploadVisible}
          okText="确定"
          cancelText="取消"
          title="导入鉴定数据"
          onOk={() => {
            const { fileList } = this.state;
            if(fileList.length == 0) {
              return message.error(`请选择文件!`);
            }
            const formData = new FormData();
            formData.append('xfile', fileList[0]);
            $loading.open('文件上传中,请稍后。。。');
            grade_importIdentityTemplate(formData).then(res => {
              $loading.close();
              this.setState({ uploadVisible: false, fileList: [] });
            }).catch(ex => {
              $loading.close();
              console.log(ex);
            });
          }}
          onCancel={() => {
            this.setState({ uploadVisible: false });
          }}
        >
          <Form layout="horizontal">
            <Form.Item  {...formItemLayout} style={{ marginTop: 10 }} label="下载模板">
              <Button onClick={() => {
                window.open('https://bcxin-static.obs.cn-north-1.myhuaweicloud.com/bktang/Template/%E8%81%8C%E4%B8%9A%E6%8A%80%E8%83%BD%E9%89%B4%E5%AE%9A%E4%BA%BA%E5%91%98%E5%90%8D%E5%86%8C%E6%A8%A1%E6%9D%BF.xlsx', '_blank');
              }}>
                <Icon type="download" /> 下载
                </Button>
            </Form.Item>

            <Form.Item  {...formItemLayout} style={{ marginTop: 10 }} label="上传等级证信息">
              <Upload
                showUploadList={true}
                fileList={this.state.fileList}
                beforeUpload={(file) => {
                  let canUpload = true;
                  const reg = /(\.doc$)|(\.docx$)|(\.xlsx$)|(\.xls$)/;
                  if (!(file.name + '').toLocaleLowerCase().match(reg)) {
                    message.error(`请上传拓展名为 .doc .docx .xlsx .xls的文件!`);
                    canUpload = false;
                  }
                  return canUpload;
                }}
                onRemove={() => {
                  this.setState({
                    fileList: []
                  });
                }}
                customRequest={({ file }) => {
                  this.setState({
                    fileList: [file]
                  });
                }}
              >
                <Button style={{ marginLeft: 10 }} ><Icon type="upload" />上传文件</Button>
                <span style={{ marginLeft: 10 }}>支持拓展名：.doc .docx .xlsx .xls
                </span>
              </Upload>
            </Form.Item>
          </Form>
        </Modal>
      </div >
    );
  }
}

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