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

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,
    tableLoading: 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 KrLoadRateReportPage extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      echertKey: guid(),
      dateYear: moment().format('YYYY'),
      editing: false,
      dataSource: []
    }
  }
  componentDidMount() {
    this.getRunData()
  }
  dateYearChange = (dateYear, str) => {
    this.setState({ dateYear: moment(dateYear).format('YYYY') })
  }
  onBarRef = (ref) => {
    this.barChild = ref
  }

  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: moment(this.state.dateYear).format('YYYY-MM-DD'),
    }
    this.setState({
      tableLoading: true,
    })
    dispatch({
      type: 'app/getDataByPost',
      url: 'BD/BDApplianceAttr/KrLoadRateOrderPaged',
      payload: json,
      onlyData: false,
      onComplete: (res) => {
        this.setState({
          tableLoading: false,
        })
        if (res && res.IsSuccessful && res.Data) {
          const { editing, data } = res.Data
          const currState = {
            editing: editing,
            dataSource: data,
            echertKey: guid()
          }
          this.setState(currState)
        }
      }
    })
  };
  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 { dateYear, editing, dataSource } = this.state
    const arrs = new Array(12).fill(false)
    const children = arrs.map((item, i) => ({
      title: i + 1,
      children: [
        {
          title: "实际电流(A)",
          dataIndex: "Month" + (i + 1),
          key: "Month" + (i + 1)
        },
        {
          title: "负荷率(%)",
          dataIndex: "value" + (i + 1),
          key: "value" + (i + 1)
        }],
      editable: editing
    }))

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

    const columns = [
      {
        title: "序号",
        dataIndex: "Num",
        key: "Num"
      },
      {
        title: "名称",
        dataIndex: "Name",
        key: "Name"
      },
      {
        title: "节点",
        dataIndex: "NodeName",
        key: "NodeName"
      },
      {
        title: "额定容量",
        dataIndex: "RATED_CAPACITY",
        key: "RATED_CAPACITY"
      },
      {
        title: "额定电流",
        dataIndex: "RATED_CURRENT",
        key: "RATED_CURRENT"
      },
      {
        title: "运行状态",
        dataIndex: "Status",
        key: "Status"
      },
      {
        title: "月份",
        children: childrenCols
      },
      {
        title: "年均负荷率",
        dataIndex: "AvgValue",
        key: "AvgValue"
      },
    ]

    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}
                  mode='year'
                  format='YYYY'
                  value={moment(this.state.dateYear, 'YYYY')}
                  onPanelChange={this.dateYearChange}
                />
              </Form.Item>
              <div className='advanced-search__btns-zone'>
                <Button type='primary' onClick={this.btnClick}>查询</Button>
              </div>
            </Form>
          </div>
        </LayoutCard>
        <LayoutCard style={{ textAlign: 'right' }}>
          <ExportToExcel
            fileName='负荷率表'
            insertRows={[`负荷率表 ${moment(dateYear).format('YYYY-MM-DD')}`]}
            tableId='KrLoadRateReportPageExport'
          />
          <Table
            id='KrLoadRateReportPageExport'
            size='small'
            loading={this.state.tableLoading}
            bordered
            columns={columns}
            dataSource={dataSource}
            pagination={false}
            components={components}
            scroll={{ x: '100%' }}
            style={{ marginTop: 8 }}
          />
        </LayoutCard>
      </>
    )
  }
}

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