import ModuleTitle from '@/components/ManagementPage/moduleTitle';
import TabsContent from '@/components/TabsContent';
import ThresholdDetail from '@/components/ThresholdDetail';
import { UnityAction } from '@/utils/utils';
import { connect } from '@umijs/max';
import { Spin, Table, Tabs } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useMemo, useState } from 'react';
import styles from './DeviceAnalysis.less';

const { TabPane } = Tabs;

const DeviceAnalysis = (props) => {
  const Status = [
    { name: '异常', type: '0', data: [] },
    { name: '全部', type: '1 ', data: [] },
  ];

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

  const columns = [
    {
      title: '设备名称',
      render: (record) => (
        <div>
          {record.DeviceName}({record.DeviceCode})
        </div>
      ),
    },
    {
      title: '巡检项',
      width: '14%',
      dataIndex: 'TemplateItem',
      render: (TemplateItem) => <div>{TemplateItem.Name}</div>,
    },
    {
      title: '设定值范围',
      width: '40%',
      render: (record) => (
        <ThresholdDetail
          current={record.Value || 0}
          data={record || {}}
          // onClick={() => onClickThreshold(record)}
        />
      ),
    },
    {
      title: '状态',
      width: '14%',
      dataIndex: 'Status',
      render: (Status) => {
        switch (Status) {
          case -1:
          case 0:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#12CEB3' }}
                ></i>
                正常
              </div>
            );
          case 1:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#FE5850' }}
                ></i>
                异常
              </div>
            );
          case 2:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#FFE26D' }}
                ></i>
                警告
              </div>
            );
        }
      },
    },
  ];

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

  const selectedItem = (e) => {
    setSelectedRowKeys(e);
    console.log(data);
    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.Id}"]`);
      if (dom) {
        let v = document.getElementsByClassName('ant-table-body')[itemIndex];
        v.scrollTop = dom.offsetTop;
      }
    }
  };

  const data = useMemo(() => {
    return [
      {
        name: '异常',
        type: '1',
        data: autoReport?.extendWarningData,
        FluidLevelList: autoReport?.FluidLevelList?.filter(
          (item) => item.status,
        ),
        DrugFlowList: autoReport?.DrugFlowList?.filter((item) => item.status),
        WaterInCheckList: autoReport?.WaterInCheckList?.filter(
          (item) => item.status,
        ),
        PressureCompareList: autoReport?.PressureCompareList,
        WaterQualityCompareList: autoReport?.WaterQualityCompareList,
      },
      {
        name: '全部',
        type: '2',
        data: autoReport?.extendWarningAllData,
        FluidLevelList: autoReport?.FluidLevelList,
        DrugFlowList: autoReport?.DrugFlowList,
        WaterInCheckList: autoReport?.WaterInCheckList,
        PressureCompareList: autoReport?.PressureCompareList,
        WaterQualityCompareList: autoReport?.WaterQualityCompareList,
      },
    ];
  }, [autoReport]);

  const onTabChange = (tab) => {
    setTab(tab);
    setSelectedRowKeys(null);
    UnityAction.sendMsg('DevAnalysisType', 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}>
      <div style={{ height: 'calc(100vh - 5.6rem)', overflow: 'auto' }}>
        <TabsContent
          small={true}
          center={false}
          defaultActiveKey="1"
          items={data?.map((item) => {
            return {
              label: `${item.name}(${item.data?.length || 0})`,
              key: item.type,
              children: (
                <>
                  {(item.type === '1' ? item?.data?.length > 0 : true) && (
                    <>
                      <ModuleTitle title="设备检测" />
                      <Table
                        dataSource={item.data}
                        columns={columns}
                        rowKey="Id"
                        rowClassName={setRowClassName}
                        onRow={(record, index) => ({
                          onClick: () => onSelectRow(record, index),
                        })}
                        pagination={false}
                        // scroll={{ y: document.body.clientHeight - 730 }}
                      />
                    </>
                  )}
                  {(item.type === '1'
                    ? item?.FluidLevelList.length > 0
                    : true) && <LiquidLevel allData={item?.FluidLevelList} />}
                  {(item.type === '1'
                    ? item?.DrugFlowList.length > 0
                    : true) && <DosingFlow allData={item?.DrugFlowList} />}
                  {(item.type === '1'
                    ? item?.WaterInCheckList.length > 0
                    : true) && <WaterFlow allData={item?.WaterInCheckList} />}
                  {(item.type === '1'
                    ? item?.PressureCompareList.length > 0
                    : true) && (
                    <PressureGauge allData={item?.PressureCompareList} />
                  )}
                  {(item.type === '1'
                    ? item?.WaterQualityCompareList.length > 0
                    : true) && (
                    <WaterQuality allData={item?.WaterQualityCompareList} />
                  )}
                </>
              ),
            };
          })}
          onChange={onTabChange}
        />
      </div>
    </Spin>
  );
};
export default connect(({ eqSelfInspection, loading }) => ({
  loading: loading.effects['eqSelfInspection/getPatrolDataById'],
  autoReport: eqSelfInspection.autoReport,
}))(DeviceAnalysis);

const LiquidLevel = (props) => {
  const { allData } = props;

  const columns = [
    {
      title: '设备名称',
      width: '20%',
      dataIndex: 'device_name',
    },
    {
      title: '类型',
      key: 'template_item_name',
      dataIndex: 'template_item_name',
    },
    {
      title: '液位数',
      dataIndex: 'origin_value',
    },
    {
      title: '差值/比值',
      dataIndex: 'value',
    },
    {
      title: '设定值范围',
      width: '25%',
      render: (record) => (
        <ThresholdDetail
          current={record.value || 0}
          data={{
            JsonNumThreshold: record?.json_num_threshold,
            Type: record.type,
          }}
        />
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: '1.25rem',
      render: (status) => {
        switch (status) {
          case -1:
          case 0:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#60FE76' }}
                />
                正常
              </div>
            );
          case 1:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#FF8600' }}
                />
                异常
              </div>
            );
          case 2:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#FFE26D' }}
                />
                警告
              </div>
            );
          default:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#FF8600' }}
                />
                异常
              </div>
            );
        }
      },
    },
  ];

  return (
    <div>
      <ModuleTitle title="液位检测" />
      <Table dataSource={allData} columns={columns} />
    </div>
  );
};

const DosingFlow = (props) => {
  const { allData } = props;

  const columns = [
    {
      title: '设备名称',
      width: '15%',
      dataIndex: 'device_name',
    },
    {
      title: '类型',
      key: 'template_item_name',
      dataIndex: 'template_item_name',
    },
    {
      title: '实际流量',
      dataIndex: 'origin_value',
    },
    {
      title: '计量流量',
      dataIndex: 'value',
    },
    {
      title: '差值/比值',
      dataIndex: 'value',
    },
    {
      title: '设定值范围',
      width: '20%',
      render: (record) => (
        <ThresholdDetail
          current={record.value || 0}
          data={{
            JsonNumThreshold: record?.json_num_threshold,
            Type: record.type || 2,
          }}
        />
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: '1.25rem',
      render: (status) => {
        switch (status) {
          case -1:
          case 0:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#12CEB3' }}
                />
                正常
              </div>
            );
          case 1:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#FF8600' }}
                />
                异常
              </div>
            );
          case 2:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#FFE26D' }}
                />
                警告
              </div>
            );
          default:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#FF8600' }}
                />
                异常
              </div>
            );
        }
      },
    },
  ];
  return (
    <div>
      <ModuleTitle title="加药流量校验" />
      <Table dataSource={allData} columns={columns} />
    </div>
  );
};

const WaterFlow = (props) => {
  const { allData } = props;
  const columns = [
    {
      title: '设备名称',
      width: '20%',
      dataIndex: 'item_alias',
    },
    // {
    //   title: '实际流量',
    //   width: '20%',
    //   dataIndex: 'current_val',
    // },
    // {
    //   title: '计量流量',
    //   width: '16%',
    //   dataIndex: 'thresholds',
    // },
    {
      title: '差值',
      // width: '15%',
      dataIndex: 'current_val',
    },
    {
      title: '时间',
      // width: '15%',
      dataIndex: 'create_time',
      render: (text) => {
        if (text) {
          return dayjs(text).format('HH:mm:ss');
        }
        return '-';
      },
    },
    {
      title: '设定值范围',
      width: '30%',
      render: (record) => (
        <ThresholdDetail
          current={record.current_val || 0}
          data={{
            JsonNumThreshold: {
              exception: [
                { ThresholdValue: record?.thresholds, ThresholdType: 1 },
              ],
            },
            Type: 2,
          }}
        />
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: '1.25rem',
      render: (status) => {
        switch (status) {
          case -1:
          case 0:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#12CEB3' }}
                />
                正常
              </div>
            );
          case 1:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#FF8600' }}
                />
                异常
              </div>
            );
          case 2:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#FFE26D' }}
                />
                警告
              </div>
            );
          default:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#FF8600' }}
                />
                异常
              </div>
            );
        }
      },
    },
  ];

  return (
    <div>
      <ModuleTitle title="进出水流量校验" />
      <Table dataSource={allData} columns={columns} />
    </div>
  );
};

const PressureGauge = (props) => {
  const { allData } = props;

  const columns = [
    {
      title: '设备名称',
      width: '20%',
      key: 'item_alias',
      dataIndex: 'item_alias',
    },
    {
      title: '时间范围',
      key: 'dataRange',
      width: '1.5rem',
      render: (record) => {
        if (record.query_start && record.query_end) {
          return (
            <>
              {dayjs(record.query_start).format('HH:mm:ss')}
              <br />
              {dayjs(record.query_end).format('HH:mm:ss')}
            </>
          );
        }
        return '-';
      },
    },
    {
      title: (
        <>
          仪表
          <br />
          最小数
        </>
      ),
      width: '1.25rem',
      key: 'data_min',
      dataIndex: 'data_min',
    },
    {
      title: (
        <>
          仪表
          <br />
          最大数
        </>
      ),
      width: '1.25rem',
      key: 'data_max',
      dataIndex: 'data_max',
    },
    {
      title: '可能原因',
      key: 'content',
      dataIndex: 'content',
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      width: '1.25rem',
      render: (status) => {
        switch (status) {
          case -1:
          case 0:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#12CEB3' }}
                />
                正常
              </div>
            );
          case 1:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#FF8600' }}
                />
                异常
              </div>
            );
          case 2:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#FFE26D' }}
                />
                警告
              </div>
            );
          default:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#FF8600' }}
                />
                异常
              </div>
            );
        }
      },
    },
  ];

  return (
    <div>
      <ModuleTitle title="压力仪表校验" />
      <Table dataSource={allData} columns={columns} />
    </div>
  );
};

const WaterQuality = (props) => {
  const { allData } = props;

  const columns = [
    {
      title: '设备名称',
      width: '20%',
      key: 'item_alias',
      dataIndex: 'item_alias',
    },
    {
      title: '时间范围',
      key: 'dataRange',
      width: '1.5rem',
      render: (record) => {
        if (record.query_start && record.query_end) {
          return (
            <>
              {dayjs(record.query_start).format('HH:mm:ss')}
              <br />
              {dayjs(record.query_end).format('HH:mm:ss')}
            </>
          );
        }
        return '-';
      },
    },
    {
      title: (
        <>
          仪表
          <br />
          最小数
        </>
      ),
      width: '1.25rem',
      key: 'data_min',
      dataIndex: 'data_min',
    },
    {
      title: (
        <>
          仪表
          <br />
          最大数
        </>
      ),
      width: '1.25rem',
      key: 'data_max',
      dataIndex: 'data_max',
    },
    {
      title: '可能原因',
      key: 'content',
      dataIndex: 'content',
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      width: '1.25rem',
      render: (status) => {
        switch (status) {
          case -1:
          case 0:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#12CEB3' }}
                />
                正常
              </div>
            );
          case 1:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#FF8600' }}
                />
                异常
              </div>
            );
          case 2:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#FFE26D' }}
                />
                警告
              </div>
            );
          default:
            return (
              <div>
                <i
                  className={styles.iconStatus}
                  style={{ background: '#FF8600' }}
                />
                异常
              </div>
            );
        }
      },
    },
  ];

  return (
    <div>
      <ModuleTitle title="水质仪表校验" />
      <Table dataSource={allData} columns={columns} />
    </div>
  );
};
