import { postAlgorithmModelGetAlgorithmModelById } from '@/services/resource/AlgorithmModel';
import { deleteModelVersionDeleteModelVersion, postModelVersionGetModelVersionList } from '@/services/resource/ModelVersion';
import { ArrowLeftOutlined, PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProCard,
  ProColumns,
  ProDescriptions,
  ProTable,
} from '@ant-design/pro-components';
import { Access, FormattedMessage, history, useAccess, useParams, useIntl } from '@umijs/max';

import { Button, message } from 'antd';
import React, { useRef, useState } from 'react';
import MyCreateForm from '../ModelVersionList/components/MyCreateForm';
import TableActionCard from '@/components/TableActionCard';
import IsDelete from '@/components/TableActionCard/isDelete';
import UpdateForm from '../ModelVersionList/components/UpdateForm';

/**styles */

const detailStylesProps = {
  marginBottom: 15,
  textColor: '#333333',
};
const headerStylesProps = {
  fontSize: 16,
  fontWeight: 700,
  color: '#333333',
};



const AlgorithmModelDetail: React.FC = () => {
  const access = useAccess();
  const intl = useIntl();

  const actionRef = useRef<ActionType>();

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

  const [currentRow, setCurrentRow] = useState<API.ModelVersion>();
  const [selectedRowsState, setSelectedRows] = useState<API.ModelVersion[]>([]);
  const [model_fk_id_open, set_model_fk_id_open] = useState(false);
  const [model_fk_id, set_model_fk_id] = useState<API.AlgorithmModel>();
  const [model_fk_id_column_open, set_model_fk_id_column_open] = useState(false);
  const [modelFkIdIds, setModelFkIdIds] = useState([]);
  const [modelFkIdMap, setModelFkIdMap] = useState<{ [key: number]: string }>({});

  const handleDestroy = async (selectedRow: API.ModelVersion) => {
    deleteModelVersionDeleteModelVersion({ 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 columns: ProColumns<API.ModelVersion>[] = [
    {
      title: <FormattedMessage id="resource.model_version.table.list.id" defaultMessage="id" />,
      dataIndex: 'id',
      sorter: true,
    },
  
    {
      title: (
        <FormattedMessage id="resource.model_version.table.list.modelFkId" defaultMessage="$$$" />
      ),
      dataIndex: 'modelFkId',
      hideInSearch: false,
    },
  
    {
      title: <FormattedMessage id="resource.model_version.table.list.version" defaultMessage="$$$" />,
      dataIndex: 'version',
      hideInSearch: true,
    },
  
    {
      title: <FormattedMessage id="resource.model_version.table.list.path" defaultMessage="$$$" />,
      dataIndex: 'path',
      hideInSearch: true,
    },
  
    {
      title: (
        <FormattedMessage id="resource.model_version.table.list.startCode" defaultMessage="$$$" />
      ),
      dataIndex: 'startCode',
      hideInSearch: true,
    },
  
    {
      title: (
        <FormattedMessage id="resource.model_version.table.list.isEnable" defaultMessage="$$$" />
      ),
      dataIndex: 'isEnable',
      filters: true,
      onFilter: true,
      hideInSearch: true,
      valueType: 'switch',
    },
  
    {
      title: <FormattedMessage id="resource.model_version.table.list.remark" defaultMessage="$$$" />,
      dataIndex: 'remark',
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="resource.model_version.table.list.status" defaultMessage="$$$" />,
      dataIndex: 'status',
      hideInSearch: true,
      valueEnum: {
        1: { text: '已创建', status: 'Default' },
        2: { text: '已发布', status: 'Processing' },
        3: { text: '已上架', status: 'Success' },
        4: { text: '已下架', status: 'Default' },
        5: { text: '已关闭', status: 'Error' },
      },
    },
  
    {
      title: (
        <FormattedMessage id="resource.model_version.table.list.createTime" defaultMessage="$$$" />
      ),
      dataIndex: 'createTime',
      sorter: true,
      hideInSearch: true,
      valueType: 'dateTime',
    },
  
    {
      title: (
        <FormattedMessage id="resource.model_version.table.list.updateTime" defaultMessage="$$$" />
      ),
      dataIndex: 'updateTime',
      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"
                  onClick={() => {
                    setUpdateModalOpen(true);
                    setCurrentRow(record);
                  }}
                >
                  <FormattedMessage id="pages.searchTable.update" defaultMessage="Update" />
                </Button>
              ),
            },
            {
              key: 'destroy',
              renderDom: (
                <IsDelete
                  deleteApi={() => {
                    handleDestroy(record).then(() => {});
                  }}
                ></IsDelete>
              ),
            },
          ]}
        ></TableActionCard>,
      ],
    },
  ];
  //  TODO 需要将业务层代码转移到此处
  // TODO 按UI原稿重新布局此模块
  // 关闭页面
  const doClose = () => {
    history.back();
  };

  const handleCreateModal = () => {
    if (createModalOpen) {
      setCreateModalOpen(false);
      setCurrentRow(undefined);
    } else {
      setCreateModalOpen(true);
    }
  };

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



  const routeParams = useParams();
  return (
    <PageContainer>
      <ProCard split="horizontal" style={{ background: 'transparent' }}>
        <ProCard
          wrap
          bodyStyle={{ margin: 0, padding: 0 }}
          style={{ margin: 0, padding: 0, background: 'transparent' }}
        >
          <ProCard
            title={
              <div onClick={doClose} style={{ display: 'flex', alignItems: 'center' }}>
                <ArrowLeftOutlined style={{ marginRight: 10 }} />
                <span style={{ fontSize: 20, color: '#333333', fontWeight: 700 }}>模型详情</span>
              </div>
            }
            style={{
              margin: 0,
              padding: 0,
              marginBottom: detailStylesProps.marginBottom,
              background: 'transparent',
            }}
            headStyle={{ margin: 0, padding: 0 }}
            bodyStyle={{ margin: 0, padding: 0 }}
          ></ProCard>
          <ProCard
            style={{ margin: 0, padding: 0, marginBottom: detailStylesProps.marginBottom }}
            bodyStyle={{ margin: 0, padding: 20 }}
          >
            <ProDescriptions
              column={4}
              title="模型详细信息"
              tooltip="包含了模型详细信息"
              columns={columns}
              request={async () => {
                console.log(routeParams, 'id');
                const resp = await postAlgorithmModelGetAlgorithmModelById({
                  id: Number(routeParams.id),
                });
                // postModelVersionGetModelVersionList({modelFkId: 3})
                console.log('resp', resp);
                return {
                  data: resp.data?.algorithmModel,
                  success: resp.success,
                };
              }}
            ></ProDescriptions>
          </ProCard>
        </ProCard>
        <ProCard
          title="模型版本"
          extra={<><Access
            accessible={access.canUpdate(history.location.pathname)}
            key={`${history.location.pathname}-add`}
          >
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                setCreateModalOpen(true);
              }}
            >
              <PlusOutlined />{' '}
              <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
            </Button>
          </Access></>}
          style={{ margin: 0, padding: 0 }}
          headStyle={{ paddingTop: 20, paddingBottom: 20, ...headerStylesProps }}
          bodyStyle={{ margin: 0, padding: 0 }}
        >
          <ProTable
            actionRef={actionRef}
            tableStyle={{ paddingTop: 15, paddingBottom: 15 }}
            columns={columns}
            cardBordered
            toolBarRender={() => [
              
            ]}
            request={async (params = {}, sort) => {
              const { current, ...rest } = params;
              const reqParams = {
                page: current,
                desc: false,
                orderKey: '',
                modelFkId: Number(routeParams?.id),
                ...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 postModelVersionGetModelVersionList({ ...reqParams });
              return {
                data: resp.data.list.map((v: API.ModelVersion) => {
                  return { ...v, key: v.id };
                }),
                success: resp.success,
                total: resp.data.total,
                current: resp.data.page,
                pageSize: resp.data.pageSize,
              };
            }}
            editable={{
              type: 'multiple',
            }}
            columnsState={{
              persistenceKey: 'pro-table-singe-demos',
              persistenceType: 'localStorage',
              onChange(value) {
                console.log('value: ', value);
              },
            }}
            rowKey="id"
            search={false}
            options={{
              fullScreen: false,
              setting: false,
              density: false,
              reload: false,
            }}
            form={{
              // 由于配置了 transform,提交的参与与定义的不同这里需要转化一下
              syncToUrl: (values, type) => {
                if (type === 'get') {
                  return {
                    ...values,
                    created_at: [values.startTime, values.endTime],
                  };
                }
                return values;
              },
            }}
            pagination={{
              pageSize: 5,
              onChange: (page) => console.log(page),
            }}
            dateFormatter="string"
          />
        </ProCard>
      </ProCard>
      <MyCreateForm
        createModalOpen={createModalOpen}
        values={{modelFkId: Number(routeParams?.id)}}
        handleModal={handleCreateModal}
        reload={actionRef.current?.reload}
        currentDefaultFieldsData={{modelFkId: Number(routeParams?.id)}}
      />
       <UpdateForm
        updateModalOpen={updateModalOpen}
        values={currentRow || {}}
        handleModal={handleUpdateModal}
        reload={actionRef.current?.reload}
        currentDefaultFieldsData={{modelFkId: Number(routeParams?.id)}}
      />
    </PageContainer>
  );
};
export default AlgorithmModelDetail;