import TableActionCard from '@/components/TableActionCard';
import IsDelete from '@/components/TableActionCard/isDelete';
import { getInterfacesUpload, postInterfacesUpload } from '@/services/realTime/interfaces';
import { EditOutlined } from '@ant-design/icons';
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, Tag, message } from 'antd';
import moment from 'moment';
import React, { useRef, useState } from 'react';
import { proTablePaginationOptions } from '../../../../config/defaultTable';
import CaptureForm from './components/CaptureForm';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
const OfflineDeviceList: 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) => {
    postInterfacesUpload({ 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 columns: ProColumns<API.UpdateInterfacesParams>[] = [
    {
      title: (
        <FormattedMessage
          id="device.interface_manage.table.list.videoName"
          defaultMessage="接口名称"
        />
      ),
      dataIndex: 'device_name',
      hideInSearch: true,
    },
    {
      title: (
        <FormattedMessage
          id="device.interface_manage.table.list.obtainMode"
          defaultMessage="获取方式"
        />
      ),
      dataIndex: 'operate_mode',
      hideInSearch: true,
      render: (dom) => {
        return (
          <div>
            {dom === 1 && 'FTP'}
            {dom === 2 && 'FTP上传'}
            {dom === 3 && '文件系统'}
          </div>
        );
      },
    },
    {
      title: (
        <FormattedMessage
          id="device.interface_manage.table.list.obtainStatus"
          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.create_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.addVideoSource"
              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 getInterfacesUpload({ ...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 OfflineDeviceList;
