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

const { MonthPicker } = DatePicker
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 EDWorkReportPage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      importUrl: '',
      echertKey: guid(),
      date: moment().format('YYYY-MM'),
      queryDate: moment().format('YYYY-MM'),
      editing: false,
      dateLen: 30,
      dataSource: []
    }
  }
  componentDidMount () {
    this.getConsumData()
  }
  dateChange = (date, str) => {
    this.setState({ date: str })
  }
  onBarRef = (ref) => {
    this.barChild = ref
  }

  btnClick = () => {
    this.getConsumData()
  };
  handleSave = (row) => {
    const newData = [...this.state.dataSource.Record]
    const index = newData.findIndex((item) => row.ID === item.ID)
    const item = newData[index]
    newData.splice(index, 1, {
      ...item,
      ...row
    })
    const source = { ...this.state.dataSource }
    source.Record = newData
    this.setState({ dataSource: source })
  };

  getConsumData = () => {
    const { login, dispatch } = this.props
    const json = initFilter(login.OrgId, this.state.date)
    const that = this
    //addRuleAndGroups(json, this.state.searchRules)
    //json["Parameter4"] = this.state.parentId;
    this.setState({
      Loading: true
    })
    dispatch({
      type: 'app/getDataByPost',
      url: 'ED/EDProdRecord/MonthProductRecord',
      payload: json,
      onlyData: false,
      onComplete: (res) => {
        if (res && res.IsSuccessful && res.Data) {
          this.setState({
            columns: res.Data.Colums,
          }, () => {
            this.setState(
              {
                dataSource: res.Data,
                editing: true,
                dateLen: res.Data.DateLen,
                queryDate: that.state.date
              }, () => {
                this.setState({
                  Loading: false
                })
              })
          })
        } else {
          this.setState({
            Loading: false
          })
        }
      }
    })
  };

  runDataSave = () => {
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'ED/EDProdRecord/SaveProductRecord',
      payload: this.state.dataSource,
      onlyData: true,
      onComplete: (res) => {
        if (res) {
          message.success('保存成功')
        }
      }
    })
  }
  fillImportData = (ret) => {
    if (!ret) {
      this.setState({
        data: [],
        selectedRowKeys: [],
        messages: '',
      })
      return
    }
    if (ret.ErrorMessage) {
      this.setState({
        messages: ('错误：' + ret.ErrorMessage)
      })
    }
    let messages = ''
    if (ret.Data && ret.Data.MessageList && ret.Data.MessageList.length) {
      var tmps = []
      ret.Data.MessageList.forEach((n, i) => {
        tmps.push(n)
      })
      messages = tmps.join('\n')
    }
    const selectedRowKeys = []
    if (ret.Data && ret.Data.Data) {
      ret.Data.Data.forEach((n, i) => {
        selectedRowKeys.push(n.ID)
      })
    }
    this.setState({
      data: (ret.Data && ret.Data.Data ? ret.Data.Data : []),
      selectedRowKeys,
      messages
    })
  }

  getDataUpdate = (update) => {
    if (update) {
      this.setState({ importUrl: 'api/PF/Import/ImportUpdate' })
    } else {
      this.setState({ importUrl: 'api/PF/Import/ImportUpdate' })
    }

  }

  render () {
    const { editing, dataSource, dateLen } = this.state
    const arrs = new Array(dateLen).fill(false)
    const children = arrs.map((item, i) => ({
      title: i + 1,
      dataIndex: 'Day' + (i + 1),
      key: 'Day' + (i + 1),
      editable: editing,
      align: 'center',
      render: (value, row, index) => {
        return {
          children: value,
        }
      }

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

    const columns = [
      {
        title: "序号",
        dataIndex: "Num",
        key: "Num",
        align: 'center',
        render: (value, row, index) => {
          return index + 1
        }
      },
      {
        title: "节点",
        dataIndex: "NODE_NAME",
        key: "NODE_NAME",
        width: 100,
        align: 'center',
        render: (value, row, index) => {
          return {
            children: value,
            props: {
              rowSpan: row.RowSpan
            }
          }
        }
      },
      {
        title: this.state.queryDate,
        align: 'center',
        children: childrenCols
      }
    ]


    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    }
    let url = this.state.importUrl
    const that = this
    const uploadProps = {
      showUploadList: false,
      name: 'file',
      action: config.serviceHost(url),
      data: { OrgId: that.props.login.OrgId, ImportConfigCode: 'configCode' },
      fileList: that.state.updateLoadFileList,
      accept: '.xls,.xlsx',
      onChange (info) {
        that.setState({
          updateLoadFileList: info.fileList,
        })

        if (info.file.status === 'done') {
          if (info.file.response.IsSuccessful) {
            if (url == 'api/PF/Import/ImportUpdate') {
              message.info(`${info.file.name} 导入并保存成功`)
            }
            that.fillImportData(info.file.response)
          } else {
            message.error(`${info.file.response.ErrorMessage} `)
          }
        } else if (info.file.status === 'error') {
          if (info.file.response && info.file.response.ErrorMessage) {
            message.error(`${info.file.name} 导入错误，详情：${info.file.response.ErrorMessage}`)
          }
          else {
            message.error(`${info.file.name} 导入错误`)
          }
        }
      },
    }
    return (
      <>
        <LayoutCard style={{ marginBottom: '0.15rem' }}>
          <div className='advanced-search__form'>
            <Form>
              <Form.Item label='月份'>
                <MonthPicker
                  allowClear={false}
                  value={moment(this.state.date, 'YYYY-MM')}
                  format={'YYYY-MM'}
                  onChange={this.dateChange}
                  style={{ width: '100%' }}
                />
              </Form.Item>
              <div className='advanced-search__btns-zone'>
                <Button type='primary' onClick={this.btnClick}>查询</Button>
                <div className='advanced-search__tool-wrap'>
                  <div className='advanced-search__children'>
                    <Upload {...uploadProps}>
                      <Button type='primary' onClick={() => this.getDataUpdate(true)}> <Icon type="upload" /> 导入</Button>
                    </Upload>
                  </div>
                  <div className='advanced-search__children'>
                    {
                      editing ? <Button type='primary' onClick={this.runDataSave}>保存</Button> : null
                    }
                  </div>
                  <ExportToExcel
                    fileName={'生产记录维护_' + this.state.date}
                    insertRows={['生产记录维护 ' + this.state.date]}
                    tableId='WorkPrportPagetTable'
                  />
                </div>
              </div>
            </Form>
          </div>
        </LayoutCard>
        <LayoutCard>
          <Table
            id='WorkPrportPagetTable'
            size='small'
            bordered
            columns={columns}
            dataSource={dataSource ? dataSource.Record : []}
            pagination={false}
            components={components}
            loading={this.state.Loading}
            scroll={{ x: '100%' }}
          />
        </LayoutCard>
      </>
    )
  }
}

EDWorkReportPage.propTypes = {
}

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