// 核心库
import React from 'react'
import { connect } from 'dva'
// 组件库
import { Form, Button, DatePicker, Table, InputNumber, message } from 'antd'
import { ExportToExcel, LayoutCard } from '@woowalker/feui'
import CommonChart from '../../Chart/CommonChart'
// 工具库
import moment from 'moment'

const EditableContext = React.createContext()
const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
)

const EditableFormRow = Form.create()(EditableRow)

class EditableCell extends React.Component {
  state = {
    editing: false,
  };

  toggleEdit = () => {
    const editing = !this.state.editing
    this.setState({ editing }, () => {
      if (editing) {
        this.input.focus()
      }
    })
  };

  save = e => {
    const { record, handleSave } = this.props
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return
      }
      this.toggleEdit()
      handleSave({ ...record, ...values })
    })
  };

  renderCell = form => {
    this.form = form
    const { children, dataIndex, record } = this.props
    const { editing } = this.state
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          initialValue: record[dataIndex],
        })(<InputNumber ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} />)}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{ paddingRight: 24 }}
        onClick={this.toggleEdit}
      >
        {children}
      </div>
    )
  };

  render () {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    )
  }
}

class KrElectricityReportPage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      date: moment(),
      editing: false,
      dataSource: [],
      chartData: {}
    }
  }
  componentDidMount () {
    this.getRunData()
  }
  dateChange = (date) => {
    this.setState({ date })
  }

  btnClick = () => {
    this.getRunData()
  };
  handleSave = (row) => {
    const newData = [...this.state.dataSource]
    const index = newData.findIndex((item) => row.key === item.key)
    const item = newData[index]
    newData.splice(index, 1, {
      ...item,
      ...row
    })
    this.setState({ dataSource: newData })
  };
  getRunData = () => {
    const { login, dispatch } = this.props
    const json = {
      OrgId: login.OrgId,
      Parameter1: this.state.date.format('YYYY-MM-DD'),
    }
    dispatch({
      type: 'app/getDataByPost',
      url: 'KR/Statistics/GetRunData',
      payload: json
    }).then(res => {
      if (res) {
        const { editing, data, chartData } = res
        this.setState({
          editing,
          dataSource: data,
          chartData: {
            xAxis: chartData.XAxis[0].Data,
            yAxis: chartData.YAxis,
            data: chartData.Data
          }
        })
      }
    })
  };
  runDataSave = () => {
    const json = {
      OrgId: this.props.login.OrgId,
      Data: this.state.dataSource
    }
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'KR/Statistics/RunDataSave',
      payload: json,
      onlyData: false,
      onComplete: (res) => {
        if (res && res.IsSuccessful && res.Data) {
          if (res.Data.IsSucceed) {
            message.success(res.Data.Msg)
            this.getRunData()
          }
          else {
            message.error(res.Data.Msg)
          }
        }
      }
    })
  }

  render () {
    const { date, editing, dataSource, chartData } = this.state

    var length = dataSource.length
    const render0 = (value, row, index) => {
      return {
        children: value,
        props: {
          colSpan: index == length - 1 ? 0 : 1
        },
      }
    }
    const nums1 = [2, 9, 16, 23]
    const nums2 = [6, 13, 20]
    const arrs = new Array(24).fill(false)
    const children = arrs.map((item, i) => ({
      title: i + 1,
      dataIndex: "Hour" + (i + 1),
      key: "Hour" + (i + 1),
      editable: editing,
      render: (value, row, index) => {
        return {
          children: value,
          props: {
            colSpan: index == length - 1 ? (nums1.includes(i + 1) ? 4 : nums2.includes(i + 1) ? 3 : 0) : 1
          },
        }
      }

    }))

    const childrenCols = children.map((col) => {
      if (!col.editable) {
        return col
      }
      return {
        ...col,
        onCell: (record, index) => ({
          record,
          editable: index == length - 1 ? false : col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave
        })
      }
    })

    const columns = [
      {
        title: "序号",
        dataIndex: "Num",
        key: "Num",
        render: (value, row, index) => {
          return {
            children: value,
            props: {
              rowSpan: row.RowSpan,
              colSpan: index == length - 1 ? 2 : 1
            },
          }
        }
      },
      {
        title: "参数名称",
        dataIndex: "Name",
        key: "Name",
        width: 100,
        render: (value, row, index) => {
          return {
            children: value,
            props: {
              rowSpan: row.RowSpan,
              colSpan: index == length - 1 ? 0 : 1
            },
          }
        }
      },
      {
        title: "母线",
        dataIndex: "Generatrix",
        key: "Generatrix",
        render: (value, row, index) => {
          return {
            children: value,
            props: {
              rowSpan: row.RowSpan2,
              colSpan: index == length - 1 ? 3 : row.ColSpan
            },
          }
        }
      },
      {
        title: "柜号",
        dataIndex: "Container",
        key: "Container",
        render: (value, row, index) => {
          return {
            children: value,
            props: {
              colSpan: index == length - 1 ? 0 : row.ColSpan > 1 ? 0 : row.ColSpan
            },
          }
        }
      },
      {
        title: "时间",
        children: childrenCols
      },
      {
        title: "电能表读数",
        children: [
          {
            title: "有功",
            dataIndex: "ReadActive",
            key: "ReadActive",
            render: render0,
            editable: editing,
            onCell: (record) => ({
              record,
              editable: editing,
              dataIndex: "ReadActive",
              title: "有功",
              handleSave: this.handleSave
            })
          },
          {
            title: "无功",
            dataIndex: "ReadReactive",
            key: "ReadReactive",
            render: (value, row, index) => {
              return {
                children: value,
                props: {
                  colSpan: index == length - 1 ? 3 : 1
                },
              }
            },
            editable: editing,
            onCell: (record) => ({
              record,
              editable: editing,
              dataIndex: "ReadReactive",
              title: "无功",
              handleSave: this.handleSave
            })
          }
        ]
      },
      {
        title: "电量",
        children: [
          {
            title: "有功",
            dataIndex: "ElectricActive",
            key: "ElectricActive",
            render: render0
          },
          {
            title: "无功",
            dataIndex: "ElectricReactive",
            key: "ElectricReactive",
            render: render0
          }
        ]
      },
    ]

    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    }

    return (
      <>
        <LayoutCard style={{ marginBottom: '0.15rem' }}>
          <div className='advanced-search__form'>
            <Form>
              <Form.Item label='日期'>
                <DatePicker
                  allowClear={false}
                  value={date}
                  onChange={this.dateChange}
                  style={{ width: '100%' }}
                />
              </Form.Item>
              <div className='advanced-search__btns-zone'>
                <Button type='primary' onClick={this.btnClick}>查询</Button>
                {
                  editing ? <Button type='primary' onClick={this.runDataSave}>保存</Button> : null
                }
              </div>
            </Form>
          </div>
        </LayoutCard>
        <LayoutCard style={{ textAlign: 'right' }}>
          <ExportToExcel
            fileName='日运行表'
            insertRows={[`日运行表 ${moment(date).format('YYYY-MM-DD')}`]}
            tableId='KrElectricityReportPageExport'
          />
          <Table
            id='KrElectricityReportPageExport'
            size='small'
            bordered
            columns={columns}
            dataSource={dataSource}
            pagination={false}
            components={components}
            scroll={{ x: '100%' }}
            style={{ marginTop: 8 }}
          />
        </LayoutCard>
        <LayoutCard>
          <CommonChart
            chartId='KrElectricityReportPage'
            {...chartData}
            style={{ height: 300 }}
          />
        </LayoutCard>
      </>
    )
  }
}

export default connect(({ login, app }) => ({ login, app }))(Form.create()(KrElectricityReportPage))