import React, {useEffect, useRef, useState} from "react";
import {Button, Drawer, message, Popconfirm} from "antd";
import {
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProCard,
  ProTable,
  TableDropdown,
  ProFormSelect, ActionType
} from "@ant-design/pro-components";
import ModelVersionList from "@/pages/Resource/ModelVersionList";
import {Access, FormattedMessage, history, useAccess} from "@@/exports";
import {
  postAlgorithmModelGetAlgorithmModelFkSelect,
  putAlgorithmModelUpdateAlgorithmModel
} from "@/services/resource/AlgorithmModel";
import {postModelVersionGetModelVersionList} from "@/services/resource/ModelVersion";
import {PlusOutlined} from "@ant-design/icons";
import MyCreateForm from "@/pages/Resource/ModelVersionList/components/MyCreateForm";

export type ColumnDrawProps = {
  handleDrawer: (id?: any)=>void;
  isShowDetail: boolean;
  columns: any;
  currentRow: API.AlgorithmModel | undefined;
};

type GithubIssueItem = {
  url: string;
  id: number;
  number: number;
  title: string;
  labels: {
    name: string;
    color: string;
  }[];
  state: string;
  comments: number;
  created_at: string;
  updated_at: string;
  closed_at?: string;
};

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) => [
    //   <Access accessible={access.canUpdate(history.location.pathname)} key={`${history.location.pathname}-add`}>
    //     <a
    //       key="update"
    //       onClick={() => {
    //         setUpdateModalOpen(true);
    //         setCurrentRow(record);
    //       }}
    //     >
    //       <FormattedMessage id="pages.searchTable.update" defaultMessage="Update" />
    //     </a>
    //     <a
    //       key="destroy"
    //       onClick={() => {
    //         handleDestroy(record).then(()=>{})
    //       }}>
    //       <FormattedMessage
    //         id="pages.searchTable.destroy"
    //         defaultMessage="Destroy"
    //       />
    //     </a>
    //     <Popconfirm
    //       title="发布模型"
    //       description="确认发布模型吗?"
    //       onConfirm={()=>{}}
    //       onCancel={()=>{}}
    //       okText="Yes"
    //       cancelText="No"
    //     >
    //       <a
    //         key="confirm_publish"
    //         onClick={() => {
    //           setPublishModalOpen(true);
    //           setCurrentRow(record);
    //         }}>
    //         <FormattedMessage
    //           id="common.confirm_publish"
    //           defaultMessage="confirm_publish"
    //         />
    //       </a>
    //     </Popconfirm>
    //     <Popconfirm
    //       title="设置为默认版本"
    //       description="确认设置为默认版本吗?"
    //       onConfirm={()=>{
    //         putAlgorithmModelUpdateAlgorithmModel({id: record.modelFkId, defaultVersionFkId: record.id}).then(()=>{
    //           message.success(intl.formatMessage({id: 'common.success', defaultMessage: '$$$'}))
    //         }).catch(()=>{
    //           message.error(intl.formatMessage({id: 'common.failure', defaultMessage: '$$$'}))
    //         })
    //       }}
    //       onCancel={()=>{}}
    //       okText="Yes"
    //       cancelText="No"
    //     >
    //       <a
    //         key="set_default"
    //         onClick={() => {
    //
    //         }}>
    //         <FormattedMessage
    //           id="common.set_default"
    //           defaultMessage="$$$"
    //         />
    //       </a>
    //     </Popconfirm>
    //   </Access>
    // ],
  },];
const ModelVersionListDrawer: React.FC<ColumnDrawProps> = (props) => {
  const access = useAccess();
  const actionRef = useRef<ActionType>();
  const [createModalOpen, setCreateModalOpen] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.ModelVersion>();

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

  useEffect(() => {
    if (props.isShowDetail) {
      actionRef.current?.reload();
    }
  }, [props.isShowDetail]);

  return (
    <Drawer
      width={"80%"}
      open={props.isShowDetail}
      onClose={() => {
        props.handleDrawer();
      }}
      closable={true}
    >
      <ProCard split="horizontal">
          <ProCard>
            <ProDescriptions
              column={2}
              dataSource={props.currentRow}
              title="模型详细信息"
              tooltip="包含了模型详细信息"
              columns={props.columns}

            >
            </ProDescriptions>
          </ProCard>
        <ProCard>
          <ProTable
            columns={columns}
            cardBordered
            actionRef={actionRef}
            request={async (params = {}, sort) => {
              const {current, ...rest} = params
              const reqParams = {
                page: current,
                desc: false,
                orderKey: "",
                modelFkId: props.currentRow?.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={{
              setting: {
                listsHeight: 400,
              },
            }}
            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"
            headerTitle="模型版本列表"
            toolBarRender={() => [
              <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>
            ]}
          />
          <MyCreateForm
            createModalOpen={createModalOpen}
            values={currentRow || {}}
            handleModal={handleCreateModal}
            reload={actionRef.current?.reload}
          />
        </ProCard>
      </ProCard>
    </Drawer>
  )
}
export {ModelVersionListDrawer}

