/*
 * @Author: donghao donghao@supervision.ltd
 * @Date: 2024-04-08 16:57:30
 * @LastEditors: donghao donghao@supervision.ltd
 * @LastEditTime: 2024-07-23 09:29:54
 * @FilePath: \general-ai-manage\src\pages\Project\BusinessProject\components\detailServerState.tsx
 * @Description: 服务器详情
 * @交互说明
 *
 */
import {
  apiEntityNodesBusimodelDeploy,
  apiEntityNodesDeviceListSimple,
} from '@/services/business/entity';
import { isSuccessApi } from '@/utils/forApi';
import { mathConvertCommaSeparatedStringToArray, mathExtractIds } from '@/utils/forMath';
import { isArrayAndNotEmpty } from '@/utils/is';
import { ProCard, ProColumns, ProDescriptions, ProTable } from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Modal, message } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { proFormSmallModelWidth } from '../../../../../config/defaultForm';
import { proTableDefaultOptions } from '../../../../../config/defaultTable';

type ModelDeployConfigProps = {
  info: Record<string, any>;
  nodeInfo: Record<string, any>;
  detailOpen: boolean;
  handleModal: () => void;
  reload: () => void;
};

const ModelDeployConfig: React.FC<ModelDeployConfigProps> = ({
  info,
  nodeInfo,
  detailOpen,
  reload,
  handleModal,
}) => {
  /**state */
  const intl = useIntl();
  const [selectedRows, setSelectedRows] = useState<Record<string, any>[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const actionRef = useRef();
  // 基础配置信息
  const detailColumns = [
    {
      title: (
        <FormattedMessage
          id="business_model.deploy.config.bussnessName"
          defaultMessage="业务名称"
        />
      ),
      dataIndex: 'busi_model_name',
    },
    {
      title: <FormattedMessage id="business_model.deploy.config.remark" defaultMessage="简介" />,
      dataIndex: 'busi_model_comment',
    },
    {
      title: (
        <FormattedMessage
          id="business_model.deploy.config.linkModels"
          defaultMessage="关联基础模型"
        />
      ),
      dataIndex: 'linkModels',
      render: (_, record) => {
        return (
          <ul className="flex flex-wrap">
            {mathConvertCommaSeparatedStringToArray(record?.base_models)?.map((item, index) => {
              return (
                <li
                  className={`text_primary primary_border rounded-[2px] px-[8px] mb-[8px] ${
                    index !== 0 ? 'ml-[8px]' : ''
                  }`}
                  key={index + item}
                >
                  {item}
                </li>
              );
            })}
          </ul>
        );
      },
    },
  ];

  // 模型列表信息
  const columns: ProColumns<Record<string, any>>[] = [
    {
      title: (
        <FormattedMessage id="business_model.deploy.config.table.name" defaultMessage="设备名称" />
      ),
      dataIndex: 'name',
      hideInSearch: true,
      key: 'fixedName',
      fixed: 'left',
      width: '55%',
    },
    {
      title: (
        <FormattedMessage
          id="business_model.deploy.config.table.deviceType"
          defaultMessage="设备类型"
        />
      ),
      dataIndex: 'classification_name',
      hideInSearch: true,
    },
  ];

  // 基础模型列表数据api
  function loadData() {
    console.log(info?.devices, 'loadData_devices');
    if (isArrayAndNotEmpty(info?.devices)) {
      const selectArr = [];
      info?.devices.forEach((item) => {
        selectArr.push(item.device_id);
      });
      setSelectedRowKeys(selectArr);
    }
  }

  useEffect(() => {
    // eslint-disable-next-line @typescript-eslint/no-unused-expressions
    info?.busi_model_id && loadData();
  }, [info]);

  // 初始化加载
  useEffect(() => {
    console.log('modelDeployConfig_detailOpen', detailOpen);
    if (!detailOpen) {
      actionRef?.current?.clearSelected();
      setSelectedRows([]);
      setSelectedRowKeys([]);
    }
  }, [detailOpen]);

  return (
    <Modal
      width={proFormSmallModelWidth}
      title={`${intl.formatMessage({
        id: 'business_model.table.list.action.config',
        defaultMessage: '配置参数',
      })}`}
      open={detailOpen}
      onCancel={() => {
        handleModal();
      }}
      onOk={async () => {
        console.log(info, 'onOk_selectedRows', selectedRows);
        let resp = await apiEntityNodesBusimodelDeploy({
          node_id: nodeInfo?.node_id,
          busi_model_id: info?.busi_model_id,
          device_ids: mathExtractIds(selectedRows)?.join(','),
        });
        if (isSuccessApi(resp)) {
          message.success(
            intl.formatMessage({ id: 'common.action.success', defaultMessage: '$$$' }),
          );
          reload();
          handleModal();
        } else {
          message.error(
            resp?.meta?.message ||
              intl.formatMessage({ id: 'common.action.failure', defaultMessage: '$$$' }),
          );
        }
      }}
      okText={<FormattedMessage id="pages.modelForm.okText" defaultMessage="确认" />}
      cancelText={<FormattedMessage id="pages.modelForm.cancelText" defaultMessage="取消" />}
    >
      <ProCard className="gn_card_wrap" bodyStyle={{ padding: 0 }}>
        <div className="my-[8px] gn_active_descriptions gn_descriptions bg_active_4">
          <ProDescriptions column={1} columns={detailColumns} dataSource={info}></ProDescriptions>
        </div>
        <div className="head4 py-[8px]">
          <FormattedMessage
            id="business_model.deploy.config.table.title.name"
            defaultMessage="请选择"
          />
        </div>
        <ProTable
          {...proTableDefaultOptions}
          style={{
            height: '300px',
            overflowY: 'scroll',
          }}
          className="gn_pro_table"
          cardProps={{
            bodyStyle: { padding: 0 },
          }}
          actionRef={actionRef}
          // 标题栏
          search={false}
          options={{ fullScreen: false, setting: false, density: false, reload: false }}
          rowKey="id"
          pagination={false}
          rowSelection={{
            selectedRowKeys,
            onChange: (_, selectedRowsData) => {
              setSelectedRows(selectedRowsData);
            },
          }}
          tableAlertRender={false}
          request={async () => {
            let resp = await apiEntityNodesDeviceListSimple({ node_id: nodeInfo?.node_id });
            console.log(resp, 'getAllDeviceList_resp');
            return {
              data: resp.data?.data,
              success: resp.success,
            };
          }}
          columns={columns}
        />
      </ProCard>
    </Modal>
  );
};

export default ModelDeployConfig;
