import AlarmLevelBox from '@/components/DictionaryBox/alarmLevel';
import TableActionCard from '@/components/TableActionCard';
import IsDelete from '@/components/TableActionCard/isDelete';
import { alarmLevelStatusEnum } from '@/enums/status';
import {
  deleteDeviceCategoryDeleteDeviceCategory,
  postDeviceCategoryGetDeviceCategoryList,
} from '@/services/device/DeviceCategory';
import { getInterfaces, postInterfaces, postTestDevice } from '@/services/alarm/Interfaces'
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Space, Tag, message } from 'antd';
import React, { useRef, useState } from 'react';
import { proTablePaginationOptions } from '../../../../config/defaultTable';
import { proIconForTableActionStyle } from '../../../../config/defaultIcon';
import { EditOutlined, InstagramOutlined, RedoOutlined } from '@ant-design/icons';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import CaptureForm from './components/CaptureForm';
import CaptureButton from './components/CaptureButton';
const InterfaceManageList: React.FC = () => {
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();
  const actionRef = useRef<ActionType>();
  //  动态设置每页数量
  const [currentPageSize, setCurrentPageSize] = useState<number>(10);

  const handleDestroy = async (selectedRow: API.UpdateInterfacesParams) => {
    postInterfaces({ id: selectedRow.id, device_status: '3' } )
      .then(() => {
        message.success(intl.formatMessage({ id: 'common.success', defaultMessage: '成功' }));
        actionRef.current?.reload();
      })
      .catch(() => {
        message.error(intl.formatMessage({ id: 'common.failure', defaultMessage: '失败' }));
      });
  };

  const [currentRow, setCurrentRow] = useState<API.UpdateInterfacesParams>();
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, setCreateModalOpen] = useState<boolean>(false);
  const handleCreateModal = () => {
    if (createModalOpen) {
      setCreateModalOpen(false);
      setCurrentRow(undefined);
    } else {
      setCreateModalOpen(true);
    }
  };
  // 编辑弹框
  const [updateModalOpen, setUpdateModalOpen] = useState<boolean>(false);

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

  // 最近拍摄
  const [captureModalOpen, setCaptureModalOpen] = useState<boolean>(false);

  const handleCaptureModal = () => {
    console.log(captureModalOpen);
    if (captureModalOpen) {
      setCaptureModalOpen(false);
      setCurrentRow(undefined);
    } else {
      setCaptureModalOpen(true);
    }
  };
  // 测试连接
  const [loading, setLoading] = useState<boolean>(false);
  const connection = (value: any) => {
    setLoading(true);
    postTestDevice({
      device_ip: value.device_ip,
      id: value.id,
    })
      .then((res) => {
        if(res.success) {
          message.success(res.msg);
        }
        setLoading(false);
      })
      .catch(() => {
        message.error(intl.formatMessage({ id: 'common.failure', defaultMessage: '失败' }));
        setLoading(false);
      });
  };


  const columns: ProColumns<API.UpdateInterfacesParams>[] = [
    {
      title: <FormattedMessage id="device.interface_manage.table.list.name" defaultMessage="接口名称" />,
      dataIndex: 'device_name',
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="alarm_rules.page.status" defaultMessage="设备状态" />,
      dataIndex: 'test_result',
      hideInSearch: true,
      render: (dom,entity) => {
          return (
            // <div>
            //   <Tag bordered={false} color={dom === 1? "success": ""} style={{
            //     // fontSize:14,
            //     color: dom === 1? '#52C41A': "#999"
            //   }}>
            //     {dom === 1 ? '在线' : '离线'}
            //   </Tag>
            //   <span>{moment(entity.appear_time).format('YYYY-MM-DD hh:mm:ss')}</span>
            //   <Button 
            //     type="link" 
            //     icon={<RedoOutlined />} 
            //     loading={loading}
            //     onClick={() => {
            //       connection(entity)
            //     }}
            //   />
            // </div>
            <CaptureButton 
              values={entity || {}}
              reload={actionRef.current?.reload} 
              />
          );
      },
    },
    // {
    //   title: <FormattedMessage id="device.interface_manage.table.list.address" defaultMessage="接口地址" />,
    //   dataIndex: 'device_api',
    //   hideInSearch: true,
    // },
    // {
    //   title: <FormattedMessage id="device.interface_manage.table.list.testTime" defaultMessage="状态查询时间" />,
    //   dataIndex: 'test_time',
    //   sorter: true,
    //   hideInSearch: true,
    //   valueType: 'dateTime',
    // },
    {
      title: <FormattedMessage id="device.interface_manage.table.list.createTime" defaultMessage="创建时间" />,
      dataIndex: 'create_time',
      sorter: true,
      hideInSearch: true,
      valueType: 'dateTime',
    },

    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="操作" />,
      dataIndex: 'option',
      valueType: 'option',
      width: '260px',
      fixed: 'right',
      render: (_, record) => [
        <TableActionCard
          key="TableActionCardRef"
          renderActions={[
            {
              key: 'capture',
              renderDom: (
                <Button
                  key="capture"
                  type="link"
                  size="small"
                  style={{
                      color:"#081FA8",
                  }}
                  icon={<InstagramOutlined style={{
                      marginRight: 3
                  }} />}
                  onClick={() => {
                    console.log('11');
                    setCaptureModalOpen(true);
                    setCurrentRow(record);
                  }}
                >
                  {/* 最近拍摄 */}
                  <FormattedMessage id="device.interface_manage.table.list.capture" defaultMessage="最近拍摄" />
                </Button>
              ),
          },
            {
                key: 'update',
                renderDom: (
                  <Button
                    key="update"
                    type="link"
                    size="small"
                    style={{
                        color:"#081FA8",
                    }}
                    icon={<EditOutlined style={{
                        marginRight: 3
                    }} />}
                    onClick={() => {
                      setUpdateModalOpen(true);
                      setCurrentRow(record);
                    }}
                  >
                    <FormattedMessage id="common.edit" defaultMessage="编辑" />
                  </Button>
                ),
            },
            {
              key: 'destroy',
              renderDom: (
                <IsDelete
                  deleteApi={() => {
                    handleDestroy(record).then(() => {});
                  }}
                ></IsDelete>
              ),
            },
          ]}
        ></TableActionCard>,
      ],
    },
  ];
  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="device.interface_manage.table.list.add" defaultMessage="新建设备/输入源" />
                </Button>
          </div>
        }
    >
      <ProTable<API.DeviceCategory>
        cardProps={{
          bodyStyle: {
            padding: 20
          }
        }}
        options={{ fullScreen: false, setting: false, density: false, reload: false }}
        actionRef={actionRef}
        rowKey="key"
        search={false}
        showSorterTooltip={false}
        pagination={{
          ...proTablePaginationOptions,
          pageSize: currentPageSize,
          onChange: (page, pageSize) => setCurrentPageSize(pageSize),
        }}
        columnsState={{
          persistenceKey: 'device_category_list',
          persistenceType: 'localStorage',
        }}
        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';
          }
        //   let resp = await postDeviceCategoryGetDeviceCategoryList({ ...reqParams });
          let resp = await getInterfaces({ ...reqParams });
          return {
            data: resp.data.results.map((v: API.DeviceCategory) => {
              return { ...v, key: v.id };
            }),
            success: resp.success,
            total: resp.data.count,
            current: resp.data.page,
            pageSize: resp.data.pageSize,
          };
        }}
        columns={columns}
      />
      <CreateForm
        createModalOpen={createModalOpen}
        values={currentRow || {}}
        handleModal={handleCreateModal}
        reload={actionRef.current?.reload}
      />
      <UpdateForm
        updateModalOpen={updateModalOpen}
        values={currentRow || {}}
        handleModal={handleUpdateModal}
        reload={actionRef.current?.reload}
      />
      <CaptureForm
        captureModalOpen={captureModalOpen}
        values={currentRow || {}}
        handleModal={handleCaptureModal}
        reload={actionRef.current?.reload}
      />
    </PageContainer>
  );
};

export default InterfaceManageList;
