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

class EDUnitUsePage2 extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      searchRules: [],
      boxProNameData: [],
      boxProNameDefaultValue: [],
      data: [],
      legend: [],
      xAxis: [],
      proData: [],
      selectData: [],
      selectKey: [],
      startTime: [],
      endTime: [],
      visible: false
    }
  }

  onBarRef = (ref) => {
    this.barChild = ref
  }

  onPieRef = (ref) => {
    this.pieChild = ref
  }

  onModalRef = (ref) => {
    this.modalChild = ref
  }

  showTitleModal = () => {
    this.setState({
      visible: true,
    })
  }

  handleOk = e => {
    this.setState({
      visible: false,
    })
  }

  handleCancel = e => {
    this.setState({
      visible: false,
    })
  }

  handleSearch = (value) => {
    var searchD = ""
    value.rules.forEach(d => {
      if (d.field == "SEARCH_DATE")
        searchD = d.value
    })

    var searchDate = searchD.split(',')
    let startDate = searchDate[0]
    let endDate = searchDate[1]
    let rule1 = {
      field: "Parameter1",
      operator: 0,
      value: startDate,
      isCustom: true,
      isSysParam: false,
    }
    let rule2 = {
      field: "Parameter2",
      operator: 0,
      value: endDate,
      isCustom: true,
      isSysParam: false,
    }
    let rule7 = {
      field: "Parameter7",
      operator: 0,
      value: "ProNameSelect_" + this.props.login.userId,
      isCustom: true,
      isSysParam: false,
    }
    let rule8 = {
      field: "Parameter8",
      operator: 0,
      value: "ProNameSelect_" + this.props.login.userId + "_Select",
      isCustom: true,
      isSysParam: false,
    }
    value.rules.push(rule1)
    value.rules.push(rule2)
    value.rules.push(rule7)
    value.rules.push(rule8)
    this.setState({
      searchRules: value,
    }, () => {
      this.getUnitUseChartData(value, true)
    })
  }

  //图表信息
  getUnitUseChartData = (value, isFirst) => {
    //非首次加载的话，加载选中条件
    for (var i = 0; i < value.rules.length; i++) {
      var v = value.rules[i]
      if (v.field == 'Parameter7' || v.field == 'Parameter8') {
        value.rules.splice(i--, 1)
      }
    }

    let rule7 = {
      field: "Parameter7",
      operator: 0,
      value: "ProNameSelect_" + this.props.login.userId,
      isCustom: true,
      isSysParam: false,
    }
    value.rules.push(rule7)

    let rule8 = {
      field: "Parameter8",
      operator: 0,
      value: "ProNameSelect_" + this.props.login.userId,
      isCustom: true,
      isSysParam: false,
    }
    value.rules.push(rule8)

    const json = initFilter(this.props.login.OrgId)
    addRuleAndGroups(json, value)
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'ED/EDUnitUse/ChartData',
      payload: json,
      onlyData: false,
      onComplete: (re) => {
        if (re && re.IsSuccessful && re.Data) {
          const chartDataModel = re.Data
          this.setState({
            xAxis: chartDataModel.XData.XAxis,
            legend: chartDataModel.Legend,
            data: chartDataModel.ChartApiData,
            searchRules: value,
            proData: chartDataModel.UnitUseProductData,
            selectKey: chartDataModel.SelectKey,
            selectData: chartDataModel.SelectData
          })
          this.barChild.setValue(this.state.xAxis, this.state.data, this.state.legend)
        }
      }
    })
  }

  //保存选中项
  ProNameSettingSave = (select, code, isReData = true) => {
    const json = {
      OrgId: this.props.login.OrgId,
      UserId: this.props.login.userId,
      ChildIds: select,
      Code: code
    }
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'FM/Product/ProNameSelectSave',
      payload: json,
      onlyData: false,
      onComplete: (re) => {
        if (re && re.IsSuccessful && re.Data) {
          if (isReData)
            this.getUnitUseChartData(this.state.searchRules, false)
        }
      }
    })
  }

  //选择列表显示数据项
  onSelectChange = (selectedRowKeys) => {
    if (selectedRowKeys.length == 0) {
      message.error("至少选中1个产品")
    }
    else {
      this.setState({ selectData: selectedRowKeys }, () => {
        this.ProNameSettingSave(this.state.selectData, "ProNameSelect_" + this.props.login.userId + "_Select", true)
      })
    }
  }

  //删除列表显示数据
  btnDelete = (id) => {
    var selectData = this.state.selectData
    var selectKey = this.state.selectKey
    //排除选中项
    for (var i = 0; i < selectData.length; i++) {
      if (selectData[i] == id) {
        selectData.splice(i--, 1)
      }
    }
    for (var j = 0; j < selectKey.length; j++) {
      if (selectKey[j] == id) {
        selectKey.splice(j--, 1)
      }
    }
    this.setState({ selectData: selectData, selectKey: selectKey }, () => {
      this.ProNameSettingSave(this.state.selectKey, "ProNameSelect_" + this.props.login.userId, true)
    })
  }

  showModal = () => {
    this.modalChild.showModal()
  }

  render () {
    const color = ["#54D9FD", "#CB0013"]
    const { searchRules } = this.state
    const { formParam, login, dispatch } = this.props
    const rowSelection = { selectedRowKeys: this.state.selectKey, onChange: this.onSelectChange }
    const render = (value, row, index) => {
      return <a style={{ color: row.Color }}>{value}</a>
    }
    const columns = [
      { title: '序号', dataIndex: 'INDEX', render },
      { title: '产品名称', dataIndex: 'PRODUCT_NAME', render },
      { title: '生产单元', dataIndex: 'UNIT_NAME', render },
      { title: '班组', dataIndex: 'CLASS_NAME', render },
      { title: '最大值', dataIndex: 'MAX', render },
      { title: '最小值', dataIndex: 'MIN', render },
      { title: '平均值', dataIndex: 'CURRENT', render },
      {
        title: '操作',
        dataIndex: 'Action',
        render: (value, row, index) => <a><Icon type="delete" Title='删除' onClick={() => this.btnDelete(row.key)} /></a>
      }
    ]
    return (
      <>
        <Search
          formId={this.props.formId}
          formCode={this.props.formCode}
          onSearch={this.handleSearch}
          iconEle={
            <>
              <Button onClick={this.showModal}>配置</Button>
              <Button style={{ marginLeft: 4 }} onClick={this.showTitleModal}>单耗说明</Button>
            </>
          }
        />
        <LayoutCard>
          <ChartLine onRef={this.onBarRef} color={color} />
        </LayoutCard>

        <LayoutCard>
          <Table size='small' rowSelection={rowSelection} columns={columns} dataSource={this.state.proData} />
        </LayoutCard>

        <EDUnitUseSettingModal
          onRef={this.onModalRef}
          getUnitUseChartData={this.getUnitUseChartData}
          searchRules={searchRules}
          login={login}
          formParam={formParam}
          dispatch={dispatch}
        />

        <Modal
          title="单耗说明"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <p>动态单耗即历史平均单位能耗，实现各品类具体产品的单耗计算</p>
          <p style={{ color: "black", fontWeight: "800" }}>计算公式：</p>
          <p style={{ color: "black", fontWeight: "800" }}>动态单耗 = 累计用能 ÷ 累计生产数</p>
        </Modal>
      </>
    )
  }
}

EDUnitUsePage2.propTypes = {
}

export default connect(({ login, loading, EMemOrder, custom, app }) => ({ login, loading, EMemOrder, custom, app }))(Form.create()(EDUnitUsePage2))
