import TableActionCard from '@/components/TableActionCard';
import { deviceStatusEnums } from '@/enums/status';
import { ActionType, PageContainer, ProCard, ProList } from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Modal, Tag } from 'antd';
import React, { useRef, useState } from 'react';
import { proTableCommonOptions, proTablePaginationOptions } from '../../../../config/defaultTable';
import DeviceStatusCard from './components/DeviceStatusCard';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { QuestionCircleFilled } from '@ant-design/icons';

/**
 * @交互说明
 * 1、列表分页展示服务器状态
 */
const tabOptions: Record<string, any> = {
  allStatus: 90,
  onlineStatus: 20,
  outlineStatus: 20,
  // processingStatus: 10,
  // errorStatus: 20,
};
export type DeleteBoxProps = {
  modalOpen: boolean;
  handleModal: () => void;
  values: any
  reload: any;
};

const ServerStatus: React.FC = () => {
  const [cardActionProps, setCardActionProps] = useState<'actions' | 'extra'>('extra');
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, setCreateModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 更新窗口的弹窗
   * */
  const [updateModalOpen, setUpdateModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 删除窗口
   * */
  const [modalOpen, setModalOpen] = useState(false);
  const [currentRow, setCurrentRow] = useState<Record<string, any>>({});
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  // const access = useAccess();
  // const intl = useIntl();
  const actionRef = useRef<ActionType>();
  //  动态设置每页数量
  const [currentPageSize, setCurrentPageSize] = useState<number>(8);

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

  const handleCreateModal = () => {
    if (createModalOpen) {
      setCreateModalOpen(false);
      setCurrentRow(undefined);
    } else {
      setCreateModalOpen(true);
    }
  };

  const handleUpdateModal = () => {
    if (updateModalOpen) {
      setUpdateModalOpen(false);
      setCurrentRow(undefined);
    } else {
      setUpdateModalOpen(true);
    }
  };

  const handleDestroy = async () => {
    if (modalOpen) {
      setModalOpen(false);
      setCurrentRow(undefined);
    } else {
      setModalOpen(true);
    }
    // deleteBusinessImageDeleteBusinessImage({ id: selectedRow.id })
    //   .then(() => {
    //     message.success(intl.formatMessage({ id: 'common.success', defaultMessage: '$$$' }));
    //     actionRef.current?.reload();
    //   })
    //   .catch(() => {
    //     message.error(intl.formatMessage({ id: 'common.failure', defaultMessage: '$$$' }));
    //   });
  };

  const { confirm } = Modal;
  const showConfirm = (record: any) => {
    confirm({
      title: `确定删除${record.name}吗`,
      icon: <QuestionCircleFilled />,
      content: '确定删除服务器1吗？删除后将找不到此服务器，请谨慎操作.',
      okText: '确认',
      cancelText: '取消',
      width: 560,
      onOk() {
        console.log('OK');
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  const dataTestList = [
    { 
      status: '在线' ,
      name: '服务器1'
    },
    { 
      status: '在线' ,
      name: '服务器2'
    },
    { 
      status: '在线' ,
      name: '服务器3'
    },
    { 
      status: '在线' ,
      name: '服务器4'
    },
    { 
      status: '在线' ,
      name: '服务器5'
    },
    { 
      status: '在线' ,
      name: '服务器6'
    },
    { 
      status: '在线' ,
      name: '服务器7'
    },
    { 
      status: '在线' ,
      name: '服务器8'
    },
  ].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: (
                    <Button
                      key="update"
                      type="link"
                      size="small"
                      onClick={() => {
                        setUpdateModalOpen(true);
                        setCurrentRow(record);
                      }}
                    >
                      <FormattedMessage id="pages.searchTable.edit" defaultMessage="Update" />
                    </Button>
                  ),
                },
                {
                  key: 'destroy',
                  renderDom: (
                    // <IsDelete
                    //   deleteApi={() => {
                    //     handleDestroy(record).then(() => {});
                    //   }}
                    // ></IsDelete>
                    <Button
                      key="destroy"
                      type="link"
                      size="small"
                      danger
                      onClick={() => {
                        setCurrentRow(record);
                        showConfirm(record);
                      }}
                    >
                      <FormattedMessage id="pages.searchTable.destroy" defaultMessage="destroy" />
                    </Button>
                  ),
                },
              ]}
            ></TableActionCard>
          </div>
          <DeviceStatusCard info={record}></DeviceStatusCard>{' '}
        </ProCard>
      ),
    };
  });

  return (
    <PageContainer
      title={false}
      content={
        <div style={{
          display: 'flex',
          justifyContent: 'space-between'
        }}>
          <div style={{
            fontWeight: 600,
            fontSize: 20,
            color: '#333'
          }}>服务器状态</div>
          <Button type="primary"
            onClick={() => {
              setCreateModalOpen(true);
            }}
          >
            <FormattedMessage id="resource.server_status.table.list.add" defaultMessage="add" />
          </Button>
        </div>
      }
    >
      <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: 4, 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,
          };
        }}
      />
      <CreateForm
        createModalOpen={createModalOpen}
        values={currentRow || {}}
        handleModal={handleCreateModal}
        reload={actionRef.current?.reload}
      />
      <UpdateForm
        updateModalOpen={updateModalOpen}
        values={currentRow || {}}
        handleModal={handleUpdateModal}
        reload={actionRef.current?.reload}
      />
    </PageContainer>
  );
};

export default ServerStatus;
