// 核心库
import React from 'react'
import { connect } from 'dva'
// 组件库
import { Menu, Input, Row, Col, Form, Radio, Button, Icon, Popconfirm, Result, Empty, message, Modal } from 'antd'
import { Scrollbars } from 'react-custom-scrollbars'
import { LayoutCard, IFComponent, TableTransfer } from '@woowalker/feui'
// 工具库
import { initFilter, guid } from "../../../utils/common"
import { gradientColors } from '../../../utils/gradientColors'
// 样式
import styles from './index.css'

const { GradientCard } = LayoutCard
class FMVarCruveConfigModel extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      visible: false,
      loading: false,
      // 配置项
      activeKey: '',
      selectVar: {},
      selectVarCurve: [],
      //selectedVar: [],
      config_name: '',
      // 配置项对应数据
      tableData: {},
      dataSource: [],
      // 配置项校验
      formValid: {
        help: '',
        validateStatus: ''
      },
      paginat: {
        current: 1
      },
      search: ''
    }
    // scroll bar ref
    this.scrollRef = null
    this.columns = [{ title: '变量名称', dataIndex: 'NAME', key: 'NAME' }]
  }

  componentDidMount() {
    this.getCurveConfigs();
    if (this.props.onRef) {
      this.props.onRef(this)
    }
  }

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

    })

  }

  handleOK = e => {
    this.setState({
      visible: false
    }, () => {
      this.props.getTableData(this.state.activeKey)
    })
  }

  saveSetting = () => {
    const { selectVar } = this.state
    const json = {
      OrgId: this.props.login.OrgId,
      Data: selectVar
    }
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'FM/FMVarCurve/SaveVariableSetting',
      payload: json
    }).then(res => {
      if (res) {
        if (!res.IsSucceed) {
          message.error(res.Msg)
        }
      }
    })
  }

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

  getCurveConfigs = () => {
    const { login, dispatch } = this.props
    const json = initFilter(login.OrgId);
    return dispatch({
      type: 'app/getDataByPost',
      url: 'FM/FMVarCurve/getCurveConfigs',
      payload: json,
      onlyData: false
    }).then(res => {
      if (res && res.Data.length > 0) {
        this.setState({
          selectVarCurve: res.Data,
          selectVar: res.Data[0],
          activeKey: res.Data[0].ID,
        }, () => {

        })
      } else {
        this.handleOptionAdd();
      }
    })
  }


  getTransferData = ({ pagination, searchVal }) => {
    const { login, dispatch } = this.props
    const { activeKey, selectVar } = this.state
    var strActiveKey = activeKey;
    if (selectVar.newOption)
      strActiveKey = "";
    const json = initFilter(login.OrgId, searchVal, '', 0, pagination.current || 1, strActiveKey)
    return dispatch({
      type: 'app/getDataByPost',
      url: 'FM/FMVarCurve/GetTransferData',
      payload: json,
      onlyData: false
    }).then(res => {
      selectVar.Nav_VarCurveDetail = res.Data.selectedData;
      this.setState({ selectVar });

      return res;
    })
  }

  addTransferData = () => {
    const { login, dispatch } = this.props
    const json = initFilter(login.OrgId, '', '', 0, 1)
    return dispatch({
      type: 'app/getDataByPost',
      url: 'FM/FMVarCurve/AddTransferData',
      payload: json,
      onlyData: false
    }).then(res => {
      if (res?.Data?.selectVarCurve) {
        this.setState({ selectVarCurve: { Nav_VarCurveDetail: [] } })
      }
      return res
    })
  }

  handleTransferChange = (data) => {
    const { selectVar } = this.state

    selectVar.Nav_VarCurveDetail = data.map(({ ID, VAR_ID }) => ({
      VAR_CURVE_ID: this.state.activeKey,
      VAR_ID: VAR_ID, YAXIS_INDEX: 0, ORG_ID: this.props.login.OrgId
    }))
    this.setState({
      selectVar
    }, () => {
      //this.saveSetting()
      this.handleOptionSave(false);
    })
  }

  handleRadioChange = (evt, index) => {
    const { selectVar } = this.state
    selectVar.Nav_VarCurveDetail[index].YAXIS_INDEX = evt.target.value
    this.setState({ selectVar }, () => {
      //this.saveSetting()
    })
  }

  handleMenuSelected = ({ selectedKeys }) => {
    this.setState({
      activeKey: selectedKeys[0],
      selectVar: this.state.selectVarCurve.find(x => x.ID === selectedKeys[0])
    })
  }


  handleOptionAdd = () => {
    const activeKey = guid();
    var newOptionConfig = {
      ID: activeKey,
      CONFIG_NAME: `配置${this.state.selectVarCurve.length + 1}`,
      GET_INTERVALS: 1,
      Nav_VarCurveDetail: [],
      newOption: true
    };
    this.setState({
      activeKey,
      selectVarCurve: [].concat(this.state.selectVarCurve, [newOptionConfig]),
      selectVar: newOptionConfig
    }, () => {
      //this.saveSetting()
      this.addTransferData().then(() => {
        this.scrollRef && this.scrollRef.scrollToBottom()
      })
    })
  }

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

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

    if (selectVarCurve[findIndex].newOption) {
      message.success('删除成功')
      selectVarCurve.splice(findIndex, 1)
      this.setState({ activeKey: newActiveKey, selectVarCurve },
        () => {
          this.setState({
            selectVar: selectVarCurve.find(x => x.ID === newActiveKey)
          }, () => {
            //this.saveSetting()
          })
        });

      return
    }

    this.props.dispatch({
      type: 'app/getDataByGet',
      url: 'FM/FMVarCurve/FullDelete',
      payload: { ID: selectVarCurve[findIndex].ID }
    }).then(res => {
      if (res) {
        message.success('删除成功')
        selectVarCurve.splice(findIndex, 1)
        this.setState({ activeKey: newActiveKey, selectVarCurve },
          () => {
            this.setState({
              selectVar: selectVarCurve.find(x => x.ID === newActiveKey)
            }, () => {
              //this.saveSetting()

            })
          })
      }
    })
  }

  handleOptionSave = (msg) => {
    const { selectVar } = this.state
    const { login, dispatch } = this.props
    const updateData = {
      ID: selectVar.ID,
      ORG_ID: login.OrgId,
      USER_ID: login.userId,
      CONFIG_NAME: selectVar.CONFIG_NAME,
      GET_INTERVALS: selectVar.GET_INTERVALS,
      Nav_VarCurveDetail: selectVar.Nav_VarCurveDetail
    }
    dispatch({
      type: 'app/getDataByPost',
      url: 'FM/FMVarCurve/FullUpdate',
      payload: updateData
    }).then(res => {
      if (msg && res) {
        message.success('保存成功')
      }
      //
      selectVar.newOption = false;
      this.setState(selectVar);
    })
  }

  handleFormChange = (val) => {
    const { selectVarCurve, activeKey, selectVar } = this.state
    const find = selectVarCurve.find(item => item.ID === activeKey)
    find['CONFIG_NAME'] = val
    selectVar.CONFIG_NAME = val
    this.setState({
      formValid: {
        help: val ? '' : '请输入配置名称',
        validateStatus: val ? '' : 'error'
      },
      selectVarCurve,
      selectVar
    })
  }

  handleChartChange = (evt) => {
    const { selectVar } = this.state
    selectVar.GET_INTERVALS = evt.target.value
    this.setState({ selectVar }, () => {
      //this.saveSetting()
    })
  }

  render() {
    const { loading, selectVarCurve, activeKey, formValid, visible, selectVar } = this.state
    return (
      <Modal
        title='变量曲线配置'
        maskClosable={false}
        onOk={this.handleOK}
        onCancel={this.handleCancel}
        visible={visible}
        bodyStyle={{ padding: 8, backgroundColor: '#f2f2f2' }}
        width='80%'
        style={{ maxWidth: 1480, minWidth: 1200, top: '8%' }}
      >
        <div style={{ width: '100%', height: '70%' }}>
          <div style={{ width: 100, height: '100%', float: 'left' }}>
            <IFComponent IF={!!selectVarCurve.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}
                >
                  {
                    selectVarCurve.map(item => {
                      return (
                        <Menu.Item key={item.ID}>{item.newOption ? '*' : ''}{item.CONFIG_NAME}</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={!!selectVarCurve.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={selectVar?.CONFIG_NAME} onChange={evt => this.handleFormChange(evt.target.value)} />
                    </Form.Item>
                    <Form.Item label='数据间隔'>
                      <Radio.Group name='radiogroup' value={selectVar?.GET_INTERVALS} onChange={this.handleChartChange}>
                        <Radio value={0}>五分钟</Radio>
                        <Radio value={1}>一小时</Radio>
                        <Radio value={2}>一天</Radio>
                      </Radio.Group>
                    </Form.Item>
                    <Form.Item>
                      <Button type='primary' onClick={() => this.handleOptionSave(true)}>保存</Button>
                    </Form.Item>
                    <Form.Item>
                      <Popconfirm
                        title="确定删除这条配置吗？"
                        onConfirm={this.handleOptionDel}
                        okText='确定'
                        cancelText='取消'
                      >
                        <Button type='delete'>刪除</Button>
                      </Popconfirm>
                    </Form.Item>
                  </Form>
                </LayoutCard>
                <LayoutCard style={{ marginTop: 8 }}>
                  <div className={styles.fmvp_transfer}>
                    <TableTransfer
                      key={activeKey}
                      filterKey='NAME'
                      rowKey="VAR_ID"
                      totalKeypath='Data.totalCount'
                      maxSelected={9}
                      getData={this.getTransferData}
                      columns={[this.columns]}
                      onChange={this.handleTransferChange}
                    />
                  </div>
                  <div className={styles.fmvp_cardWrap}>
                    <Row gutter={8}>
                      {
                        selectVar?.Nav_VarCurveDetail != null && selectVar?.Nav_VarCurveDetail.length > 0 ?
                          selectVar?.Nav_VarCurveDetail.map((item, index) => {
                            const varName = item?.Nav_Var?.NAME
                            return (
                              <Col key={varName} span={8}>
                                <GradientCard
                                  title={varName}
                                  titleClassName={styles.fmvp_cardTitle}
                                  colors={gradientColors[index % gradientColors.length]}
                                  style={{ borderRadius: 4, marginBottom: 8 }}
                                >
                                  <Radio.Group
                                    value={item.YAXIS_INDEX}
                                    onChange={evt => this.handleRadioChange(evt, index)}
                                    style={{ padding: '8px 0' }}
                                  >
                                    <Radio value={0}>Y1轴</Radio>
                                    <Radio value={1}>Y2轴</Radio>
                                  </Radio.Group>
                                </GradientCard>
                              </Col>
                            )
                          }) : null
                      }
                    </Row>
                  </div>
                </LayoutCard>
              </div>
            </IFComponent>
          </div>
        </div>
      </Modal>
    )
  }
}

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