/*
 * @Author: donghao donghao@supervision.ltd
 * @Date: 2024-04-08 10:36:06
 * @LastEditors: donghao donghao@supervision.ltd
 * @LastEditTime: 2024-06-06 15:13:25
 * @FilePath: \general-ai-manage\src\pages\Model\ModelRuntimeLib\index.tsx
 * @Description: 模型运行库
 * @交互说明
 * 1. 运行库列表分页展示、关键词检索
 * 2. 新增、编辑、删除（模型运行库）功能
 *
 */

import { apiModelHubDelete, apiModelHubInfo, apiModelHubList } from '@/services/business/model';
import { isSuccessApi } from '@/utils/forApi';

import { CommButton } from '@/components/Button';
import TableActionCard from '@/components/TableActionCard';
import IsDelete from '@/components/TableActionCard/isDelete';
import { SearchOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProCard, ProForm, ProFormText, 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 { proTableCommonOptions, proTablePaginationOptions } from '../../../../config/defaultTable';
import CreateForm from './components/createForm';
import UpdateForm from './components/updateForm';

import { ReactComponent as ResetIcon } from '/public/home/reset_icon.svg';
import { ReactComponent as SearchIcon } from '/public/home/search_icon.svg';

const ModelRuntimeLib: React.FC = () => {
  const access = useAccess();
  const intl = useIntl();
  const actionRef = useRef<ActionType>();
  const [querysData, setQuerysData] = useState<Record<string, any>>({}); // 列表查询参数

  const [createModalOpen, setCreateModalOpen] = useState<boolean>(false);
  // const [categoryFkIdIds, setCategoryFkIdIds] = useState([]);
  //  动态设置每页数量
  const [currentPageSize, setCurrentPageSize] = useState<number>(10);
  const [currentRow, setCurrentRow] = useState<Record<string, any>>({});
  const [form] = ProForm.useForm(); // form 对象

  const [updateModalOpen, setUpdateModalOpen] = useState<boolean>(false);
  // const [showDetail, setShowDetail] = useState<boolean>(false);

  /**新增 编辑 删除 */
  // 新增
  const handleCreateModal = () => {
    setCreateModalOpen(!createModalOpen);
  };
  // 编辑
  const handleUpdateModal = () => {
    setUpdateModalOpen(!updateModalOpen);
  };
  // 设备节点信息
  async function loadDetail(record) {
    const resp = await apiModelHubInfo({ id: record?.id });
    if (isSuccessApi(resp) && resp?.data) {
      setCurrentRow({ ...resp?.data, id: record?.id });
    }
  }
  function reloadList() {
    actionRef.current?.reload();
  }
  // 筛选查询
  useEffect(() => {
    if (actionRef) {
      reloadList();
    }
  }, [actionRef, querysData]);
  const columns: ProColumns<Record<string, any>>[] = [
    {
      title: <FormattedMessage id="model_runtimeLib.table.list.name" defaultMessage="$$$" />,
      dataIndex: 'name',
      hideInSearch: true,
      key: 'fixedName',
      fixed: 'left',
    },
    {
      title: <FormattedMessage id="model_runtimeLib.table.list.path" defaultMessage="创建时间" />,
      dataIndex: 'path',
      hideInSearch: true,
    },

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

    {
      title: (
        <FormattedMessage id="model_runtimeLib.table.list.updateTime" defaultMessage="更新时间" />
      ),
      dataIndex: 'update_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: 'update',
              renderDom: (
                <Button
                  key="update"
                  type="link"
                  size="small"
                  onClick={() => {
                    loadDetail(record);
                    setUpdateModalOpen(true);
                  }}
                >
                  <FormattedMessage id="pages.searchTable.update" defaultMessage="Update" />
                </Button>
              ),
            },
            {
              key: 'destroy',
              renderDom: (
                <IsDelete
                  deleteApi={() => {
                    console.log('删除成功');
                    apiModelHubDelete({ id: record.id }).then(() => {
                      message.success(
                        intl.formatMessage({
                          id: 'common.action.success',
                          defaultMessage: '$$$',
                        }),
                      );
                      reloadList();
                    });
                  }}
                ></IsDelete>
              ),
            },
          ]}
        ></TableActionCard>,
      ],
    },
  ];
  return (
    <div className="modelRuntimeLib_page home_container gn_table_card_wrap">
      <ProCard
        className="gn_card"
        style={{ backgroundColor: 'white' }}
        bodyStyle={{
          maxHeight: 'calc(100vh - 250px)',
          overflowY: 'scroll',
        }}
        title={
          <div className="gn_form gn_table_query_filter">
            <ProForm
              className="gn_search_from"
              form={form}
              layout="horizontal"
              submitter={{
                render: () => (
                  <div style={{ textAlign: 'center', marginLeft: 12 }}>
                    <CommButton
                      type="primary"
                      htmlType="submit"
                      prevIcon={<SearchIcon />}
                      buttonLabel={
                        <FormattedMessage id="pages.searchTable.search" defaultMessage="查询" />
                      }
                    ></CommButton>
                    <CommButton
                      style={{ marginLeft: 12 }}
                      htmlType="button"
                      prevIcon={<ResetIcon />}
                      buttonLabel={
                        <FormattedMessage id="pages.searchTable.reset" defaultMessage="重置" />
                      }
                      onClick={() => {
                        form.resetFields(); // 点击重置按钮时重置表单数据
                        setQuerysData(() => {}); // 清空筛选项
                      }}
                    ></CommButton>
                  </div>
                ),
              }}
              onFinish={async (values) => {
                console.log(values, 'filter_finish_values');
                setQuerysData(() => values);

                return true;
              }}
            >
              <ProFormText
                label={
                  <FormattedMessage
                    id="model_runtimeLib.table.list.name"
                    defaultMessage="运行库名称"
                  />
                }
                labelClassName="label_set_1"
                fieldProps={{
                  style: {
                    width: 280,
                  },
                  prefix: <SearchOutlined style={{ color: 'rgba(0,0,0,.25)' }} />,
                }}
                name="name"
                placeholder="请输入运行库名称"
              />
            </ProForm>
          </div>
        }
        extra={
          <Access
            accessible={access.canUpdate(history.location.pathname)}
            key={`${history.location.pathname}-add`}
          >
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                setCreateModalOpen(true);
              }}
            >
              <FormattedMessage
                id="model_runtimeLib.list.table.form.action.add"
                defaultMessage="新建"
              />
            </Button>
          </Access>
        }
      >
        {/* // TODO 需要控制表格溢出滚动高度 */}
        <ProTable
          className="gn_pro_table"
          cardProps={{
            bodyStyle: {
              padding: '0',
            },
          }}
          search={false}
          scroll={{ x: proTableCommonOptions.commscrollX }}
          options={{ fullScreen: false, setting: false, density: false, reload: false }}
          actionRef={actionRef}
          rowKey="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,

              ...rest,
            };
            let resp = await apiModelHubList({ ...reqParams, ...querysData });
            if (!isSuccessApi(resp)) {
              return { data: [], success: true };
            }
            console.log(resp, 'apiEntityNodesDeviceList_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}
        reload={reloadList}
      />
      <UpdateForm
        updateModalOpen={updateModalOpen}
        handleModal={handleUpdateModal}
        values={currentRow}
        reload={reloadList}
      />
    </div>
  );
};

export default ModelRuntimeLib;
