// 核心库
import React from 'react'
import { connect } from 'dva'
// 组件库
import { Menu, Input, Row, Col, Form, Radio, DatePicker, Button, Icon, Popconfirm, Result, Empty, message } from 'antd'
import { Scrollbars } from 'react-custom-scrollbars'
import { LayoutCard, IFComponent } from '@woowalker/feui'
import EditableTable from '../../EditListTable/EditableTable'
import CommonChart from '../../Chart/CommonChart'
// 工具库
import moment from 'moment'
import { initFilter, guid } from "../../../utils/common"

class EDProductUnitSetEditPage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      loading: false,
      // 配置项
      activeKey: '',
      unitSetList: [],
      // 配置项对应数据
      tableData: {},
      editTableData: [],
      num: 0,
      numT: 0,
      chartPEData: {},
      chartPGData: {},
      chartPWData: {},
      chartPCData: {},
      chartTEDataModel: {},
      chartTGDataModel: {},
      chartTWDataModel: {},
      chartTCDataModel: {},
      // 配置项校验
      formValid: {
        help: '',
        validateStatus: ''
      }
    }
    // scroll bar ref
    this.scrollRef = null
  }

  componentDidMount () {
    this.loadUnitSetList()
  }

  loadUnitSetList = () => {
    const { login, data, dispatch } = this.props
    const userGroupJson = initFilter(login.OrgId)
    userGroupJson.Parameter1 = data.id

    this.setState({ loading: true })
    dispatch({
      type: 'app/getDataByPost',
      url: 'ED/EDProductUnitSet/UnitSetOrderPaged',
      payload: userGroupJson
    }).then(res => {
      if (res) {
        this.setState({
          loading: false,
          unitSetList: res,
          activeKey: res[0]?.ID
        }, () => {
          res.length && this.loadData()
        })
      }
    })
  }

  /**
   * 加载选中项对应数据
   * @param {*} type update 或者 Add
   */
  loadData = (type = 'update') => {
    const { activeKey, unitSetList } = this.state
    const selectUnitSetList = unitSetList.find(item => item.ID === activeKey)

    const { login, data, dispatch } = this.props
    const userGroupJson = initFilter(login.OrgId)
    userGroupJson.Parameter1 = data.id
    userGroupJson.Parameter2 = selectUnitSetList.START_TIME
    userGroupJson.Parameter3 = selectUnitSetList.END_TIME
    userGroupJson.Parameter4 = selectUnitSetList.ID
    userGroupJson.Parameter5 = type

    return dispatch({
      type: 'app/getDataByPost',
      url: 'ED/EDProductUnitSet/GetProductUnitSetData',
      payload: userGroupJson
    }).then(res => {
      if (res) {
        const {
          tableData,
          chartPEData,
          chartPGData,
          chartPWData,
          chartPCoalData: chartPCData,
          chartTEDataModel,
          chartTGDataModel,
          chartTWDataModel,
          chartTCoalData: chartTCDataModel
        } = res
        // 先生成可保存的表格数据
        const editTableData = []
        for (let i = 0, len = tableData.data.length; i < len; i++) {
          const result = {}
          tableData.data[i].forEach(item => {
            result[item.fieldName] = item.value
          })
          editTableData.push(result)
        }
        this.setState({
          chartPEData,
          chartPGData,
          chartPWData,
          chartPCData,
          chartTEDataModel,
          chartTGDataModel,
          chartTWDataModel,
          chartTCDataModel,
          tableData,
          editTableData
        })
      }
    })
  }

  handleMenuSelected = ({ selectedKeys }) => {
    this.setState({ activeKey: selectedKeys[0] }, () => {
      const { unitSetList, activeKey } = this.state
      const find = unitSetList.find(item => item.ID === activeKey)
      this.loadData(find.newOption ? 'Add' : 'update')
    })
  }

  handleOptionAdd = () => {
    const activeKey = guid()
    this.setState({
      activeKey,
      unitSetList: [].concat(this.state.unitSetList, [{
        ID: activeKey,
        TITLE: `配置${this.state.unitSetList.length + 1}`,
        START_TIME: moment().format('YYYY-MM-DD'),
        END_TIME: moment().add(1, 'months').format('YYYY-MM-DD'),
        newOption: true
      }])
    }, () => {
      this.loadData('Add').then(() => {
        this.scrollRef && this.scrollRef.scrollToBottom()
      })
    })
  }

  handleOptionDel = () => {
    const { unitSetList, activeKey } = this.state
    const findIndex = unitSetList.findIndex(item => item.ID === activeKey)

    const lowerIndex = findIndex - 1
    const higherIndex = findIndex + 1
    const newActiveKey = lowerIndex >= 0 ? unitSetList[lowerIndex].ID : higherIndex <= unitSetList.length - 1 ? unitSetList[higherIndex].ID : ''

    if (unitSetList[findIndex].newOption) {
      message.success('删除成功')
      unitSetList.splice(findIndex, 1)
      this.setState({ activeKey: newActiveKey, unitSetList })
      return
    }

    this.props.dispatch({
      type: 'app/getDataByGet',
      url: 'ED/EDProductUnitSet/FullDelete',
      payload: { ID: unitSetList[findIndex].ID }
    }).then(res => {
      if (res) {
        message.success('删除成功')
        unitSetList.splice(findIndex, 1)
        this.setState({ activeKey: newActiveKey, unitSetList })
      }
    })
  }

  handleOptionSave = () => {
    const { unitSetList, activeKey, editTableData } = this.state
    const find = unitSetList.find(item => item.ID === activeKey)
    const { ID, TITLE, START_TIME, END_TIME } = find
    if (!TITLE) return

    const { data = {}, login, dispatch } = this.props
    const { TreeSelected = [] } = data
    const updateData = {
      orgId: login.OrgId,
      meterNodeId: TreeSelected.join(','),
      startTime: START_TIME,
      endTime: END_TIME,
      editListModel: JSON.stringify(editTableData),
      procuctUnitSetId: ID,
      title: TITLE
    }
    dispatch({
      type: 'app/getDataByPost',
      url: 'ED/EDProductUnitSet/AllUpdate',
      payload: updateData
    }).then(res => {
      res && message.success('保存成功')
    })
  }

  handleFormChange = (val, type) => {
    const { unitSetList, activeKey } = this.state
    const find = unitSetList.find(item => item.ID === activeKey)
    find[type] = val
    if (type === 'TITLE') {
      this.setState({
        formValid: {
          help: val ? '' : '请输入配置名称',
          validateStatus: val ? '' : 'error'
        }
      })
    } else {
      this.forceUpdate()
    }
  }

  handleChartChange = (value, type) => {
    this.setState({ [type]: value })
  }

  getChartData = (type, name) => {
    const { chartPEData, chartPGData, chartPWData, chartTEDataModel, chartTGDataModel, chartTWDataModel, chartPCData, chartTCDataModel } = this.state
    let chartData
    switch (type) {
      case 0:
        chartData = name === 'num' ? chartPEData : chartTEDataModel
        break
      case 1:
        chartData = name === 'num' ? chartPGData : chartTGDataModel
        break
      case 2:
        chartData = name === 'num' ? chartPWData : chartTWDataModel
        break
      case 3:
        chartData = name === 'num' ? chartPCData : chartTCDataModel
        break
      default:
        break
    }
    return {
      xAxis: chartData.XAxis ? chartData.XAxis[0].Data : [],
      yAxis: chartData.YAxis || [],
      data: chartData.Data || []
    }
  }

  render () {
    const { loading, unitSetList, activeKey, num, numT, tableData, formValid } = this.state
    const find = unitSetList.find(item => item.ID === activeKey) || {}
    const chartData = this.getChartData(num, 'num')
    const chartDataT = this.getChartData(numT, 'numT')
    return (
      <div style={{ width: '100%', height: '100%' }}>
        <div style={{ width: 100, height: '100%', float: 'left' }}>
          <IFComponent IF={!!unitSetList.length}>
            <Scrollbars
              ref={ref => this.scrollRef = ref}
              hideTracksWhenNotNeeded
              autoHeight
              autoHeightMax={384}
              autoHide
              autoHideTimeout={1000}
              autoHideDuration={200}
              style={{ marginBottom: 8 }}
            >
              <Menu
                mode='inline'
                selectedKeys={[activeKey]}
                onSelect={this.handleMenuSelected}
              >
                {
                  unitSetList.map(item => {
                    return (
                      <Menu.Item key={item.ID}>{item.TITLE}</Menu.Item>
                    )
                  })
                }
              </Menu>
            </Scrollbars>
          </IFComponent>
          <Button block icon='plus' onClick={this.handleOptionAdd}>新增</Button>
        </div>
        <div style={{ width: 'calc(100% - 108px)', height: '100%', float: 'right' }}>
          <IFComponent
            IF={!!unitSetList.length}
            ELSE={
              <Result
                icon={loading ? <Icon type='loading' /> : <Empty description=' ' />}
                title={loading ? '数据加载中，请稍后...' : '暂无配置项，请新增配置'}
                extra={<Button icon='plus' type='primary' onClick={this.handleOptionAdd}>新增</Button>}
              />
            }
          >
            <div className='scroll_page' style={{ overflow: 'hidden auto' }}>
              <LayoutCard>
                <Form layout='inline'>
                  <Form.Item label='配置名称' required {...formValid}>
                    <Input value={find.TITLE} onChange={evt => { this.handleFormChange(evt.target.value, 'TITLE') }} />
                  </Form.Item>
                  <Form.Item label='生效时间'>
                    <DatePicker
                      allowClear={false}
                      value={moment(find.START_TIME)}
                      onChange={(dt, ds) => { this.handleFormChange(ds, 'START_TIME') }}
                    />
                  </Form.Item>
                  <Form.Item label='失效时间'>
                    <DatePicker
                      allowClear={false}
                      value={moment(find.END_TIME)}
                      onChange={(dt, ds) => { this.handleFormChange(ds, 'END_TIME') }}
                    />
                  </Form.Item>
                  <Form.Item>
                    <Button type='primary' onClick={this.handleOptionSave}>保存</Button>
                  </Form.Item>
                  <Form.Item>
                    <Popconfirm
                      title="确定删除这条配置吗？"
                      onConfirm={this.handleOptionDel}
                      okText='确定'
                      cancelText='取消'
                    >
                      <Icon type='delete' />
                    </Popconfirm>
                  </Form.Item>
                </Form>
              </LayoutCard>
              <LayoutCard style={{ marginTop: 8 }}>
                <EditableTable
                  columns={tableData.columns}
                  data={tableData.data}
                  onEdit={val => this.setState({ editTableData: val })}
                />
              </LayoutCard>
              <Row gutter={8} style={{ marginTop: 8 }}>
                <Col span={12}>
                  <LayoutCard title='按产量统计' style={{ textAlign: 'center' }}>
                    <Radio.Group value={num} onChange={evt => this.handleChartChange(evt.target.value, 'num')}>
                      <Radio.Button value={0} key="EMCostPage_EM_1">电单耗</Radio.Button>
                      <Radio.Button value={1} key="EMCostPage_EM_2">气单耗</Radio.Button>
                      <Radio.Button value={2} key="EMCostPage_EM_3">水单耗</Radio.Button>
                      <Radio.Button value={3} key="EMCostPage_EM_4">标煤</Radio.Button>
                    </Radio.Group>
                    <CommonChart {...chartData} style={{ height: 300 }} />
                  </LayoutCard>
                </Col>
                <Col span={12}>
                  <LayoutCard title='按时间统计' style={{ textAlign: 'center' }}>
                    <Radio.Group value={numT} onChange={evt => this.handleChartChange(evt.target.value, 'numT')}>
                      <Radio.Button value={0} key="EMCostPage_EMT_1">电单耗</Radio.Button>
                      <Radio.Button value={1} key="EMCostPage_EMT_2">气单耗</Radio.Button>
                      <Radio.Button value={2} key="EMCostPage_EMT_3">水单耗</Radio.Button>
                      <Radio.Button value={3} key="EMCostPage_EMT_4">标煤</Radio.Button>
                    </Radio.Group>
                    <CommonChart {...chartDataT} style={{ height: 300 }} />
                  </LayoutCard>
                </Col>
              </Row>
            </div>
          </IFComponent>
        </div>
      </div>
    )
  }
}

export default connect(({ login, app }) => ({ login, app }))(EDProductUnitSetEditPage)
