/*
 * @Author: donghao donghao@supervision.ltd
 * @Date: 2024-04-22 15:23:36
 * @LastEditors: donghao donghao@supervision.ltd
 * @LastEditTime: 2024-06-19 11:42:02
 * @FilePath: \general-ai-platform-web\src\pages\Business\DeviceGroup\components\deviceList.tsx
 * @Description: 设备节点设置 关键词 deviceGroup（dg）
 * @交互说明
 * 1、设备列表：分页展示、新建、编辑、删除
 * 2、基础模型配置：参数配置
 * 3、设备分类：分类标记不可删除
 * 待定：
 * 是否需要编辑
 */
import InnerPageBack from '@/components/Back/innerPageBack';
import TableActionCard from '@/components/TableActionCard';
import {
  apiDeviceClassification,
  apiDeviceClassificationAdd,
  apiDeviceClassificationDelete,
} from '@/services/business/device';
import {
  apiEntityNodesDeviceDelete,
  apiEntityNodesDeviceInfo,
  apiEntityNodesDeviceList,
} from '@/services/business/entity';
import { isSuccessApi } from '@/utils/forApi';
import { ProTable } from '@ant-design/pro-components';
import { Access, FormattedMessage, history, useAccess, useIntl } from '@umijs/max';
import { Button, message } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

import { proTablePaginationOptions } from '../../../../../config/defaultTable';

import CategorizeUpdate from '@/components/CategorizeUpdate';
import IsDelete from '@/components/TableActionCard/isDelete';
import CreateDeviceForm from './createDeviceForm';
import UpdateDeviceForm from './updateDeviceForm';

import ModelSetting from './modelSetting';

type DeviceListProps = {
  commInfo: Record<string, any>;
  nodeInfo: Record<string, any>;
};

const DeviceList: React.FC<DeviceListProps> = (props) => {
  /**state */
  const access = useAccess();
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const intl = useIntl();
  const actionRef = useRef<ActionType>();

  const [createModalOpen, setCreateModalOpen] = useState<boolean>(false);
  const [updateModalOpen, setUpdateModalOpen] = useState<boolean>(false); // 编辑窗口是否打开

  const [currentRow, setCurrentRow] = useState<Record<string, any>>({});

  //  动态设置每页数量
  const [currentPageSize, setCurrentPageSize] = useState<number>(10);
  // 设置分类
  const [deviceTypeOpen, setDeviceTypeOpen] = useState<boolean>(false);

  // 设置行业类别
  const handleSetDeviceType = () => {
    setDeviceTypeOpen(!deviceTypeOpen);
  };

  // 基础模型设置 isSettingOpen
  const [isSettingOpen, setIsSettingOpen] = useState<boolean>(false);

  /**新增 编辑 删除 */
  // 新增
  const handleCreateModal = () => {
    setCreateModalOpen(!createModalOpen);
  };
  // 编辑
  const handleUpdateModal = () => {
    setUpdateModalOpen(!updateModalOpen);
  };

  // 设备节点信息
  async function loadDetail(record) {
    const resp = await apiEntityNodesDeviceInfo({ device_id: record?.id });
    if (isSuccessApi(resp) && resp?.data) {
      setCurrentRow({ ...resp?.data, device_id: record?.id });
    }
  }

  function reloadList() {
    actionRef.current?.reload();
  }

  // 筛选查询
  useEffect(() => {
    if (actionRef && props?.nodeInfo) {
      reloadList();
      setIsSettingOpen(false);
    }
  }, [actionRef, props.nodeInfo]);

  const columns: ProColumns<Record<string, any>>[] = [
    {
      title: <FormattedMessage id="device_group_list.table.list.name" defaultMessage="设备名称" />,
      dataIndex: 'name',
      hideInSearch: true,
      // width: 80,
      //   key: 'fixedName',
      //   fixed: 'left',
    },
    {
      title: (
        <FormattedMessage id="device_group_list.table.list.deviceType" defaultMessage="设备类型" />
      ),
      dataIndex: 'classification',
      hideInSearch: true,
      // width: 120,
    },
    // TODO 待定模型部署使用什么字段
    {
      title: (
        <FormattedMessage id="device_group_list.table.list.isEnable" defaultMessage="模型部署" />
      ),
      dataIndex: 'isEnable',
      hideInSearch: true,
      // width: 80,
      render: (dom, record) => {
        return (
          <div
            className={`gn_list_type_tag flex items-center justify-center ${
              record.isEnable ? 'active1' : 'active2'
            }`}
          >
            <span className="dot"></span>
            <span>
              {record.isEnable ? (
                <FormattedMessage
                  id="device_group_list.table.list.deployed.isEnable"
                  defaultMessage="已部署"
                />
              ) : (
                <FormattedMessage
                  id="device_group_list.table.list.undeployed.isEnable"
                  defaultMessage="未部署"
                />
              )}
            </span>
          </div>
        );
      },
    },

    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="操作" />,
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      key: 'option',
      render: (_, record) => [
        <TableActionCard
          key="TableActionCardRef"
          renderActions={[
            {
              key: 'setModel',
              renderDom: (
                <Button
                  key="setModel"
                  type="link"
                  size="small"
                  onClick={() => {
                    setCurrentRow({ ...record, device_id: record.id });
                    setIsSettingOpen(true);
                  }}
                >
                  <FormattedMessage
                    id="device_group_list.table.list.action.setModel"
                    defaultMessage="基础模型配置"
                  />
                </Button>
              ),
            },
            {
              key: 'updateDetail',
              renderDom: (
                <Button
                  key="update"
                  type="link"
                  size="small"
                  onClick={() => {
                    loadDetail(record);
                    setUpdateModalOpen(true);
                  }}
                >
                  <FormattedMessage id="pages.searchTable.update" defaultMessage="编辑" />
                </Button>
              ),
            },
            {
              key: 'destroy',
              renderDom: (
                <IsDelete
                  deleteApi={() => {
                    console.log('删除成功');
                    apiEntityNodesDeviceDelete({ device_id: record.id }).then(() => {
                      message.success(
                        intl.formatMessage({
                          id: 'common.action.success',
                          defaultMessage: '$$$',
                        }),
                      );
                      reloadList();
                    });
                  }}
                ></IsDelete>
              ),
            },
          ]}
        ></TableActionCard>,
      ],
    },
  ];

  /**设备分类 */
  return (
    <div className="dg_deviceList_wrap">
      <ProTable
        style={{
          display: isSettingOpen ? 'none' : 'block',
        }}
        className="gn_pro_table"
        cardProps={{
          bodyStyle: { padding: 0 },
        }}
        // 标题栏
        toolBarRender={() => [
          <Access
            accessible={access.canUpdate(history.location.pathname)}
            key={`${history.location.pathname}-add`}
          >
            <div className="mb-[16px] ">
              <Button
                className="mr-[12px]"
                type="primary"
                key="add"
                onClick={() => {
                  setCreateModalOpen(true);
                }}
              >
                <FormattedMessage
                  id="device_group_list.table.list.action.new"
                  defaultMessage="新建"
                />
              </Button>
              <Button
                key="deviceType"
                onClick={() => {
                  handleSetDeviceType();
                }}
              >
                <FormattedMessage
                  id="device_group_list.table.list.action.deviceType"
                  defaultMessage="设备分类"
                />
              </Button>
            </div>
          </Access>,
        ]}
        search={false}
        // scroll={{ y: proTableCommonOptions.commscrollY, x: proTableCommonOptions.commscrollX }}
        options={{ fullScreen: false, setting: false, density: false, reload: false }}
        actionRef={actionRef}
        rowKey="id"
        onDataSourceChange={(data) => {
          console.log(data, 'onDataSourceChange_data');
        }}
        pagination={{
          ...proTablePaginationOptions,
          pageSize: currentPageSize,
          onChange: (pageNo, pageSize) => setCurrentPageSize(pageSize),
        }}
        columnsState={{
          persistenceKey: 'algorithm_model_list',
          persistenceType: 'localStorage',
        }}
        request={async (params = {}) => {
          const { current, ...rest } = params;
          const reqParams = {
            pageNo: current,
            node_id: props.nodeInfo.id,
            ...rest,
          };
          if (!reqParams.node_id) {
            return { data: [], success: true };
          }
          let resp = await apiEntityNodesDeviceList({ ...reqParams });
          console.log(resp, 'apiEntityNodesDeviceList_resp');
          return {
            data: resp.data?.data,
            success: resp.success,
            total: resp.data.count,
            current: current,
            pageSize: currentPageSize,
          };
        }}
        columns={columns}
      />
      {isSettingOpen ? (
        <>
          <InnerPageBack
            backType="custom"
            toBack={() => {
              setIsSettingOpen(false);
            }}
            size={16}
            title="模型列表"
          ></InnerPageBack>
          <ModelSetting info={currentRow}></ModelSetting>
        </>
      ) : (
        <></>
      )}

      <CreateDeviceForm
        createModalOpen={createModalOpen}
        handleModal={handleCreateModal}
        commInfo={props.commInfo}
        nodeInfo={props.nodeInfo}
        reload={reloadList}
      />

      <UpdateDeviceForm
        updateModalOpen={updateModalOpen}
        handleModal={handleUpdateModal}
        values={currentRow}
        commInfo={props.commInfo}
        nodeInfo={props.nodeInfo}
        reload={reloadList}
      />
      <CategorizeUpdate
        visible={deviceTypeOpen}
        handleModal={handleSetDeviceType}
        values={{ deviceType: [{ name: '', value: '' }] }}
        apiRequest={async () => {
          let resp = await apiDeviceClassification();
          return {
            data: resp.data,
          };
        }}
        beforeCloseRequest={async (params, successRes) => {
          let resp = await apiDeviceClassificationDelete({ id: params.id });
          if (isSuccessApi(resp)) {
            successRes(resp);
          } else {
            message.error(resp.meta.message);
          }
        }}
        beforeAddRequest={async (params, successRes) => {
          let resp = await apiDeviceClassificationAdd({ name: params });
          if (isSuccessApi(resp)) {
            successRes(resp);
          } else {
            message.error(resp.meta.message);
          }
        }}
        modalFormProps={{
          categorizeFormProps: {
            label: (
              <FormattedMessage
                id="device_group_list.table.list.action.deviceType"
                defaultMessage="设备分类"
              />
            ),
            name: 'deviceType',
          },
          categorizeModelProps: {
            title: intl.formatMessage({
              id: 'device_group_list.table.list.action.setDeviceType',
              defaultMessage: '新建',
            }),
          },
        }}
      />
    </div>
  );
};

export default DeviceList;
