import TableActionCard from '@/components/TableActionCard';
import IsDelete from '@/components/TableActionCard/isDelete';
import {
  deleteDeviceCategoryDeleteDeviceCategory,
  postDeviceCategoryGetDeviceCategoryList,
} from '@/services/device/DeviceCategory';
import { getInterfaces, postInterfaces } from '@/services/alarm/Interfaces'
import { getUserList } from '@/services/system/User'
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 } from '@ant-design/icons';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
const UserList: 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.UserList) => {
    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.UserList>();
  /**
   * @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 columns: ProColumns<API.UserList>[] = [
    {
      title: <FormattedMessage id="system.user.table.list.userName" defaultMessage="$$$" />,
      dataIndex: 'username',
      hideInSearch: true,
    },

    {
      title: <FormattedMessage id="system.user.table.list.remark" defaultMessage="$$$" />,
      dataIndex: 'note',
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="system.user.table.list.createTime" defaultMessage="$$$" />,
      dataIndex: 'date_joined',
      sorter: true,
      hideInSearch: true,
      valueType: 'dateTime',
    },

    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, record) => [
        <TableActionCard
          key="TableActionCardRef"
          renderActions={[
            {
                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="Update" />
                  </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="system.user.table.list.create" defaultMessage="add" />
            </Button>
        </div>
        }
    >
      <ProTable<API.UserList>
        cardProps={{
          bodyStyle: {
            padding: 20
          }
        }}
        options={{ fullScreen: false, setting: false, density: false, reload: false }}
        actionRef={actionRef}
        rowKey="key"
        search={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 getUserList({ ...reqParams });
          return {
            data: resp.data.results.map((v: API.UserList) => {
              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}
      />
    </PageContainer>
  );
};

export default UserList;
