import TableActionCard from '@/components/TableActionCard';
import IsConfirmAction from '@/components/TableActionCard/isConfirmAction';
import { deviceStatusEnums } from '@/enums/status';
import { PageContainer, ProCard, ProColumns, ProList } from '@ant-design/pro-components';
import { FormattedMessage } from '@umijs/max';
import { Button, Tag } from 'antd';
import React, { useState } from 'react';
import { proTableCommonOptions, proTablePaginationOptions } from '../../../../config/defaultTable';
import DetailInfoCard from './components/DetailInfoCard';
import DeviceStatusCard from './components/DeviceStatusCard';

/**
 * @交互说明
 * 1、列表分页展示分布式设备状态（分类查询）
 * 2、详情展示基础信息、日志
 * 3、重启设备
 */
const tabOptions: Record<string, any> = {
  allStatus: 90,
  onlineStatus: 20,
  outlineStatus: 20,
  processingStatus: 10,
  errorStatus: 20,
};

const DeviceStatus: React.FC = () => {
  const [cardActionProps, setCardActionProps] = useState<'actions' | 'extra'>('extra');
  const [detailModalOpen, setDetailModalOpen] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<Record<string, any>>({});
  //  动态设置每页数量
  const [currentPageSize, setCurrentPageSize] = useState<number>(8);

  const [activeTabIndex, setActiveTabIndex] = useState<number>(0);

  const handleDetailModal = () => {
    if (detailModalOpen) {
      setDetailModalOpen(false);
      setCurrentRow({});
    } else {
      setDetailModalOpen(true);
    }
  };

  const dataTestList = [
    { status: '在线' },
    { status: '在线' },
    { status: '故障' },
    { status: '故障' },
    { status: '运行中' },
    { status: '在线' },
    { status: '在线' },
    { status: '离线' },
  ].map((record, index) => {
    let currColor = 'default';
    switch (record.status) {
      case '在线':
        currColor = 'success';
        break;
      case '故障':
        currColor = 'error';
        break;
      case '运行中':
        currColor = 'warning';
        break;
      default:
        currColor = 'default';
        break;
    }
    return {
      content: (
        <ProCard
          className="gn"
          style={{ backgroundColor: '#FAFAFA', margin: 0, padding: 0 }}
          bodyStyle={{ margin: 0, padding: 0 }}
        >
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              padding: 12,
              justifyContent: 'space-between',
              borderBottom: '1px solid rgba(224, 224, 224, 1)',
            }}
          >
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                maxWidth: '60%',
              }}
            >
              <Tag color={currColor}>{record.status}</Tag>
              <p
                className="gn single_line text_1 fw7"
                style={{ maxWidth: '80%', padding: 0, margin: 0 }}
              >
                控制设备控制设备{index + 1}
              </p>
            </div>
            <TableActionCard
              key="TableActionCardRef"
              listType="proList"
              renderActions={[
                {
                  key: 'update',
                  renderDom: (
                    <IsConfirmAction
                      key="reOpen"
                      title={'重启'}
                      buttonFormatText={'pages.searchTable.reOpen'}
                      danger={true}
                      confirmAction={() => {
                        // setPublishModalOpen(true);
                        // putAlgorithmModelUpdateAlgorithmModel({
                        //   id: record.modelFkId,
                        //   defaultVersionFkId: record.id,
                        // })
                        //   .then(() => {
                        //     message.success(
                        //       intl.formatMessage({ id: 'common.success', defaultMessage: '$$$' }),
                        //     );
                        //   })
                        //   .catch(() => {
                        //     message.error(
                        //       intl.formatMessage({ id: 'common.failure', defaultMessage: '$$$' }),
                        //     );
                        //   });
                      }}
                    ></IsConfirmAction>
                  ),
                },
                {
                  key: 'detail',
                  renderDom: (
                    <Button
                      key="detail"
                      type="link"
                      size="small"
                      onClick={() => {
                        handleDetailModal();
                        setCurrentRow(record);
                      }}
                    >
                      <FormattedMessage id="pages.searchTable.detail" defaultMessage="Update" />
                    </Button>
                  ),
                },
              ]}
            ></TableActionCard>
          </div>
          <DeviceStatusCard info={record}></DeviceStatusCard>{' '}
        </ProCard>
      ),
    };
  });

  return (
    <PageContainer>
      <ProList<any>
        className="gn"
        ghost={true}
        itemCardProps={{
          ghost: true,
          bodyStyle: { padding: 0, margin: 0 },
        }}
        search={{
          labelWidth: proTableCommonOptions.searchLabelWidth,
        }}
        headerTitle={
          <>
            <div>
              {Object.keys(tabOptions).map((item, index) => {
                // eslint-disable-next-line react/jsx-key
                return (
                  <Button
                    style={{ marginRight: 12 }}
                    type={activeTabIndex === index ? 'primary' : 'default'}
                    key={index}
                    onClick={() => {
                      setActiveTabIndex(index);
                    }}
                  >
                    {Object.keys(deviceStatusEnums).includes(item)
                      ? deviceStatusEnums[item].miniName
                      : ''}
                  {"("+tabOptions[item]+ ')'}
                  </Button>
                );
              })}
            </div>
          </>
        }
        cardProps={{
          bodyStyle: {
            background: 'white',
            padding: '8px 16px 16px',
            borderRadius: 8,
          },
        }}
        pagination={{
          ...proTablePaginationOptions,
          pageSize: currentPageSize,
          onChange: (page, pageSize) => setCurrentPageSize(pageSize),
        }}
        showActions="hover"
        rowSelection={false}
        grid={{ gutter: 16, xs: 1, md: 2, lg: 2, xl: 3, xxl: 4 }}
        metas={{
          type: {
            // 不展示在筛选项
            hideInSearch: true,
          },
          content: {
            hideInSearch: true,
          },
          actions: {
            cardActionProps,
          },
          status1: {
            // 自己扩展的字段，主要用于筛选，不在列表中显示
            title: '设备组',
            valueType: 'select',
            valueEnum: {
              '0': { text: '全部设备分组', status: '0' },
              '1': {
                text: '设备分组1',
                status: '1',
              },
              '2': {
                text: '设备分组2',
                status: '2',
              },
              '3': {
                text: '设备分组3',
                status: '3',
              },
            },
          },
          status2: {
            // 自己扩展的字段，主要用于筛选，不在列表中显示
            title: '分类',
            valueType: 'select',
            valueEnum: {
              '0': { text: '全部分类', status: '0' },
              '1': {
                text: '外围监控',
                status: '1',
              },
              '2': {
                text: '室内监控',
                status: '2',
              },
              '3': {
                text: '违规监控',
                status: '3',
              },
            },
          },
        }}
        request={async (params = {}, sort) => {
          const { current, ...rest } = params;
          const reqParams = {
            page: current,
            desc: false,
            orderKey: '',
            ...rest,
          };
          if (sort && Object.keys(sort).length) {
            reqParams.orderKey = Object.keys(sort)[0];
            let sort_select = sort[reqParams.orderKey];
            reqParams.desc = sort_select === 'descend';
          }
          // TODO 联调查询设备状态接口
          // let resps = await postDeviceGroupGetDeviceGroupList({ ...reqParams });
          let resp = {
            success: true,
            data: {
              list: dataTestList,
              total: 8,
              page: 1,
              pageSize: 8,
            },
          };
          return {
            data: resp.data.list,
            success: resp.success,
            total: resp.data.total,
            current: resp.data.page,
            pageSize: resp.data.pageSize,
          };
        }}
      />
      <DetailInfoCard
        detailModalOpen={detailModalOpen}
        handleDetailModal={handleDetailModal}
      ></DetailInfoCard>
    </PageContainer>
  );
};

export default DeviceStatus;
