import IsBatchDelete from '@/components/BatchOperation/isBatchDelete';
import TableActionCard from '@/components/TableActionCard';
import StopBtn from '@/components/TableActionCard/stopBtn';
import {
  deleteProjectDeleteProject,
  deleteProjectDeleteProjectByIds,
  postProjectGetProjectList,
} from '@/services/project/Project';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { FormattedMessage, useAccess, useIntl } from '@umijs/max';
import { Tag, message } from 'antd';
import React, { useRef, useState } from 'react';
import { proTableCommonOptions, proTablePaginationOptions } from '../../../../config/defaultTable';
const TaskList: React.FC = () => {
  /**
   * @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);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();
  const actionRef = useRef<ActionType>();
  //  动态设置每页数量
  const [currentPageSize, setCurrentPageSize] = useState<number>(10);
  const [currentRow, setCurrentRow] = useState<API.Project>();
  const [selectedRowsState, setSelectedRows] = useState<API.Project[]>([]);

  const handleUpdateModal = () => {
    if (updateModalOpen) {
      setUpdateModalOpen(false);
      setCurrentRow(undefined);
    } else {
      setUpdateModalOpen(true);
    }
  };
  const handleCreateModal = () => {
    if (createModalOpen) {
      setCreateModalOpen(false);
      setCurrentRow(undefined);
    } else {
      setCreateModalOpen(true);
    }
  };
  const handleColumnDrawer = () => {
    if (showDetail) {
      setShowDetail(false);
      setCurrentRow(undefined);
    } else {
      setShowDetail(true);
    }
  };
  const handleDestroy = async (selectedRow: API.Project) => {
    deleteProjectDeleteProject({ 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 columns: ProColumns<API.Project>[] = [
    {
      title: <FormattedMessage id="task.task.table.list.name" defaultMessage="$$$" />,
      dataIndex: 'name',
      hideInSearch: false,
      key: 'fixedName',
      fixed: 'left',
    },

    {
        title: <FormattedMessage id="task.task.table.list.deviceGroup" defaultMessage="$$$" />,
        dataIndex: 'info',
        hideInSearch: true,
    },

    {
      title: <FormattedMessage id="task.task.table.list.state" defaultMessage="$$$" />,
      dataIndex: 'code',
      // hideInSearch: true,
      render: (dom) => {
        return (
          <Tag bordered={false} color={dom === 'XM00002'? "success": "error"}>
            {dom}
          </Tag>
        );
      },
    },

    {
      title: <FormattedMessage id="task.task.table.list.startTime" defaultMessage="$$$" />,
      dataIndex: 'createTime',
      hideInSearch: true,
      valueType: 'dateTime',
    },
    {
        title: <FormattedMessage id="task.task.table.list.runTime" defaultMessage="$$$" />,
        dataIndex: 'createTime',
        hideInSearch: true,
        valueType: 'dateTime',
    },

    {
        title: <FormattedMessage id="task.task.table.list.endTime" defaultMessage="$$$" />,
        dataIndex: 'createTime',
        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: 'destroy',
              renderDom: (
                <StopBtn
                  deleteApi={() => {
                    handleDestroy(record).then(() => {});
                  }}
                ></StopBtn>
              ),
            },
          ]}
        ></TableActionCard>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.Project>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.title',
          defaultMessage: '$$$',
        })}
        scroll={{ y: proTableCommonOptions.commscrollY, x: proTableCommonOptions.commscrollX }}
        options={{ fullScreen: true, setting: true, density: true, reload: true }}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: proTableCommonOptions.searchLabelWidth,
        }}
        onDataSourceChange={() => {}}
        pagination={{
          ...proTablePaginationOptions,
          pageSize: currentPageSize,
          onChange: (page, pageSize) => setCurrentPageSize(pageSize),
        }}
        columnsState={{
          persistenceKey: 'project_list',
          persistenceType: 'localStorage',
        }}
        tableAlertOptionRender={() => {
          return (
            <>
              {selectedRowsState?.length > 0 && (
                <IsBatchDelete
                  deleteApi={() => {
                    // TODO 需要；联调删除接口
                    deleteProjectDeleteProjectByIds({
                      ids: selectedRowsState.map((v: API.Project) => {
                        return v.id as number;
                      }),
                    }).then(() => {
                      actionRef.current?.reloadAndRest?.();
                    });
                  }}
                />
              )}
            </>
          );
        }}
        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 postProjectGetProjectList({ ...reqParams });
          return {
            data: resp.data.list.map((v: API.Project) => {
              return { ...v, key: v.id };
            }),
            success: resp.success,
            total: resp.data.total,
            current: resp.data.page,
            pageSize: resp.data.pageSize,
          };
        }}
        columns={columns}
        // rowSelection={{
        //   onChange: (_, selectedRows) => {
        //     setSelectedRows(selectedRows);
        //   },
        // }}
      />
    </PageContainer>
  );
};

export default TaskList;
