import React, {useEffect, useRef, useState} from 'react';
import { connect, history } from 'umi';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { dispatchHandle } from '@/utils/publicHandle';
import useFormTable from '@/useHooks/useFormTable';
import {Form, Card, Table, Button, Popconfirm, Divider} from 'antd'
import {PlusOutlined} from '@ant-design/icons'
import utilsStyles from '@/utils/utils.less';
import classNames from "classnames";
import styles from './index.less';

import AddGroup from './Modal/AddGroup'
import AddConfig from './Modal/AddConfig'
import BatchCreate from './Modal/BatchCreate'


const Index = (props) => {
  const {
    dispatch, loading,
    match: {params},
    opsGather: {robinGroupPage}
  } = props

  const {id} = params
  const name = decodeURIComponent(params.name)

  const [visible, setVisible] = useState(false);
  const [groupId, seGroupId] = useState();

  const [cVisible, setCVisible] = useState(false);
  const [maxLength, setMaxLength] = useState()

  const [bVisible, setBVisible] = useState(false);
  const [vVisible, setVVisible] = useState(false)
  const [modelId, setModelId] = useState()
  /**
   * @表单提交
   */
  const [form] = Form.useForm();
  const getListItems = (payload = {}) => {
    dispatchHandle(dispatch, 'opsGather/device_service_round_robin_group_post',
      {...payload, gatewayId: id}
      );
  }
  const { search, tableProps } = useFormTable(getListItems, {
    form,
  });

  const itemDelete = (id) => {
    dispatchHandle(dispatch, 'opsGather/device_service_round_robin_group_id_delete', {id}, () => {
      search.refresh()
    })
  }
  /**
   * @页面方法
   */
  const handleClose = () => {
    seGroupId()
    setVisible(false);
  }
  const openEdit = id => {
    seGroupId(id);
    setVisible(true);
  }

  const openConfig = (record) => {
    seGroupId(record.id)
    setCVisible(true);
    const robin = record?.roundRobinList;
    const lastIndex = robin?.length > 0 ? robin[robin?.length -1].groupRelationNum : 0;
    setMaxLength(lastIndex)
    dispatchHandle(dispatch,
      'opsGather/device_service_round_robin_post',
      {gatewayId: record.gatewayId, bindRoundRobinGroupIs: false}
    )
  }
  const closeConfig = id => {
    seGroupId()
    setCVisible(false);
  }

  const openView = (num, meterModelId) => {
    dispatchHandle(dispatch,
      'opsGather/device_service_meter_model_command_template_command_example_meterModelId_num_post',
      {num, meterModelId});
  }


  /**
   * @Table方法
   */
  const tableDelete = (id) => {
    dispatchHandle(dispatch,
      'opsGather/device_service_round_robin_group_relation_id_delete',
      {id},
      () => {
        search.refresh()
    });
  }
  const download = () => {
    dispatchHandle(dispatch,
      'opsGather/device_service_round_robin_record_downRoundRobin_post',
      {gatewayId: parseInt(id, 10), isSync: true}
      )
  }
  const downloadWitch = () => {
    dispatchHandle(dispatch,
      'opsGather/device_service_round_robin_group_send_to_gateway_gatewayId_put',
      {gatewayId: parseInt(id, 10)}
    )
  }
  const columns = [
    { title: '轮询组序号', dataIndex: 'groupNum'},
    { title: '轮询组名称', dataIndex: 'name'},
    { title: '网关编号', dataIndex: 'gatewayCode'},
    { title: '操作', dataIndex: 'option', disabled: true, key: 'option',
      render: (text, record) => (
        <>
          <a onClick={() => openEdit(record.id)}>编辑</a>
          <Divider type="vertical" />
          <a onClick={() => openConfig(record)}>添加轮询组</a>
          <Divider type="vertical" />
          <Popconfirm title="确认删除此轮询组吗?" onConfirm={() => itemDelete(record.id)}>
            <a>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ]

  const expandedRowRender = (dataSource) => {
    const childColumns = [
      { title: 'num', dataIndex: 'groupRelationNum'},
      { title: '轮询Id', dataIndex: 'pollingId' },
      { title: '命令', dataIndex: 'command' },
      { title: '操作', dataIndex: 'option',
        render: (val, record) =>
          <Popconfirm title="确认删除此轮询吗?" onConfirm={() => tableDelete(record.groupRelationId)}>
            <a>删除</a>
          </Popconfirm>
      }
    ]

    return (
      <Table
        loading={loading}
        bordered
        size="small"
        rowKey={(record) => record.id}
        pagination={false}
        columns={childColumns}
        dataSource={dataSource}
      />
    )
  }
  const expandable = {
    expandedRowRender: (record) => expandedRowRender(record?.roundRobinList || [])
  }

  useEffect(() => {
    dispatchHandle(dispatch, 'opsGather/device_service_gateway_post')
    dispatchHandle(dispatch, 'opsGather/device_service_meter_model_list')
  }, [])

  return (
    <PageHeaderWrapper title="轮询组">
      <div className={ classNames(utilsStyles.disFlexCol, utilsStyles.fullContainer) }>
        <div className={styles.full_flex}>
          <Card size="small" className={styles.full_flex}>
            <h1>{name}</h1>
            <Button
              type='primary'
              style={{ marginRight: 15, marginBottom: 15 }}
              onClick={() => setVisible(true)}
            >
              <PlusOutlined />添加轮询配置组
            </Button>
            <Button
              type='primary'
              style={{ marginRight: 15, marginBottom: 15 }}
              onClick={() => setBVisible(true)}
            >批量生成轮询组</Button>
            {/*<Button*/}
            {/*  type='primary'*/}
            {/*  style={{ marginRight: 15, marginBottom: 15 }}*/}
            {/*  onClick={download}*/}
            {/*>下发轮询配置</Button>*/}
            <Button
              type='primary'
              style={{ marginRight: 15, marginBottom: 15 }}
              onClick={downloadWitch}
            >下发已关联组轮询配置</Button>
            <Form form={form}/>
            <Table
              bordered
              size="small"
              rowKey={(record) => record.id}
              dataSource={robinGroupPage.list}
              pagination={robinGroupPage.pagination}
              columns={columns}
              {...tableProps}
              expandable={expandable}
            />
          </Card>
        </div>
        <AddGroup
          groupId={groupId}
          visible={visible}
          gatewayId={id}
          handleClose={handleClose}
          update={search.refresh}
        />
        <AddConfig
          maxNum={maxLength}
          groupId={groupId}
          visible={cVisible}
          handleClose={closeConfig}
          update={search.refresh}
        />
      </div>
      <BatchCreate
        gateWayId={id}
        visible={bVisible}
        handleClose={() => setBVisible(false)}
        update={search.refresh}
        onView={openView}
      />
    </PageHeaderWrapper>
  );
};

export default connect(({ opsGather, loading }) => ({
  opsGather,
  loading: loading.models.opsGather,
}))(Index);