import React, { useState, useEffect } from 'react';
import { Button, Modal, Table, TablePaginationConfig, TableColumnsType, Typography, message, Tabs, Input } from 'antd';
import type { TableProps } from 'antd';
import { apis } from '@/apis';
import { Record } from '../types';
import dayjs from 'dayjs';
import useAppState from '@/store';

import PrevewSlice from './prevewSlice';

interface QuoteModalProps {
  open: boolean;
  knowledgeDetail: any;
  onCancel: () => void;
}

const QuoteModal: React.FC<QuoteModalProps> = ({ open, knowledgeDetail, onCancel }) => {
  const [list, setList] = useState<Record[]>([]); // 示例数据
  const [page, setPage] = useState<{ page: number; size: number; total: number }>({
    page: 1,
    size: 10,
    total: 0,
  });
  const [titleName, setTitleName] = useState<string>('');
  const [appStateList, setAppStateList] = useState<any[]>([]);
  const [activeTabKey, setActiveTabKey] = useState<string>('');
  const [searchKeyword, setSearchKeyword] = useState<string>('');
  const { getAppState } = useAppState();
  const [openDrawer, setOpenDrawer] = useState<boolean>(false);
  const [selectedRecord, setSelectedRecord] = useState<any>(null);
  const columns: TableColumnsType<Record> = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 80,
      render: (text, record, index) => {
        return index + 1;
      }
    },
    {
      title: '文件名',
      dataIndex: 'name',
      width: 300,
      sorter: (a, b) => a.name.localeCompare(b.name),
      render: (text, record) => {
        return (
          `${text}`
        )
      }
    },
    {
      title: '所在知识库',
      dataIndex: 'knowledgeName',
      width: 300,
      render: (text, record) => {
        return (
          `${text}`
        )
      }
    },
    {
      title: '创建人',
      dataIndex: 'nickName',
      width: 300,
      render: (text, record) => {
        return (
          `${text}`
        )
      }
    },
    {
      title: '文件大小',
      dataIndex: 'length',
      width: 100,
      render: (text) => {
        if (text) {
          const size = (text / 1024 / 1024).toFixed(2);
          return `${size} M`;
        } else {
          return '--'
        }
      }
    },
    {
      title: '字符数量',
      dataIndex: 'wordNum',
      width: 100,
      render: (text) => {
        if (text) {
          return `${text}`;
        } else {
          return '--'
        }
      }
    },
    {
      title: '切片数量',
      dataIndex: 'sliceTotal',
      width: 100,
      render: (text) => {
        if (text) {
          return `${text}`;
        } else {
          return '--';
        }
      }
    },
    {
      title: '上传时间',
      dataIndex: 'createTime',
      width: 180,
      render: (text) => {
        if (text) {
          return dayjs(text).format('YYYY-MM-DD HH:mm:ss');
        } else {
          return '--';
        }
      }
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      width: 180,
      render: (text) => {
        if (text) {
          return dayjs(text).format('YYYY-MM-DD HH:mm:ss');
        } else {
          return '--';
        }
      }
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 180,
      fixed: 'right',
      render: (text, record: any) => {
        return (
          <>
            <a
              style={{ marginRight: 16 }}
              onClick={() => {
                setOpenDrawer(true);
                setSelectedRecord(record);
              }}
            >
              查看切片
            </a>
          </>
        )
      }
    }
  ];
  const [allLoding, setAllLoding] = useState<boolean>(false);
  const handleOk = async () => {
    if (documentids.length === 0) {
      Modal.warning({
        title: '提示',
        content: '请选择要引用的文档',
      });
      return;
    }
    setAllLoding(true);
    try {
      const falgDocumentids = documentids.map((item: any) => {
        return item
      })
      // 先调用效验接口
      const checkRes: any = await apis.checkQuoteFileApi({
        documentIds: falgDocumentids,
        knowledgeId: knowledgeDetail.knowledgeId,
      })
      const checkResData = checkRes.data || [];
      if (!checkResData?.length) {
        await onImportDocumentList(falgDocumentids);
      } else {
        setAllLoding(false);
        Modal.confirm({
          title: '提示',
          content: checkResData.map((item: any) => {
            return <div key={item.ossId}>文件“{item.newName}”已存在，知识库中已存在的文件名是“{item.oldName}”</div>
          }),
          onOk: async () => {
            setAllLoding(true);
            // 过滤掉已存在的文件（根据 ossId）
            const filtered = falgDocumentids.filter((f: any) => !checkResData.some((d: any) => d.documentId === f));

            if (!filtered || filtered.length === 0) {
              // 所有文件都已存在，提示并结束
              message.warning('选中文件均已存在，请重新选择。');
              setAllLoding(false);
              return;
            }

            // 构建参数并继续上传剩余文件
            // const nextParams = {
            //   ...values,
            //   parsingType: values.parsingType,
            //   standardClassification,
            //   fileList: filtered.map((item: any) => ({
            //     ...item,
            //     suffix: (item.fileName || item.name || '').split('.').pop(),
            //   })),
            // };
            await onImportDocumentList(filtered);
          },
          onCancel: () => {
            setAllLoding(false);
          }
        });
      }
      return
    } catch (error) {
      setAllLoding(false);
    }
    onCancel();
  };

  const onImportDocumentList = async (documentids:any) => {
    const res: any = await apis.importDocumentList({
      documentIds: documentids,
      knowledgeId: knowledgeDetail.knowledgeId,
    });
    if (res?.code === 200) {
      message.success('引用成功');
    }
    setAllLoding(false);
  }


  const paginationConfig: TablePaginationConfig = {
    // 显示数据总量
    showTotal: (total: number) => {
      return `共 ${total} 条`;
    },
    // 展示分页条数切换
    showSizeChanger: true,
    // 指定每页显示条数
    pageSizeOptions: ['10', '20', '50', '100'],
    // 快速跳转至某页
    showQuickJumper: true,
    current: page.page,
    pageSize: page.size,
    total: page.total,
    onChange: async (page, pageSize) => {
      setPage((prevState) => ({
        ...prevState,
        page: page,
        size: pageSize,
      }));
      onGetQuoteDocumentList(page, pageSize);
    },
  };
  const [listLoading, setListLoading] = useState<boolean>(false);
  const [documentids, setdocumentids] = React.useState<string[]>([]); // 选择的文档ID数组
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  // 示例数据和列定义
  const rowSelection: TableProps<Record>['rowSelection'] = {
    selectedRowKeys,
    onChange: (selectedRowKeys: React.Key[], selectedRows: Record[]) => {
      setSelectedRowKeys(selectedRowKeys);
      const flagids = selectedRows.map((item) => {
        return item.documentId
      })
      setdocumentids(flagids)
    },
  };
  const onGetQuoteDocumentList = async (pageNum: number = 1, pageSize: number = 10, keyword?: string, name: string = '') => {
    const params: any = {
      knowledge_id: knowledgeDetail.knowledgeId,
      standardClassification: keyword,
      name,
      pageNum,
      pageSize,
    };
    const res: any = await apis.getQuoteDocumentList(params);
    if (res?.code === 200) {
      setList(res.rows || [])
      setPage((prev) => ({ ...prev, total: res.total || prev.total }));
    }
  }
  const init = async () => {
    const res: any = await getAppState();
    const list = res || [];
    setAppStateList([{
      label: '全部',
      value: '',
    }, ...list]);
    // 初始tab key
    const initKey = String((knowledgeDetail.standardClassification ?? (list[0] && list[0].value)) || '');
    setActiveTabKey('');
    // 设置显示名称
    const match = list.find((it: any) => String(it.value) === String(initKey));
    if (match) setTitleName(match.label);
    // 首次请求
    onGetQuoteDocumentList(1, page.size, activeTabKey, '');
  }
  useEffect(() => {
    init();
  }, [])
  return (
    <>
      <Modal
        title="引用知识文库"
        width={'90%'}
        open={open}
        onCancel={onCancel}
        footer={<div className="flex justify-end gap-3 items-center">
          <Button onClick={onCancel}>取消</Button>
          <Button type="primary" loading={allLoding} onClick={() => handleOk()}>
            保存
          </Button>
        </div>}
      >
        <div className="flex items-center justify-between">
          <Tabs
            activeKey={activeTabKey}
            onChange={(key) => {
              setActiveTabKey(String(key));
              const match = appStateList.find((it: any) => String(it.value) === String(key));
              if (match) setTitleName(match.label);
              // 切换 tab 时重载列表
              onGetQuoteDocumentList(1, page.size, key, '');
              setdocumentids([]); // 清空已选择的文档ID
              setSelectedRowKeys([])
            }}
            items={appStateList.map((it: any) => ({ key: String(it.value), label: it.label }))}
          />
          <Input.Search
            placeholder="请输入文件名搜索"
            allowClear
            enterButton
            style={{ width: 260 }}
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e.target.value)}
            onSearch={(value) => {
              // 搜索时重新拉取第一页
              onGetQuoteDocumentList(1, page.size, activeTabKey, value);
            }}
          />
        </div>
        <Table
          scroll={{ x: 'max-content' }}
          rowSelection={{ type: 'checkbox', ...rowSelection }}
          rowKey={(record) => record.documentId}
          loading={listLoading}
          columns={columns}
          dataSource={list}
          pagination={paginationConfig}
        />
      </Modal>
      <PrevewSlice openDrawer={openDrawer} onClose={() => setOpenDrawer(false)} title="预览切片" record={selectedRecord} />
    </>
  );
};

export default QuoteModal;