import TabsContent from '@/components/TabsContent';
import { UnityAction } from '@/utils/utils';
import { connect } from '@umijs/max';
import { Button, Spin, Table, Tabs } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import ThresholdBar from './components/ThresholdBar';
import styles from './index.less';
const { TabPane } = Tabs;

const Analysis = (props) => {
  const Status = [
    { name: '异常', type: '1', data: [] },
    { name: '警告', type: '2', data: [] },
    { name: '提醒', type: '3', data: [] },
  ];

  const { list = [], processList, loading } = props;
  const [selectedRowKeys, setSelectedRowKeys] = useState();
  const [tab, setTab] = useState('1');

  const columns = [
    {
      title: '设备名称',
      width: '20%',
      render: (record) => (
        <div>
          {record.DeviceName}({record.DeviceCode})
        </div>
      ),
    },
    {
      title: '工艺单元',
      width: '14%',
      dataIndex: 'ProcessSectionId',
      render: (id) => {
        return processList.find((item) => item.id == id)?.name;
      },
    },
    {
      title: '阈值范围',
      width: '14%',
      render: (record) => {
        // let thresholds = [-3,4,6,1];
        let thresholds = record.fault_range.split(',');
        return (
          <div>
            {record.fault_range && (
              <ThresholdBar
                current={record.fault_result}
                thresholds={thresholds}
              />
            )}
            {record.plcs && (
              <Button
                type="primary"
                className={styles.anaBtn}
                onClick={() =>
                  handleBtnClick(
                    record.plcs,
                    record.DeviceName || record.DeviceCode,
                  )
                }
              >
                相关性分析
              </Button>
            )}
          </div>
        );
      },
    },
    {
      title: '可能原因',
      width: '20%',
      dataIndex: 'Reason',
    },
    {
      title: '解决方案',
      render: (record) => {
        if (record.FixPlan instanceof Array) {
          return (
            <div>
              {record.FixPlan.map((item) => (
                <div>
                  {item.content}
                  <br />
                </div>
              ))}
            </div>
          );
        } else {
          return record.FixPlan;
        }
      },
    },
  ];

  useEffect(() => {
    UnityAction.on('SynDev', selectedItem);
    return () => UnityAction.off('SynDev', selectedItem);
  }, [data, tab]);

  const selectedItem = (e) => {
    setSelectedRowKeys(e);
    console.log(data);
    // alert(e)
    const itemIndex = data?.findIndex((item) => item.type == tab);
    const item = data[itemIndex]?.data?.find(
      (item) => item.DeviceCode == e,
    );
    if (item) {
      const dom = document.querySelector(`tr[data-row-key="${item.index}"]`);
      if (dom) {
        let v = document.getElementsByClassName('ant-table-body')[itemIndex];
        v.scrollTop = dom.offsetTop;
      }
    }
  };

  const data = useMemo(() => {
    return Status.map((item, idx) => {
      const data = list?.filter((cur) => cur.grade_alarm == item.type);
      return { ...item, data };
    });
  }, [list]);

  const handleBtnClick = (plcs, title) => {
    if (!plcs) return;
    const msg = JSON.stringify(plcs); //[{ dataitemid: 'Raw_Water_Tank_Level', deviceid: '1436022785' }]
    // router.push(`/unity/smart-ops/chart-page/46?type=2&data=${msg}`);
    UnityAction.sendMsg(
      'ProcessAnalysisAbout',
      JSON.stringify({
        title,
        data: msg,
      }),
    );
  };

  const onTabChange = (tab) => {
    setTab(tab);
    setSelectedRowKeys(null);
    UnityAction.sendMsg('ProcessAnalysisType', tab);
  };

  // const rowSelection = {
  //   type: 'radio',
  //   selectedRowKeys,
  //   onChange: (selectedRowKeys, selectedRows) => {
  //     setSelectedRowKeys(selectedRowKeys);
  //     UnityAction.sendMsg('SynDev', selectedRows[0].DeviceCode);
  //   },
  // };

  const onSelectRow = (record, index) => {
    // const selectedList = [...selectedRowKeys];
    // if (selectedList[0] === index) return;
    // selectedList[0] = index;
    setSelectedRowKeys(index);
    UnityAction.sendMsg('SynDev', record.DeviceCode);
      };

  const setRowClassName = (record, index) => {
    if (!selectedRowKeys && selectedRowKeys !== 0) return;
    if (selectedRowKeys == index || selectedRowKeys == record.DeviceCode) {
      return styles.tableSelect;
    }
  };

  return (
    <Spin spinning={loading}>
      <TabsContent
        small={true}
        center={false}
        defaultActiveKey="1"
        items={data?.map((item) => {
          return {
            label: `${item.name}(${item.data?.length || 0})`,
            key: item.type,
            children: (
              <Table
                dataSource={item.data}
                columns={columns}
                rowKey={'index'}
                // rowSelection={rowSelection}
                rowClassName={setRowClassName}
                onRow={(record, index) => ({
                  onClick: () => onSelectRow(record, index),
                })}
                pagination={false}
                scroll={{ y: document.body.clientHeight - 730 }}
              />
            ),
          };
        })}
        onChange={onTabChange}
      />
    </Spin>
  );
};
export default connect(({ smartOps, loading }) => ({
  loading: loading.effects['smartOps/queryList'],
  list: smartOps.list.list,
  processList: smartOps.processList,
}))(Analysis);
