// 核心库
import React from 'react'
import { connect } from 'dva'
// 组件库
import { Form, Row, Col, Table, InputNumber, Popconfirm, message, Button } from 'antd'
import { Search, LayoutCard } from '@woowalker/feui'
// 工具库
import { initFilter, addRuleAndGroups } from '../../../utils/common'

const { GradientCard } = LayoutCard
const EditableContext = React.createContext();

class EditableCell extends React.Component {
  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      valChange,
      dataIndex,
      title,
      record,
      index,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0 }}>
            {getFieldDecorator(dataIndex, {
              rules: [
                {
                  required: true,
                  message: `请输入 ${title}!`,
                },
              ],
              initialValue: record[dataIndex],
            })(
              <InputNumber onChange={v => valChange(v, dataIndex)} />
            )}
          </Form.Item>
        ) : (
            children
          )}
      </td>
    );
  };

  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}


class EaEnergyAmortizeHistoryPage extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      statisticalDatas: [],
      data: [],
      total: 0,
      price: 0,
      loss: 0,
      editingKey: ''
    }
  }

  handleSearch = (value) => {
    value.rules.push({
      field: "Keyword",
      operator: 0,
      value: this.props.data.id,
      isCustom: true,
      isSysParam: false,
    })
    value.rules.push({
      field: 'Parameter1',
      operator: 0,
      value: this.props.formParam.Parameter1,
      isCustom: true,
      isSysParam: false,
    })
    this.setState({
      searchRules: value
    }, () => {
      this.getAmortizeHistoryData(value)
    })
  }

  getAmortizeHistoryData = (value) => {
    const json = initFilter(this.props.login.OrgId)
    addRuleAndGroups(json, value)
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'EA/AdjustAccounts/GetAmortizeHistoryData',
      payload: json,
      onlyData: false,
      onComplete: (re) => {
        if (re && re.IsSuccessful && re.Data && re.Data.data) {
          const { data, statisticalDatas, total, price } = re.Data
          const currState = {
            data,
            statisticalDatas,
            total,
            price,
            loss: 0,
          }
          this.setState(currState)
        }
      }
    })
  }

  dataSave = () => {
    const { data, loss } = this.state
    if (loss != 0) {
      message.error("可摊销量为0时才能保存！")
      return
    }
    const json = {
      OrgId: this.props.login.OrgId,
      Data: data
    };
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'EA/AdjustAccounts/AmortizeDataSave',
      payload: json,
      onlyData: false,
      onComplete: (re) => {
        if (re && re.IsSuccessful && re.Data) {
          if (re.Data.IsSucceed) {
            message.success(re.Data.Msg);
          }
          else
            message.error(re.Data.Msg);
        }
      }
    })
  }

  isEditing = record => record.key === this.state.editingKey;

  cancel = () => {
    this.setState({ editingKey: '' });
  };

  valChange = (value, dataIndex) => {
    const { total } = this.state
    if (dataIndex == 'Loss') {
      this.props.form.setFieldsValue({
        Ratio: total == 0 ? 0 : +((value / total) * 100).toFixed(2)
      })
    }
    if (dataIndex == 'Ratio') {
      this.props.form.setFieldsValue({
        Loss: +(total * (value / 100)).toFixed(3)
      })
    }
  }

  save(form, key) {
    form.validateFields((error, row) => {
      if (error) {
        return;
      }

      const { total, data, loss, price } = this.state
      if (row['Loss'] > total) {
        message.error('摊销量不能大于摊销总量！');
        return;
      }
      if (row['Ratio'] > 100 || row['Ratio'] < 0) {
        message.error('摊销比例必须大于等于0，小于等于100！');
        return;
      }
      const newData = [...data];
      const index = newData.findIndex(item => key === item.key);
      if (index > -1) {
        const item = newData[index];
        const newLoss = loss + (item.Loss - row['Loss']);
        const newPrice = total == 0 ? 0 : price * (row['Loss'] / total);
        item.Price = +newPrice.toFixed(3);
        item.Amortize = item.Value + row['Loss'];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        this.setState({ data: newData, editingKey: '', loss: +newLoss.toFixed(3) });
      } else {
        newData.push(row);
        this.setState({ data: newData, editingKey: '' });
      }
    });
  }

  edit(key) {
    this.setState({ editingKey: key });
  }


  render() {
    const { data, statisticalDatas, loss } = this.state
    const { formId, formCode } = this.props

    const dataSource = []
    for (let i = 0; i < data.length; i++) {
      let item = data[i];
      item.key = i;
      dataSource.push(item);
    }

    const components = {
      body: {
        cell: EditableCell,
      },
    };

    const list = [
      { title: '节点名称', dataIndex: 'NodeName' },
      { title: '器具名称', dataIndex: 'Name' },
      { title: '时间', dataIndex: 'Date' },
      { title: '计量值', dataIndex: 'Value' },
      { title: '摊销量', dataIndex: 'Loss', editable: true, },
      { title: '摊销比例（%）', dataIndex: 'Ratio', editable: true, },
      { title: '摊销结果', dataIndex: 'Amortize' },
      { title: '成本摊销（元）', dataIndex: 'Price' },
      {
        title: '操作',
        dataIndex: 'operation',
        render: (text, record) => {
          const { editingKey } = this.state;
          const editable = this.isEditing(record);
          return editable ? (
            <span>
              <EditableContext.Consumer>
                {form => (
                  <a
                    onClick={() => this.save(form, record.key)}
                    style={{ marginRight: 8 }}
                  >
                    保存
                  </a>
                )}
              </EditableContext.Consumer>
              <Popconfirm title="确定取消?" onConfirm={() => this.cancel(record.key)}>
                <a>取消</a>
              </Popconfirm>
            </span>
          ) : (
              <a disabled={editingKey !== ''} onClick={() => this.edit(record.key)}>
                编辑
              </a>
            );
        },
      },
    ]

    const columns = list.map((col, index) => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record),
          valChange: this.valChange,
        }),
      };
    })
    return (
      <>
        <Search
          formId={formId}
          formCode={formCode}
          onSearch={this.handleSearch}
        />
        <Row gutter={16} style={{ marginBottom: '0.15rem' }}>
          {
            statisticalDatas.map((item, index) => {
              return (
                <Col span={6} style={{ width: `${100 / statisticalDatas.length}%` }}>
                  <GradientCard
                    key={'GradientCard_EMUsePage2_' + index}
                    title={item.Name}
                    colorIndex={index}
                    style={{ borderRadius: '4px' }}>
                    <span style={{ fontSize: 20, lineHeight: 1 }}>
                      {`${index == statisticalDatas.length - 1 ? loss : item.Value}${item.Unit ? ' ' + item.Unit : ''}`}
                    </span>
                    <br />
                    {
                      item.Value2 ? <span>{item.Value2}</span> :
                        <span style={{ opacity: 0 }}>{'占位'}</span>
                    }
                  </GradientCard>
                </Col>
              )
            })
          }
        </Row>
        <LayoutCard style={{ textAlign: 'right' }}>
          <Button type='primary' icon="save" onClick={this.dataSave}>保存</Button>
          <EditableContext.Provider value={this.props.form}>
            <Table
              id='EaEnergyAmortizeHistoryPageExport'
              components={components}
              bordered
              size='small'
              columns={columns}
              dataSource={dataSource}
              style={{ marginTop: 8 }}
              rowClassName="editable-row"
              pagination={{ onChange: this.cancel }}
            />
          </EditableContext.Provider>
        </LayoutCard>
      </>
    )
  }
}

EaEnergyAmortizeHistoryPage.propTypes = {
}

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