import IsBatchDelete from '@/components/BatchOperation/isBatchDelete';
import AlarmLevelBox from '@/components/DictionaryBox/alarmLevel';
import TableActionCard from '@/components/TableActionCard';
import IsDelete from '@/components/TableActionCard/isDelete';
import { alarmLevelStatusEnum } from '@/enums/status';
import { useAlarmSettingLevel } from '@/hooks/useAlarmSettingLevel';
import {
  deleteDeviceCategoryDeleteDeviceCategory,
  deleteDeviceCategoryDeleteDeviceCategoryByIds,
  postDeviceCategoryGetDeviceCategoryList,
} from '@/services/device/DeviceCategory';
import { EditOutlined, PlusOutlined, SettingOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProFormSelect, ProTable } from '@ant-design/pro-components';
import { Access, FormattedMessage, history, useAccess, useIntl } from '@umijs/max';
import { Button, Space, message } from 'antd';
import React, { useRef, useState } from 'react';
import { proIconForTableActionStyle } from '../../../../config/defaultIcon';
import { proTableCommonOptions, proTablePaginationOptions } from '../../../../config/defaultTable';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import AlarmStatusForm from './components/alarmStatusForm';
const DeviceCategoryList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, setCreateModalOpen] = useState<boolean>(false);
  // 告警状态设置
  const [alarmStatusModalOpen, setAlarmStatusModalOpen] = useState<boolean>(false);

  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, setUpdateModalOpen] = useState<boolean>(false);
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const access = useAccess();
  const intl = useIntl();
  const actionRef = useRef<ActionType>();
  //  动态设置每页数量
  const [currentPageSize, setCurrentPageSize] = useState<number>(10);
  const [currentRow, setCurrentRow] = useState<API.DeviceCategory>();
  const [selectedRowsState, setSelectedRows] = useState<API.DeviceCategory[]>([]);
  const { fetchAlarmSettingLevel } = useAlarmSettingLevel();

  /**
    1. 告警状态设置
    2. 项目部署告警添加
   */

  const handleUpdateModal = () => {
    if (updateModalOpen) {
      setUpdateModalOpen(false);
      setCurrentRow(undefined);
    } else {
      setUpdateModalOpen(true);
    }
  };
  const handleCreateModal = () => {
    if (createModalOpen) {
      setCreateModalOpen(false);
      setCurrentRow(undefined);
    } else {
      setCreateModalOpen(true);
    }
  };
  const handleAlarmStatusModal = () => {
    if (alarmStatusModalOpen) {
      setAlarmStatusModalOpen(false);
    } else {
      setAlarmStatusModalOpen(true);
    }
  };
  const handleDestroy = async (selectedRow: API.DeviceCategory) => {
    deleteDeviceCategoryDeleteDeviceCategory({ 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.DeviceCategory>[] = [
    {
      title: <FormattedMessage id="alarm.setting.table.list.name" defaultMessage="$$$" />,
      dataIndex: 'name',
      hideInSearch: false,
    },

    {
      title: <FormattedMessage id="alarm.setting.table.list.code" defaultMessage="$$$" />,
      dataIndex: 'code',
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="alarm.setting.table.list.category" defaultMessage="$$$" />,
      dataIndex: 'category',
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="alarm.setting.table.list.level" defaultMessage="$$$" />,
      dataIndex: 'level',
      hideInSearch: false,

      render: (text, record, index) => {
        console.log(text, record, index, 'level_record');
        const currVal = index % 6;
        const currLevel = alarmLevelStatusEnum[currVal];
        return (
          <Space>
            <AlarmLevelBox {...currLevel}></AlarmLevelBox>
            <span style={{ color: currLevel.color }}>{currLevel.label}</span>
          </Space>
        );
      },
      renderFormItem: () => {
        return (
          // TODO 需要在告警设置完成后实时改变
          <ProFormSelect
            placeholder={`${intl.formatMessage({
              id: 'alarm.setting.table.list.level',
              defaultMessage: '$$$',
            })}`}
            required={false}
            showSearch
            debounceTime={1000}
            request={async () => {
              return fetchAlarmSettingLevel();
            }}
          />
        );
      },
    },
    {
      title: <FormattedMessage id="alarm.setting.table.list.createTime" defaultMessage="$$$" />,
      dataIndex: 'createTime',
      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"
                //   onClick={() => {
                //     setUpdateModalOpen(true);
                //     setCurrentRow(record);
                //   }}
                // >
                //   <FormattedMessage id="common.edit" defaultMessage="Update" />
                // </Button>
                <EditOutlined
                  key="update"
                  style={{
                    color: 'rgba(21, 77, 221, 1)',
                    ...proIconForTableActionStyle,
                  }}
                  onClick={() => {
                    setUpdateModalOpen(true);
                    setCurrentRow(record);
                  }}
                />
              ),
            },
            {
              key: 'destroy',
              renderDom: (
                <IsDelete
                  buttonType="deleteIcon"
                  deleteApi={() => {
                    handleDestroy(record).then(() => {});
                  }}
                ></IsDelete>
              ),
            },
          ]}
        ></TableActionCard>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.DeviceCategory>
        headerTitle={intl.formatMessage({
          id: 'alarm.setting.table.title',
          defaultMessage: '$$$',
        })}
        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: 'device_category_list',
          persistenceType: 'localStorage',
        }}
        // tableAlertOptionRender={() => {
        //   return (
        //     <>
        //       {selectedRowsState?.length > 0 && (
        //         <IsBatchDelete
        //           deleteApi={() => {
        //             // TODO 需要；联调删除接口
        //             deleteDeviceCategoryDeleteDeviceCategoryByIds({
        //               ids: selectedRowsState.map((v: API.DeviceCategory) => {
        //                 return v.id as number;
        //               }),
        //             }).then(() => {
        //               actionRef.current?.reloadAndRest?.();
        //             });
        //           }}
        //         />
        //       )}
        //     </>
        //   );
        // }}
        toolBarRender={() => [
          <Access
            accessible={access.canUpdate(history.location.pathname)}
            key={`${history.location.pathname}-add`}
          >
            <Button
              type="primary"
              key="setting"
              onClick={() => {
                setAlarmStatusModalOpen(true);
              }}
            >
              <SettingOutlined />{' '}
              <FormattedMessage id="alarm.setting.table.list.setting" defaultMessage="New" />
            </Button>
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                setCreateModalOpen(true);
              }}
            >
              <PlusOutlined />{' '}
              <FormattedMessage id="alarm.setting.table.list.add" defaultMessage="New" />
            </Button>
          </Access>,
        ]}
        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 });
          return {
            data: resp.data.list.map((v: API.DeviceCategory) => {
              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);
          },
        }}
      />
      <AlarmStatusForm
        alarmStatusModalOpen={alarmStatusModalOpen}
        values={currentRow || {}}
        handleModal={handleAlarmStatusModal}
        reload={actionRef.current?.reload}
      />
      <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 DeviceCategoryList;
