import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Button, Card, Form, Input, message, Space, Table, Tag } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { queryDeviceOperations, queryDeviceOperationsData } from '@/services/afterSales/afterSales';
import DeviceStatusData from './deviceStatusData';
import DeviceHistory from '@/pages/AfterSales/AfterSalesManagement/deviceHistory';
import { DownloadOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import Overwrite from '@/pages/home/overwrite';
import { queryAfterSalesExport, queryOtaCheck, queryOtaUpdate } from '@/services/reportHome';

interface DataType {
  home_name: string;
  user_name: string;
  device_code: string;
  is_online: boolean;
  power: number;
  mode: number;
  speed: number;
  set_temp: number;
  temperature: number;
  humidity: number;
  fan_voltage: number;
  record_id: string;
}

const BannerManagement: React.FC = () => {
  const [dataList, setDataList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({ total: 0, current: 1, pageSize: 10 });
  const [historyVisible, setHistoryVisible] = useState(false);
  const [historyData, setHistoryData] = useState(null);
  const [statusVisible, setStatusVisible] = useState(false);
  const [statusData, setStatusData] = useState(null);
  const [form] = Form.useForm();
  const [searchData, setSearchData] = useState<object | null>({});
  const [visible, setVisible] = useState(false);
  const [editData, setEditData] = useState(null);

  const getList = () => {
    const params = {
      q: 'page',
      current: pagination.current,
      pageSize: pagination.pageSize,
      ...searchData,
    };
    queryDeviceOperations(params).then((res) => {
      if (res && res.code === 0) {
        setDataList(res.data.list || []);
        setPagination(res.data.pagination);
        setLoading(false);
      }
    });
  };

  // 切换分页
  const tableChange = (page: any) => {
    setLoading(true);
    const params = {
      q: 'page',
      current: page.current,
      pageSize: page.pageSize,
      ...searchData,
    };
    queryDeviceOperations(params).then((res) => {
      if (res && res.code === 0) {
        setDataList(res.data.list || []);
        setPagination(res.data.pagination);
        setLoading(false);
      }
    });
  };

  useEffect(() => {
    getList();
  }, []);

  useEffect(() => {
    getList();
  }, [searchData]);

  // 设备运行历史
  const onHistory = (record: any) => {
    setHistoryVisible(true);
    setHistoryData(record);
  };

  // 设备运行历史回调
  const onHistoryCallback = () => {
    setHistoryVisible(false);
  };

  // 24小时设备状态数据
  const onDeviceOperations = (record: any) => {
    queryDeviceOperationsData({ device_id: record.device_code }).then((res) => {
      if (res && res.code === 0) {
        const list = res.data.list || [];
        const result = list.reduce(
          (acc: Record<string, Record<string, any>>, { label, value, time }: any) => {
            if (!acc[time]) {
              // 如果不存在，则初始化一个新对象
              acc[time] = {};
            }

            // 将当前的 label 和 value 添加到对应的时间对象中
            acc[time][label] = value;

            return acc;
          },
          {},
        );

        const finalResult: any = Object.entries(result).map(([time, values]: any) => ({
          time,
          ...values,
        }));

        setStatusData(finalResult);
        setStatusVisible(true);
      }
    });
  };

  // 24小时设备状态数据回调
  const onStatusCallback = () => {
    setStatusVisible(false);
  };

  //  搜索
  const onFinish = () => {
    form.validateFields().then((data) => {
      setLoading(true);
      setSearchData(data);
    });
  };
  // 重置
  const onReset = () => {
    form.resetFields();
    setLoading(true);
    setSearchData(null);
  };

  // 下发
  const onOverwrite = (data: any) => {
    setVisible(true);
    setEditData(data);
  };

  // 下发弹框回调
  const overwriteCallback = () => {
    setVisible(false);
    getList();
  };

  // 导出
  const onExport = () => {
    form.validateFields().then((data) => {
      queryAfterSalesExport(data)
        .then((res: any) => {
          const link = document.createElement('a');
          link.style.display = 'none';
          link.href = window.URL.createObjectURL(new Blob([res]));
          link.setAttribute('download', '售后管理列表.xlsx');
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch(() => {
          message.error('导出失败');
        });
    });
  };

  // 升级
  const onUpgrade = (v: any) => {
    const params = {
      device_code: v.device_code,
      device_type_id: v.device_type,
    };
    queryOtaCheck(params)
      .then((res) => {
        if (res && res.code === 0) {
          if (res.data.need_update) {
            //   需要升级
            queryOtaUpdate(params)
              .then((item) => {
                if (item && item.code === 0) {
                  message.success('升级成功');
                } else {
                  message.error(res.message || '报错了');
                }
              })
              .catch((e) => {
                if (e && e.message) {
                  message.error(e.message || '报错了');
                }
              });
          } else {
            message.success('已是最新版本！');
          }
        } else {
          message.error(res.message || '报错了');
        }
      })
      .catch((e) => {
        if (e && e.message) {
          message.error(e.message || '报错了');
        }
      });
  };

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      align: 'center',
      key: 'index',
      render: (_: any, _row: any, index: number) => index + 1,
    },
    {
      title: '家名称',
      dataIndex: 'home_name',
      key: 'home_name',
    },
    {
      title: '用户名',
      dataIndex: 'user_name',
      key: 'user_name',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '地区',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '设备编号',
      dataIndex: 'device_code',
      key: 'device_code',
    },
    {
      title: '设备类型',
      dataIndex: 'device_type_name',
      key: 'device_type_name',
    },
    {
      title: '是否在线',
      dataIndex: 'is_online',
      key: 'is_online',
      render: (_, record: any) => {
        return (
          <Tag color={record.is_online ? 'green' : 'red'}>{record.is_online ? '在线' : '离线'}</Tag>
        );
      },
    },
    {
      title: '当前开关状态',
      dataIndex: 'power',
      key: 'power',
      render: (_, record: any) => {
        return (
          <Tag color={{ 0: 'red', 1: 'green' }[record.power]}>
            {{ 0: '关', 1: '开' }[record.power]}
          </Tag>
        );
      },
    },
    {
      title: '当前模式',
      dataIndex: 'mode',
      key: 'mode',
      render: (_, record: any) => {
        return (
          <span>{{ 0: '制冷', 1: '制热', 2: '除湿', 3: '送风', 4: '加湿' }[record.mode]}</span>
        );
      },
    },
    {
      title: '风速',
      dataIndex: 'speed',
      key: 'speed',
      render: (_, record: any) => {
        return (
          <span>
            {{ 1: '一档', 2: '二档', 3: '三档', 4: '四档', 5: '五档', 6: '六档' }[record.speed]}
          </span>
        );
      },
    },
    {
      title: '设定温度',
      dataIndex: 'set_temp',
      key: 'set_temp',
      render: (_, record: any) => {
        return `${record.set_temp}℃`;
      },
    },
    {
      title: '温度',
      dataIndex: 'temperature',
      key: 'temperature',
      render: (_, record: any) => {
        return `${record.temperature}℃`;
      },
    },
    {
      title: '湿度',
      dataIndex: 'humidity',
      key: 'humidity',
    },
    {
      title: '电压值',
      dataIndex: 'fan_voltage',
      key: 'fan_voltage',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              onHistory(record);
            }}
          >
            设备运行历史
          </a>
          <a
            onClick={() => {
              onDeviceOperations(record);
            }}
          >
            24小时设备状态数据
          </a>
          <a
            onClick={() => {
              onOverwrite(record);
            }}
          >
            远程配置
          </a>
          <a
            onClick={() => {
              onUpgrade(record);
            }}
          >
            升级
          </a>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <Card>
        <Form form={form} layout="inline" onFinish={onFinish} style={{ padding: '20px' }}>
          <Form.Item name="home_name" label="家名称">
            <Input placeholder="请输入家名称" />
          </Form.Item>
          <Form.Item name="user_name" label="用户名">
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item name="device_id" label="设备编号	">
            <Input placeholder="请输入设备编号" />
          </Form.Item>
          <Form.Item style={{ marginBottom: '10px' }}>
            <Space>
              <Button type="primary" htmlType="submit">
                <SearchOutlined />
                查询
              </Button>
              <Button htmlType="button" onClick={onReset}>
                <ReloadOutlined />
                重置
              </Button>
              <Button type="dashed" onClick={onExport}>
                <DownloadOutlined />
                导出
              </Button>
            </Space>
          </Form.Item>
        </Form>
        <Table
          columns={columns}
          dataSource={dataList}
          rowKey={(record) => record.record_id}
          pagination={pagination}
          loading={loading}
          onChange={tableChange}
        />
        {historyVisible && (
          <DeviceHistory
            visible={historyVisible}
            params={historyData}
            editCallback={onHistoryCallback}
          />
        )}
        {statusVisible && (
          <DeviceStatusData
            params={statusData}
            visible={statusVisible}
            editCallback={onStatusCallback}
          />
        )}
        {visible && (
          <Overwrite visible={visible} editCallback={overwriteCallback} params={editData} />
        )}
      </Card>
    </PageContainer>
  );
};
export default BannerManagement;
