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 {getAlarmRules} from '@/services/alarm/AlarmRules'
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 UpdateForm from './components/UpdateForm';
import UpdateMultiForm from './components/UpdateMultiForm';
import UpdateTimeForm from './components/UpdateTimeForm';
const AlarmRulesList: 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.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 [currentRow, setCurrentRow] = useState<API.DeviceCategory>();
  // 编辑弹框
  const [updateModalOpen, setUpdateModalOpen] = useState<boolean>(false);
  const [updateMultiModalOpen, setUpdateMultiModalOpen] = useState<boolean>(false);
  const [updateTimeModalOpen, setUpdateTimeModalOpen] = useState<boolean>(false);

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

    if (updateTimeModalOpen) {
      setUpdateTimeModalOpen(false);
    } else {
      setUpdateTimeModalOpen(true);
    }
  };

  const getAlarmRulesList = async () => {
    return {
        code: 0,
        success: true,
        data: {
            "list": [
                {
                    "id": 1,
                    "createTime": "2023-10-17T02:35:41.14308Z",
                    "updateTime": "2023-10-17T02:35:41.14308Z",
                    "name": "单人徘徊告警",
                    "status": "已启用",
                    "isEnabled": true,
                    "remark": ""
                },
                {
                    "id": 2,
                    "createTime": "2023-10-17T02:40:28.292883Z",
                    "updateTime": "2023-10-26T03:02:51.356036Z",
                    "name": "多人聚集告警",
                    "status": "未启用",
                    "isEnabled": false,
                    "remark": ""
                },
                {
                    "id": 4,
                    "createTime": "2023-12-12T02:54:52.204957Z",
                    "updateTime": "2023-12-12T02:54:52.204957Z",
                    "name": "敏感时间段告警",
                    "status": "未启用",
                    "isEnabled": false,
                    "remark": ""
                }
            ],
            "total": 3,
            "page": 1,
            "pageSize": 10
        },
        msg: "获取成功"
    }
  }

  const columns: ProColumns<API.DeviceCategory>[] = [
    {
      title: <FormattedMessage id="alarm_rules.page.name" defaultMessage="$$$" />,
      dataIndex: 'warning_name',
      hideInSearch: true,
    },

    {
      title: <FormattedMessage id="alarm_rules.page.id" defaultMessage="$$$" />,
      dataIndex: 'id',
      hideInSearch: true,
    },
    {
        title: <FormattedMessage id="alarm_rules.page.status" defaultMessage="$$$" />,
        dataIndex: 'is_use',
        hideInSearch: true,
        render: (dom) => {
            return (
              <Tag bordered={false} color={dom === 1? "success": ""} style={{
                // fontSize:14,
                color: dom === 1? '#52C41A': "#999"
              }}>
                {dom === 1 ? '已启用' : '未启用'}
              </Tag>
            );
        },
    },
    {
      title: <FormattedMessage id="alarm_rules.page.updateTime" defaultMessage="$$$" />,
      dataIndex: 'update_time',
      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={() => {
                      console.log(record);
                      if(record.id === 1) {
                        setUpdateModalOpen(true);
                      }else if(record.id === 2) {
                        setUpdateMultiModalOpen(true);
                      }else {
                        setUpdateTimeModalOpen(true);
                      }
                      setCurrentRow(record);
                    }}
                  >
                    <FormattedMessage id="common.edit" defaultMessage="Update" />
                  </Button>
                ),
              },
            // {
            //   key: 'destroy',
            //   renderDom: (
            //     <IsDelete
            //       deleteApi={() => {
            //         handleDestroy(record).then(() => {});
            //       }}
            //     ></IsDelete>
            //   ),
            // },
          ]}
        ></TableActionCard>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.DeviceCategory>
        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 getAlarmRules(reqParams);
          console.log(resp);
          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}
      />
      <UpdateForm
        updateModalOpen={updateModalOpen}
        values={currentRow || {}}
        handleModal={handleUpdateModal}
        reload={actionRef.current?.reload}
      />
      <UpdateMultiForm
        updateModalOpen={updateMultiModalOpen}
        values={currentRow || {}}
        handleModal={handleUpdateMultiModal}
        reload={actionRef.current?.reload}
      />
      <UpdateTimeForm
        updateModalOpen={updateTimeModalOpen}
        values={currentRow || {}}
        handleModal={handleUpdateTimeModal}
        reload={actionRef.current?.reload}
      />
    </PageContainer>
  );
};

export default AlarmRulesList;
