// 选择作品弹窗
import React, { useRef, useState, useEffect } from 'react';
import { Image } from 'antd';
import Table, { ProColumns, ActionType } from '@/components/Table';
import Modal, { ModalProps } from '@/components/Modal';
import { queryWorkList } from '@/services/work';
import { fetchTableData } from '@/utils/table';

interface WorkSelectModalPropsType extends ModalProps {
  value: any[];
  onOk: (val: any) => void;
  type?: 'checkbox' | 'radio';
}
const WorkSelectModal = ({
  value = [],
  onOk,
  type = 'checkbox',
  ...rest
}: WorkSelectModalPropsType) => {
  const [selectedRows, setSelectedRows] = useState<any[]>([]);
  const actionRef = useRef<ActionType>();
  const columns: ProColumns<any>[] = [
    {
      title: 'ID',
      dataIndex: 'work_id',
      width: '10%',
      hideInSearch: true,
    },
    {
      title: '封面',
      dataIndex: 'url',
      valueType: 'image',
      hideInSearch: true,
      width: '30%',
      render: (_, row) => {
        return <Image src={row.cover_resource?.url} height={100} alt="" />;
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '等级',
      dataIndex: 'rarity_name',
      width: '10%',
      hideInSearch: true,
    },
  ];
  const handleOk = () => {
    onOk && onOk(selectedRows);
  };
  const handleMerge = (keys, selectedInfos) => {
    const newInfo: any = [];
    const valueMap = {};
    const selectedInfosMap = {};
    value.forEach((item) => (valueMap[item.work_id] = item));
    selectedInfos.filter((item) => item).forEach((item) => (selectedInfosMap[item.work_id] = item));
    keys.forEach((item) => {
      newInfo.push(selectedInfosMap[item] || valueMap[item]);
    });
    setSelectedRows(newInfo);
  };
  useEffect(() => {
    setSelectedRows(value);
  }, [value]);
  return (
    <Modal title="选择作品" onOk={handleOk} width={800} {...rest}>
      <Table
        columns={columns}
        actionRef={actionRef}
        rowKey="work_id"
        rowSelection={{
          type,
          selectedRowKeys: selectedRows?.map((item) => item.work_id) || [],
          onChange: (keys, info) => {
            handleMerge(keys, info);
          },
        }}
        request={async (params) => {
          const res = await fetchTableData(queryWorkList, params);
          res.data?.forEach((item) => {
            item.work_id = item.id;
            delete item.id;
          });
          return res;
        }}
      />
    </Modal>
  );
};

export default WorkSelectModal;
