import React, { Component } from "react";
import {
  Spin,
  Button,
  Table,
  message,
  Input,
  DatePicker,
  Select,
  Icon,
  Upload,
  Tooltip,
  Modal,
} from 'antd';
import $ from "jquery/src/ajax";
import ajax from 'jquery/src/ajax/xhr.js'
import moment from "moment";
import '../../public.less';
import logo from '../../../../../image/kede.png';
import { getLoginStatus } from '../../../../utils/tools';
import Detail from "./detail"; // 详情

const Option = Select.Option;
const { RangePicker } = DatePicker;

class Content extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [], // table数据
      loading: false, // 加载loading
      searchInfor: {}, // 查询条件
      visible: false, // 控制弹窗变量
      rowdata: {}, // 行数据
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        pageSize: 10,
        onChange: function (page) {
          this.loadData(page);
        }.bind(this),
        showTotal: function (total) {
          return "共" + total + "条数据";
        },
      },
      columns: [
        {
          title: "索引",
          dataIndex: "id",
          key: "id",
          fixed: "left",
          width: 50,
        },
        {
          title: "单位名称",
          dataIndex: "userName",
          key: "userName",
          fixed: "left",
          width: 180,
        },
        {
          title: "研发活动编号",
          dataIndex: "rdNo",
          key: "rdNo",
          width: 100,
        },
        {
          title: "知识产权编号",
          dataIndex: "ipNo",
          key: "ipNo",
          width: 100,
        },
        {
          title: "研发活动名称",
          dataIndex: "rdName",
          key: "rdName",
        },
        {
          title: "起止时间",
          dataIndex: "rdStartStr",
          key: "rdStartStr",
          width: 160,
          render: (text, record) => (
            <div>
              {!text ? "" : (text + "～" + record.rdEndStr)}
            </div>
          )
        },
        {
          title: "技术领域",
          dataIndex: "technicalField",
          key: "technicalField",
        },
        {
          title: "技术来源",
          dataIndex: "technologySource",
          key: "technologySource",
        },
        {
          title: "研发经费总预算(万元)",
          dataIndex: "totalAmount",
          key: "totalAmount",
          width: 80
        },
        {
          title: "研发经费近三年总支出(万元)",
          dataIndex: "recentThreeAmount",
          key: "recentThreeAmount",
          width: 80
        },
        {
          title: "研发目的及组织实施方式",
          dataIndex: "rdObjective",
          key: "rdObjective",
          render: (text) => {
            return (
              <Tooltip title={text}>
                <div style={{
                  maxWidth: '300px',
                  overflow: 'hidden',
                  textOverflow: "ellipsis",
                  whiteSpace: 'nowrap',
                }}>{text}</div>
              </Tooltip>
            )
          }
        },
        {
          title: "核心技术及创新点",
          dataIndex: "coreTechnology",
          key: "coreTechnology",
          render: (text) => {
            return (
              <Tooltip title={text}>
                <div style={{
                  maxWidth: '300px',
                  overflow: 'hidden',
                  textOverflow: "ellipsis",
                  whiteSpace: 'nowrap',
                }}>{text}</div>
              </Tooltip>
            )
          }
        },
        {
          title: "取得的创段性成果",
          dataIndex: "achieveResults",
          key: "achieveResults",
          render: (text) => {
            return (
              <Tooltip title={text}>
                <div style={{
                  maxWidth: '300px',
                  overflow: 'hidden',
                  textOverflow: "ellipsis",
                  whiteSpace: 'nowrap',
                }}>{text}</div>
              </Tooltip>
            )
          }
        },
        {
          title: "咨询师名称",
          dataIndex: "consultantName",
          key: "consultantName",
        },
        {
          title: "阅读次数",
          dataIndex: "browseCount",
          key: "browseCount",
        },
        {
          title: "下载次数",
          dataIndex: "downloadCount",
          key: "downloadCount",
        },
      ],
      upLoad: {
        customRequest: (options) => {
          this.setState({
            upLoadFileLoading: true,
          })
          let params = new FormData();
          params.append("file", options.file);
          $.ajax({
            method: "post",
            url: globalConfig.context + "/api/admin/RD/import",
            async: true,
            cache: false,
            contentType: false,
            processData: false,
            data: params
          }).done(
            function (data) {
              this.setState({
                upLoadFileLoading: false,
              })
              if (data.data.OK == 0) {
                if (data.data.ERROR.length == 0) {
                  message.error("导入未成功，请使用正确模板导入");
                } else {
                  this.onTips(data)
                }
                this.loadData();
              } else {
                message.success(`${data.data.OK}条数据导入成功！`);
                this.loadData();
              }
            }.bind(this)
          ).always(
            function (err) {
              if (err.status === 404) {
                message.warning('数据错误');
              }
              this.setState({
                upLoadFileLoading: false,
              });
            }.bind(this)
          );
        },
        name: "file",
        action: globalConfig.context + "/api/admin/RD/import",
      },
    };
  }
  // 导入提示
  onTips(data) {
    if (data.data.ERROR.length > 0) {
      Modal.info({
        title: <span>部分导入失败,您有以下
          <span style={{ color: "red" }}>&nbsp;{data.data.ERROR.length}&nbsp;</span>条数据重复！
        </span>,
        content: (
          <div>
            {
              data.data.ERROR.map((item, index) =>
                <p key={index}>研发活动编号为[<span style={{ color: "red" }}>&nbsp;{item}&nbsp;</span>]</p>
              )
            }
            <div style={{ color: "red", marginTop: 20 }}>以上数据因研发活动编号重复无法导入</div>
          </div>
        ),
        okText: '确定',
      });
    }
  }
  // 列表查询
  loadData(pageNo) {
    const { searchInfor, pagination } = this.state;
    this.setState({
      loading: true,
    });
    let datas = Object.assign(searchInfor, {
      pageNo: pageNo || 1,
      pageSize: pagination.pageSize,
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/RD/list",
      data: datas,
      success: function (data) {
        this.setState({
          loading: false,
        });
        if (data.error && data.error.length === 0) {
          if (data.data.list) {
            pagination.current = data.data.pageNo;
            pagination.total = data.data.totalCount;
            if (data.data && data.data.list && !data.data.list.length) {
              pagination.current = 0;
              pagination.total = 0;
            }
            this.setState({
              dataSource: data.data.list,
              pagination: this.state.pagination,
              pageNo: data.data.pageNo,
            });
          } else {
            this.setState({
              dataSource: data.data,
              pagination: false,
            });
          }
        } else {
          getLoginStatus(data)
        }
      }.bind(this),
    }).always(
      function () {
        this.setState({
          loading: false,
        });
      }.bind(this)
    );
  }
  // 重置
  resetAll() {
    this.setState({
      searchInfor: JSON.parse(JSON.stringify({})),
    }, () => {
      this.loadData()
    })
  }
  // 导出
  exportExec() {
    message.config({
      duration: 20,
    });
    let loading = message.loading("下载中...");
    this.setState({
      exportPendingLoading: true,
    });
    let data = {
      pageNo: 1,
      pageSize: 99999,
    };
    let obj1 = JSON.parse(JSON.stringify(this.state.searchInfor));
    data = Object.assign(data, obj1);
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/RD/exportList",
      data,
      success: function (data) {
        if (data.error.length === 0) {
          this.download(data.data);
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(
      function () {
        loading();
        this.setState({
          exportPendingLoading: false,
        });
      }.bind(this)
    );
  }
  // Excel下载
  download(fileName) {
    window.location.href =
      globalConfig.context + "/open/download?fileName=" + fileName;
  }
  // 模板下载
  downloadTemplate(api) {
    message.loading("下载中...");
    window.location.href = globalConfig.context + api;
  }
  // 双击
  onRowDoubleClick(record) {
    this.setState({
      visible: true,
      rowdata: record,
    })
  }
  // 关闭弹窗
  onCancel() {
    this.setState({
      visible: false,
      rowdata: {}
    }, () => {
      this.loadData(this.state.pageNo)
    })
  }

  componentWillMount() {
    this.loadData();
  }

  render() {
    const { columns, searchInfor } = this.state;
    return (
      <div className="user-content">
        {/* <div className="content-title">
        </div> */}
        <div className="patent-table">
          <div className="user-search">
            <RangePicker
              style={{ width: 200 }}
              value={[
                searchInfor.rdStart ? moment(searchInfor.rdStart) : null,
                searchInfor.rdEnd ? moment(searchInfor.rdEnd) : null,
              ]}
              onChange={(data, dataString) => {
                this.setState({
                  searchInfor: Object.assign(searchInfor, {
                    rdStart: dataString[0],
                    rdEnd: dataString[1],
                  }),
                });
              }}
            />
            <Input
              placeholder={"请输入研发活动名称"}
              style={{ width: 180 }}
              value={searchInfor.rdName}
              onChange={(e) => {
                this.setState({
                  searchInfor: Object.assign(searchInfor, {
                    rdName: e.target.value,
                  }),
                });
              }}
            />
            <Button
              type="primary"
              onClick={() => {
                this.loadData();
              }}
              style={{ margin: "0 5px" }}
            >
              搜索
            </Button>
            <Button
              onClick={this.resetAll.bind(this)}
              style={{ margin: "0 5px" }}
            >
              重置
            </Button>
            <div className="button">
              <Upload {...this.state.upLoad}>
                <Button
                  type="primary"
                  style={{ marginLeft: 10 }}
                >
                  <Icon type="upload" />
                  导入数据
                </Button>
              </Upload>
              <Button
                type="primary"
                onClick={this.downloadTemplate.bind(this, "/api/admin/RD/downloadTemplate")}
                style={{ marginLeft: 10 }}
              >
                <Icon type="download" />
                下载上传模板
              </Button>
              <Button
                type="primary"
                onClick={this.exportExec.bind(this)}
                style={{ marginLeft: 10 }}
              >
                <Icon type="download" />
                导出Excel
              </Button>
            </div>
          </div>
          <Spin spinning={this.state.loading}>
            <Table
              size="middle"
              bordered
              columns={columns}
              scroll={{ x: window.innerWidth > 1530 ? '130%' : window.innerWidth < 980 ? '280%' : '200%' }}
              dataSource={this.state.dataSource}
              pagination={this.state.pagination}
              onRowDoubleClick={this.onRowDoubleClick.bind(this)}
            />
          </Spin>
        </div>
        {
          // 详情
          this.state.visible &&
          <Detail
            rowdata={this.state.rowdata}
            visible={this.state.visible}
            onCancel={this.onCancel.bind(this)}
          />
        }
      </div>
    );
  }

}

export default Content;
