import React, { Component } from 'react';
import { Tabs, Radio, InputNumber, Checkbox, Select, Modal, Table, Icon, message, Button } from 'antd';
import axios from 'axios'
import qs from 'qs';

function collectCounterItem(arr) {
  let tmpArr = []
  let obj
  arr.map(item => {
    obj = {}
    obj.id = item.id;
    item.calculationMethod ? obj.calculationMethod = item.calculationMethod : null;
    item.displayType ? obj.displayType = item.displayType : null;
    item.fieldType ? obj.fieldType = item.fieldType : null;
    item.config ? obj.config = item.config : null
    tmpArr.push(obj)
  })
  return tmpArr
}
function collectFilterItem(arr) {
  let tmpArr = []
  let obj
  arr.map(item => {
    obj = {}
    obj.id = item.id;
    item.selected && item.selected.length === 0 ? null : obj.selected = item.selected
    tmpArr.push(obj)
  })
  return tmpArr
}
let columns = []
class DetailModal extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      myVisible: false,
      iconString: 'arrows-alt',
      page: 0,
      pageSize: 10,
      totalCount: 0,
      detailData: [],
      detailColumns: [],
      // detailData: [],
      // detailColumns: [],
      modalWidth: '1000px',
      isMax: false
    }
  }
  componentWillReceiveProps(nextProps) {

  }
  //点击关闭模态窗
  handleCancel() {
    jQuery(window).off('resize')
    let self = this
    let filterH = this.props.filter.length === 0 ? 0 : 110
    jQuery(".pivot-content-container .pivot-table-content-container").css('max-height', jQuery(window).height() - filterH - 90)
    jQuery(".pivot-content-container").width(jQuery(window).width() - self.props.siderWidth)
    jQuery(window).resize(function () {
      jQuery(".pivot-content-container .pivot-table-content-container").css('max-height', jQuery(window).height() - filterH - 90)
      jQuery(".pivot-content-container").width(jQuery(window).width() - self.props.siderWidth)
    });
    this.props.closeDetailModal()
  }
  //获取数据
  fetchData(page) {
    const self = this
    let {
      pageSize
    } = this.state
    let {
      detailKey
    } = this.props
    if (0) {
      let arr = this.tranformColumns(columns)
      self.setState({
        page: 1,
        detailColumns: arr,
      })
    } else {
      let row = this.props.row
      let col = this.props.col
      let value = this.props.selectedVal
      let filter = collectFilterItem([...this.props.filter])
      let counterItem = collectCounterItem([...this.props.counterItem])
      let id = this.props.id
      let column_key = this.props.columnKey
      let { searchParams, dataLink, link_type, dataFilterParams } = this.props
      let params = { page, pageSize, key: detailKey, row, col, filter, counterItem, id, column_key, searchParams:searchParams.concat(dataFilterParams), value ,dataLink, link_type }
      axios({
        method: "POST",
        url: '/general/appbuilder/web/report/pivottable/getslice',
        data: qs.stringify(params),
      }).then((response) => {
        if (response.data.status != "ok") {
          let msg = response.data.message || '获取数据详情失败'
          message.error(msg);
        } else {
          self.setState({
            myVisible: true
          })
          let {
            page,
            totalCount,
            data,
            columns
          } = response.data
          if (page == 1) {
            let arr = this.tranformColumns(columns)
            self.setState({
              page,
              detailData: data,
              detailColumns: arr,
              totalCount
            })
          } else {
            self.setState({
              page,
              detailData: data
            })
          }
        }

      })
    }

  }
  componentDidUpdate() {
    let tableInfo = document.querySelectorAll('.pivot-detail-modal table')[0]
    //暂无数据的提示
    let placeholder = document.querySelectorAll('.pivot-detail-modal .ant-table-placeholder')[0]
    let tableWidth = this.getTableWidth()
    if (tableWidth) {
      tableInfo.style.width = `${tableWidth}px`;
      placeholder ? placeholder.style.width = `${tableWidth + 1}px` : null
      // tableInfo.style.minWidth = ``;
    } else {
      // tableInfo.style.minWidth = `100%`;
      // tableInfo.style.width = ``;
    }
  }
  //计算table的宽度
  getTableWidth = () => {
    let arr = [...this.state.detailColumns]
    function getTotal(arr) {
      let total = 0
      function loop(arr) {
        arr.forEach(item => {
          if (item.children) {
            loop(item.children)
            item.width = getTotal(item.children)
          } else {
            total = total + parseInt(item.width)
          }
        });
      }
      loop(arr)
      return total
    }
    let tableWidth = getTotal(arr)
    return tableWidth
  }
  handleChangeWidth(item, e) {
    let reg = /^[0-9]*$/
    if (reg.test(e)) {
      let inputNum = parseInt(e)
      if (inputNum < 50) {
      } else {
        let tmp = [...this.state.detailColumns]
        getDataByKey(tmp, item.key)
        myObj.width = `${e}px`
        this.setState({
          detailColumns: tmp
        })
      }

    } else {
      message.error('请输入数字');
    }
  }
  createNewTab = url => {
    // if (window.parent && typeof window.parent.createTab == 'function') {
    //   window.parent.createTab(url, '添加数据源', url)
    // } else {
    //   window.open(url, '_blank')
    // }
    window.open(url, '_blank')
  }
  //转换列
  tranformColumns = (arr) => {
    const me = this
    const loop = (arr) => {
      let _arr = []
      arr.forEach((item, key) => {
        _arr.push({
          key: item.key,
          dataIndex: item.dataIndex,
          width: item.width || '140px',
          title: item.title,
          render: function (text, record, index) {
            if (text.url) {
              return <a onClick={me.createNewTab.bind(me, text.url)}>{text.val}</a>
            } else {
              return <span>{text.val}</span>
            }
          }
        })
      })
      return _arr
    }
    return loop(arr)
  }


  toMax = () => {
    setTimeout(function () {
      if (jQuery('.pivot-detail-modal .ant-modal table').height() + 156 > jQuery(window).height()) {
        jQuery('.pivot-detail-modal .ant-modal-content').height(jQuery('.pivot-detail-modal .ant-modal table').height() + 156)
      } else {
        jQuery('.pivot-detail-modal .ant-modal-content').height(jQuery(window).height() - 1)
      }
    }, 100)
  }
  maxWin = (e) => {
    let self = this
    if (document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth) {
      var winHeight = document.documentElement.clientHeight;
      var winWidth = document.documentElement.clientWidth;
    }
    let content = document.querySelectorAll('.pivot-detail-modal .ant-modal-content')[0]
    let modal = document.querySelectorAll('.pivot-detail-modal .ant-modal ')[0]
    if (this.state.isMax) {
      content.style.height = ``
      this.setState({
        modalWidth: '1000px',
        isMax: false,
        iconString: 'arrows-alt'
      })
      jQuery('.ant-modal-mask').css('background-color', 'rgba(55, 55, 55, 0.6)')
      jQuery(window).off('resize')
    } else {
      this.toMax()
      jQuery('.ant-modal-mask').css('background-color', 'white')
      this.setState({
        modalWidth: '100%',
        isMax: true,
        iconString: 'shrink'
      })
      jQuery(window).resize(function () {
        self.toMax()
      });
    }
  }
  render() {
    const self = this
    const pagination = {
      page: self.state.page,
      total: self.state.totalCount,
      onChange(current) {
        self.fetchData(current)
        if (self.state.isMax) {
          self.toMax()
        }
      }
    };
    let showExport = this.props.showExport ? true : false
    if(this.props.showModalExport!==undefined){            
        showExport = this.props.showModalExport ? true : false;
    }
    return (
      <Modal
        width={this.state.modalWidth}
        wrapClassName="pivot-detail-modal"
        title={
          (
            <div>数据表<div style={{ float: 'right', marginRight: 40 }} onClick={(e) => this.maxWin(e)}><Icon className="icon" type={this.state.iconString} /></div></div>
          )
        }
        visible={this.state.myVisible}
        onCancel={this.handleCancel.bind(this)}
        footer={null}>
        {
          showExport ? <div className="clearfix"><Button type="ghost" onClick={this.handleExportMenuClick.bind(this)} style={{ "float": "right", "marginBottom": "10px" }}>导出Excel文件</Button></div> : null
        }
        <Table columns={this.state.detailColumns} dataSource={this.state.detailData} className="detail-table" pagination={pagination} bordered />
      </Modal>
    )
  }
  handleExportMenuClick() {
    let { columnKey, detailKey,dataLink,searchParams } = this.props
    
    let category = 'excel';
    let params = {}
    let url = '/general/appbuilder/web/report/pivottable/export';
    params.report_id = this.props.reportId
    params.id = this.props.id
    params.col = this.props.col
    params.row = this.props.row
    params.filter = this.props.filter
    params.counterItem = this.props.counterItem
    params.reportName = this.props.reportName || '统计表';
    params.columnKey = columnKey
    params.key = detailKey
    params.dataLink = dataLink
    params.searchParams = searchParams
    let xx = JSON.stringify(params);
    url = `${url}?reportId=${params.report_id}&id=${params.id}&col=${params.col}&row=${params.row}&searchParams=${JSON.stringify(params.searchParams)}&dataLink=${JSON.stringify(params.dataLink)}&filter=${JSON.stringify(params.filter)}&counterItem=${JSON.stringify(params.counterItem)}&category=${category}&reportName=${JSON.stringify(params.reportName)}&columnKey=${columnKey}&key=${detailKey}`;
    window.location.href = url
  }
  componentDidMount() {
    this.fetchData(1)
  }
  componentWillReceiveProps() {
    this.fetchData(1)
  }
}

export default DetailModal
