/*
 * @Author: donghao donghao@supervision.ltd
 * @Date: 2024-04-22 15:23:36
 * @LastEditors: donghao donghao@supervision.ltd
 * @LastEditTime: 2024-06-25 15:10:47
 * @FilePath: \general-ai-platform-web\src\pages\Node\BusinessModel\index.tsx
 * @Description: 业务模型
 * @交互说明
 * 1、业务模型列表的分页展示
 * 2、新增、更新、删除（模型）功能
 * 3. 模型详情展示
 */
import TableActionCard from '@/components/TableActionCard';
import IsDelete from '@/components/TableActionCard/isDelete';
import { useBusinessInfo } from '@/hooks/useBusinessInfo';
import {
  apiModelDeploymentDelete,
  apiModelDeploymentInfo,
  apiModelDeploymentList,
} from '@/services/business/model';
import { isSuccessApi } from '@/utils/forApi';

import { ExclamationCircleFilled } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProCard, ProTable } from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, message } from 'antd';
import { useRef, useState } from 'react';
import { proTablePaginationOptions } from '../../../../config/defaultTable';
import CreateForm from './components/createForm';
import UpdateForm from './components/updateForm';

import DetailCard from './components/detailCard';
const BusinessModel: React.FC = () => {
  const intl = useIntl();
  const { getStoreBusinessInfo } = useBusinessInfo();

  const actionRef = useRef<ActionType>();
  const [commInfo] = useState<Record<string, any>>({ ...getStoreBusinessInfo() }); // 通用信息

  const [createModalOpen, setCreateModalOpen] = useState<boolean>(false);
  const [updateModalOpen, setUpdateModalOpen] = useState<boolean>(false);

  const [detailModalOpen, setDetailModalOpen] = useState<boolean>(false); // 编辑窗口是否打开
  const [currentRow, setCurrentRow] = useState<Record<string, any>>({});

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

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

  // 设备节点信息
  async function loadDetail(record, isOpenDetail = false) {
    const resp = await apiModelDeploymentInfo({ id: record?.model_id });
    if (isSuccessApi(resp) && resp?.data) {
      setCurrentRow({ ...resp?.data, id: record?.model_id });
      if (isOpenDetail) {
        setUpdateModalOpen(true);
      }
    }
  }

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

  // 业务模型列表信息
  const columns: ProColumns<Record<string, any>>[] = [
    {
      title: <FormattedMessage id="business_model.table.list.name" defaultMessage="名称" />,
      dataIndex: 'model_name',
      hideInSearch: true,
      key: 'fixedName',
      fixed: 'left',
      width: '40%',
    },

    {
      title: (
        <FormattedMessage id="business_model.table.list.createTime" defaultMessage="创建时间" />
      ),
      dataIndex: 'create_time',
      hideInSearch: true,
      valueType: 'dateTime',
    },

    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      key: 'option',
      render: (_, record) => [
        <TableActionCard
          key="TableActionCardRef"
          renderActions={[
            {
              key: 'updateDetail',
              renderDom: (
                <Button
                  key="updateDetail"
                  type="link"
                  size="small"
                  onClick={() => {
                    loadDetail(record);
                    setDetailModalOpen(true);
                  }}
                >
                  <FormattedMessage id="pages.searchTable.updateDetail" defaultMessage="查看" />
                </Button>
              ),
            },
            {
              key: 'update',
              renderDom: (
                <Button
                  key="update"
                  type="link"
                  size="small"
                  onClick={() => {
                    loadDetail(record, true);
                  }}
                >
                  <FormattedMessage id="pages.searchTable.update" defaultMessage="查看" />
                </Button>
              ),
            },
            {
              key: 'destroy',
              renderDom: (
                <IsDelete
                  deleteApi={async () => {
                    console.log('删除成功');
                    const resp = apiModelDeploymentDelete({ id: record.id });
                    if (isSuccessApi(resp)) {
                      reloadList();
                      message.success(
                        intl.formatMessage({
                          id: 'common.action.success',
                          defaultMessage: '$$$',
                        }),
                      );
                    } else {
                      message.error(
                        resp?.meta?.message ||
                          intl.formatMessage({
                            id: 'common.action.failure',
                            defaultMessage: '$$$',
                          }),
                      );
                    }
                  }}
                ></IsDelete>
              ),
            },
          ]}
        ></TableActionCard>,
      ],
    },
  ];
  return (
    <div className="businessModel_page gn_head_card">
      <ProCard
        className="gn_card_wrap pb-[16px]"
        title={
          <span className="head3">
            <FormattedMessage id="business_model.table.title" defaultMessage="标题" />
          </span>
        }
        extra={
          <Button
            type="primary"
            onClick={() => {
              setCreateModalOpen(true);
            }}
          >
            <FormattedMessage id="business_model.table.list.action.add" defaultMessage="新增" />
          </Button>
        }
      >
        <div
          className="pb-[12px]"
          style={{
            color: '#FAAD14',
          }}
        >
          <ExclamationCircleFilled />
          <span className="pl-[8px]">业务模型需关联设备节点请先至“设备节点”页创建需关联的节点</span>
        </div>
        <ProTable
          className="gn_pro_table"
          cardProps={{
            bodyStyle: { padding: 0 },
          }}
          // 标题栏
          search={false}
          options={{ fullScreen: false, setting: false, density: false, reload: false }}
          actionRef={actionRef}
          rowKey="model_id"
          onDataSourceChange={(data) => {
            console.log(data, 'onDataSourceChange_data');
            // let CategoryFkIdIds: any = data.map((v) => {
            //   return v.categoryFkId;
            // });
            // setCategoryFkIdIds(CategoryFkIdIds);
          }}
          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,
              entity_id: commInfo.id,
              ...rest,
            };
            let resp = await apiModelDeploymentList({ ...reqParams });
            if (!isSuccessApi(resp)) {
              return { data: [], success: true };
            }
            console.log(resp, 'getModelVersionList_resp');
            return {
              data: resp.data?.data,
              success: resp.success,
              total: resp.data.count,
              current: current,
              pageSize: currentPageSize,
            };
          }}
          columns={columns}
        />
      </ProCard>
      <CreateForm
        createModalOpen={createModalOpen}
        handleModal={handleCreateModal}
        commInfo={commInfo}
        reload={reloadList}
      />
      <UpdateForm
        updateModalOpen={updateModalOpen}
        handleModal={handleUpdateModal}
        commInfo={commInfo}
        values={currentRow}
        reload={reloadList}
      />
      <DetailCard
        info={currentRow}
        detailModalOpen={detailModalOpen}
        handleModal={handleDetailModal}
      />
    </div>
  );
};

export default BusinessModel;
