import * as React from 'react';
import { generatePath, useParams, useLocation, useNavigate } from 'react-router-dom';

import PrevewSlice from './components/prevewSlice';

import config, { getHeaders } from '@/apis/config';

import {
  Button,
  Table,
  TableColumnsType,
  Modal,
  TablePaginationConfig,
  Upload,
  UploadProps,
  message,
  Tooltip,
  Spin,
  Input,
  Space
} from 'antd';
import type { TableProps } from 'antd';

import { EditOutlined, DeleteOutlined, InboxOutlined, PlusOutlined, ArrowLeftOutlined, EyeOutlined, ExportOutlined, FileTextOutlined, ArrowDownOutlined, SearchOutlined } from '@ant-design/icons';
import InfoModal from './components/InfoModal';
import InfoModalSetting from './components/InfoModalSetting';
import UploadModal from './components/UploadModal';
import MdModal from './components/MdModal'
import QuoteModal from './components/QuoteModal'
import router from '@/router';
import { Record } from './types';
import dayjs from 'dayjs';
import axios from 'axios';
import LocalStorage from '@/LocalStorage';
import store from './store';
import './style.less';
import { apis } from '@/apis';
import { useLayoutStore } from '@/pages/layout/store';
const { Dragger } = Upload;

const KnowledgeLibInfo: React.FC = () => {
  const navigate = useNavigate()
  const {
    handleNameChange,
    state,
    init,
    onClickModify,
    onClickDelete,
    onChangePagination,
    onClickDocumentDetail,
    infoModalOnClickConfirm,
    infoModalOnClickCancel,
    infoModalSettingOnClickConfirm,
    infoModalSettingOnClickCancel,
    onClickSettings,
    reset,
    onDeleteTakaiDocumentLibApi,
    onExportDocumentSliceExport
  } = store;
  const { onSetRoouterName } = useLayoutStore()
  const {
    knowledge_id,
    listLoading,
    page,
    list,
    processingList, // 处理中的状态
    infoModalOpen,
    infoModalId,
    infoModalSettingOpen,
    infoModalSettingId,
    knowledgeDetail,
  } = state;
  const location = useLocation();
  const [uploadLoading, setUploadLoading] = React.useState(false);

  const params = useParams();

  const [mdModalOpen, setMdModalOpen] = React.useState(false); // 切片弹窗
  const [quoteModalOpen, setQuoteModalOpen] = React.useState(false); // 引用知识库弹窗
  const [detailDocument, setDetailDocument] = React.useState<any>({}); // 切片详情
  const [userInfoAll, setUserInfoAll] = React.useState<any>({});
  const [uploadModalOpen, setUploadModalOpen] = React.useState<boolean>(false);
  const [record, setRecord] = React.useState<any>({});
  const [deletingIds, setDeletingIds] = React.useState<string[]>([]);
  const [standardClass, setStandardClass] = React.useState<any[]>([]);// 分类-下拉选项
  const [parsingTypeList, setParsingTypeList] = React.useState<any[]>([]);// 解析工具-下拉选项
  const [splittingType, setSplittingType] = React.useState<any>([]); // 选择切分规则 
  // 获取选择分类
  const fetchAppstandardClass = async () => {
    try {
      const res = await apis.fetchTakaiAppTypeList('standard_classification');
      const list = res.data.map((item: any) => {
        return {
          label: item.dictLabel,
          value: item.dictValue,
        }
      });
      setStandardClass(list);
    } catch (error: any) {
      console.error(error);
    }
  }
  // 获取解析工具
  const fetchParsingTypeList = async () => {
    try {
      const res = await apis.fetchTakaiAppTypeList('parsing_type');
      const list = res.data.map((item: any) => {
        return {
          label: item.dictLabel,
          value: item.dictValue,
        }
      });
      setParsingTypeList(list);
    } catch (error: any) {
      console.error(error);
    }
  }
  // 获取向默认切分规则
  const fetchsplittingType = async () => {
    try {
      const res = await apis.fetchTakaiAppTypeList('splitting_type');
      const list = res.data.map((item: any) => {
        return {
          label: item.dictLabel,
          value: item.dictValue,
        }
      });
      setSplittingType(list);
    } catch (error: any) {
      console.error(error);
    }
  }
  const [cUpdateFlag, setCUpdateFlag] = React.useState<boolean>();
  const [deleteFlag, setDeleteFlag] = React.useState<boolean>(); // 删除权限
  const [createFlag, setCreateFlag] = React.useState<boolean>();
  const [updateDoc, setupdateDoc] = React.useState<boolean>(false); // 上传知识文件权限
  const [quoteDoc, setQuoteDoc] = React.useState<boolean>(false); // 引用知识文件权限
  const [exportSlice, setExportSlice] = React.useState<boolean>(false); // 导出切片权限
  const [exportMd, setExportMd] = React.useState<boolean>(false); // 导出Md权限
  const [exportOr, setExportOr] = React.useState<boolean>(false); // 导出原文件权限
  const [slicPre, setSlicePre] = React.useState<boolean>(false); // 查看切片
  const [configuration, setConfiguration] = React.useState<boolean>(false); // 配置权限
  const [editName, setEditName] = React.useState<boolean>(false); // 编辑名称
  React.useEffect(() => {
    fetchAppstandardClass();
    fetchParsingTypeList();
    fetchsplittingType();
    init(params.knowledgeId);
    setupdateDoc(LocalStorage.getStatusFlag('knowledgeLib:detail:update'));
    setQuoteDoc(LocalStorage.getStatusFlag('knowledgeLib:detail:quote'));
    setExportSlice(LocalStorage.getStatusFlag('knowledgeLib:detail:exportSlice'));
    setExportMd(LocalStorage.getStatusFlag('knowledgeLib:detail:exportMd'));
    setExportOr(LocalStorage.getStatusFlag('knowledgeLib:detail:exportOr'));
    setSlicePre(LocalStorage.getStatusFlag('knowledgeLib:detail:slice'));
    setConfiguration(LocalStorage.getStatusFlag('knowledgeLib:detail:configuration'));
    setEditName(LocalStorage.getStatusFlag('knowledgeLib:detail:editName'));


    const cDetail = LocalStorage.getStatusFlag('deepseek:config:update');
    setCUpdateFlag(cDetail);
    const deleteF = LocalStorage.getStatusFlag('knowledgeLib:detail:del');
    setDeleteFlag(deleteF);
    const createF = LocalStorage.getStatusFlag('deepseek:document:create');
    setCreateFlag(createF);
    setUserInfoAll(LocalStorage.getUserInfo());
    return () => reset();
  }, []);

  React.useEffect(() => {
    // console.log('knowledgeDetail',knowledgeDetail)
    if (knowledgeDetail.name) {
      onSetRoouterName(knowledgeDetail.name)
    }
  }, [knowledgeDetail])

  const [documentids, setdocumentids] = React.useState<string[]>([]);
  const rowSelection: TableProps<Record>['rowSelection'] = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: Record[]) => {
      const flagids = selectedRows.map((item) => {
        return item.documentId
      })
      setdocumentids(flagids)
    },
  };

    const [openDrawer, setOpenDrawer] = React.useState<boolean>(false);


  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: 'suffix',
      width: 100,
      render: (text, record) => {
        return (
          `${text}`
        )
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 180,
      render: (text) => {
        if (text === '4') {
          return <Spin size="small" />;
        } else if (text === '5' || text === '1') {
          return '已完成';
        } else if (text === '6' || text === '2') {
          return '处理失败';
        }
      }
    },
    {
      title: '文件大小',
      dataIndex: 'length',
      width: 100,
      render: (text) => {
        if (text) {
          const size = (text / 1024 / 1024).toFixed(2);
          return `${size} M`;
        } else {
          return '--'
        }
      }
    },
    {
      title: '分类',
      dataIndex: 'standardClassification',
      width: 100,
      render: (text) => {
        if (text) {
          standardClass.forEach((item: any) => {
            if (item.value === text) {
              text = item.label
            }
          });
          return `${text}`;
        } else {
          return '--'
        }
      }
    },
    {
      title: '解析工具',
      dataIndex: 'parsingType',
      width: 100,
      render: (text) => {
        if (text) {
          parsingTypeList.forEach((item: any) => {
            if (item.value === text) {
              text = item.label
            }
          });
          return `${text}`;
        } else {
          return '--'
        }
      }
    },
    {
      title: '切分规则',
      dataIndex: 'customSeparator',
      width: 100,
      render: (text) => {
        if (text) {
          splittingType.forEach((item: any) => {
            if (item.value === text) {
              text = item.label
            }
          });
          return `${text}`;
        } 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) => {
        const isProcessing = record.status === '4';
        return (
          <>
            {
              <a
                style={{
                  marginRight: 16,
                  color: isProcessing ? '#d9d9d9' : undefined,
                  cursor: isProcessing ? 'not-allowed' : 'pointer'
                }}
                onClick={() => {
                  setOpenDrawer(true);
                  setDetailDocument(record);
                }}
              >
                查看
              </a>
            }
            {
              (record.standardClassification !== '3' && (slicPre || userInfoAll.id === record.createBy)) && <a
                style={{
                  marginRight: 16,
                  color: isProcessing ? '#d9d9d9' : undefined,
                  cursor: isProcessing ? 'not-allowed' : 'pointer'
                }}
                onClick={() => {
                  if (isProcessing) return;
                  // const path = generatePath('/knowledge/knowledgeLib/:knowledgeId/:createBy/slice/:documentId/:embeddingId', {
                  //   knowledgeId: params.knowledgeId as string,
                  //   createBy: params.createBy as string,
                  //   documentId: record.documentId,
                  //   embeddingId: state.knowledgeDetail.embeddingId,
                  // });
                  // router.navigate({ pathname: path }, { state: { createBy: record.createBy } });
                  setMdModalOpen(true);
                  setDetailDocument(record);
                }}
              >
                切片
              </a>
            }
            {
              (configuration || userInfoAll.id === record.createBy) && <a
                style={{
                  marginRight: 16,
                  color: isProcessing ? '#d9d9d9' : undefined,
                  cursor: isProcessing ? 'not-allowed' : 'pointer'
                }}
                onClick={() => {
                  if (isProcessing) return;
                  onClickSettings(record.documentId);
                  setRecord(record)
                }}
              >
                配置
              </a>
            }
            {
              (editName || userInfoAll.id === record.createBy) &&
              <a
                style={{
                  marginRight: 16,
                  color: isProcessing ? '#d9d9d9' : undefined,
                  cursor: isProcessing ? 'not-allowed' : 'pointer'
                }}
                onClick={() => {
                  if (isProcessing) return;
                  onClickModify(record.documentId);
                }}>
                <EditOutlined />
              </a>
            }
            {
              (deleteFlag || userInfoAll.id === record.createBy) &&
              <Button
                type="link"
                danger
                className='p-0 mr-0'
                onClick={() => {
                  if (isProcessing) return;
                  Modal.confirm({
                    title: '删除',
                    content: `确定删除知识文件:${record.name}吗？`,
                    okType: 'danger',
                    onOk: async () => {
                      try {
                        setDeletingIds((prev) => [...prev, record.documentId]);
                        const userInfo = LocalStorage.getUserInfo();
                        await onClickDelete(record.documentId);
                      } finally {
                        setDeletingIds((prev) => prev.filter((id) => id !== record.documentId));
                      }
                    }
                  });
                }}
                loading={deletingIds.includes(record.documentId)}
                disabled={isProcessing || deletingIds.includes(record.documentId)}
                icon={<DeleteOutlined />}
              />
            }
          </>
        )
      }
    }
  ];

  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) => {
      await onChangePagination(page, pageSize);
    },
  };
  const progressBar = () => {
    return processingList.map((item: any, index: number) => {
      return <div key={index} className='knowledgeLibInfo-progress'>
        <div className="task-card bg-[#FAFAFA] rounded-xl py-2 px-5 card-shadow task-item fade-in" data-status="processing" data-name="市场调研报告需求.docx" data-date="2023-06-15 09:32" data-project-id="1" data-project-name="电商平台重构" data-project-color="#165DFF">
          <div className="flex flex-wrap justify-between items-start mb-2">
            <div>
              <div className="flex items-center">
                <p className="font-semibold text-[14px]" style={{ marginRight: 16 }}>{item?.name}</p>
              </div>
              <p className="text-[12px] text-gray-500">上传于：{item?.createTime}</p>
            </div>
            {item?.status === '0' && <span className="bg-blue-100 text-primary text-xs font-medium px-2.5 py-0.5 rounded-full flex items-center mt-1">
              <i className="fa fa-spinner fa-spin mr-1"></i> 处理中
            </span>}
            {item?.status === '2' && <span className="bg-blue-100 text-primary text-xs font-medium px-2.5 py-0.5 rounded-full flex items-center mt-1">
              处理失败
            </span>}
            {item?.status === '3' && <span className="bg-blue-100 text-primary text-xs font-medium px-2.5 py-0.5 rounded-full flex items-center mt-1">
              待处理
            </span>}
            {item?.progress === 100 && <span className="bg-green-100 text-success text-xs font-medium px-2.5 py-0.5 rounded-full flex items-center mt-1">
              <i className="fa fa-check mr-1"></i> 已完成
            </span>}
          </div>
          <div className="mb-1">
            <div className="flex justify-between text-[12px] mb-1">
              <span>处理进度</span>
              <span id="progressText-1">{item?.progress}%</span>
            </div>
            <div className="w-full bg-gray-200 rounded-full h-2.5">
              <div className="progress-bar bg-blue-500 h-2.5 rounded-full" style={{ width: `${item?.progress}%` }} id="progressBar-1"></div>
            </div>
            <div className="flex justify-between text-[11px] mt-1">
              <span className='text-error'>{item?.errorMessage}</span>
              <p>
                <EyeOutlined className='mr-2 cursor-pointer' onClick={() => {
                  window.open(item?.url)
                }} />

                {(deleteFlag || userInfoAll.id === item.createBy) && <Button
                  type="link"
                  danger
                  className='p-0'
                  onClick={() => {
                    Modal.confirm({
                      title: '删除',
                      content: `确定删除知识文件:${item.name}吗？`,
                      okType: 'danger',
                      onOk: async () => {
                        try {
                          setDeletingIds((prev) => [...prev, item.documentId]);
                          await onDeleteTakaiDocumentLibApi(item.documentId)
                        } finally {
                          setDeletingIds((prev) => prev.filter((id) => id !== item.documentId));
                        }
                      }
                    });
                  }}
                  loading={deletingIds.includes(item.documentId)}
                  disabled={deletingIds.includes(item.documentId)}
                  icon={<DeleteOutlined />}
                />}
              </p>
            </div>
          </div>
        </div>
      </div>
    })
  }
  return (
    <div className='knowledgeLibInfo'>
      <Spin spinning={false}>
        {
          <>
            <div className='knowledgeLibInfo-operation'>
              <Button
                type='primary'
                icon={<ArrowLeftOutlined />} onClick={() => {
                  navigate({ pathname: '/knowledge/knowledgeLib' });
                }}>
                返回
              </Button>
              {
                // ((createFlag && userInfoAll.id === 1) || userInfoAll.id === params?.createBy) &&
                <p>
                  {updateDoc && <Button
                    icon={<PlusOutlined />}
                    onClick={() => setUploadModalOpen(true)}
                  >
                    上传知识文件
                  </Button>}
                  {quoteDoc && <Button
                    type='primary'
                    className='ml-3'
                    onClick={() => setQuoteModalOpen(true)}
                  >
                    引用知识文件
                  </Button>}</p>
              }
            </div>
            {/* 进度条 */}
            <div>
              {progressBar()}
            </div>
            <div className='knowledgeLibInfo-operation' style={{ justifyContent: 'flex-end' }}>
              <Space.Compact style={{ width: '300px' }} className='mr-3'>
                <Input
                  placeholder='请输入文件名称进行搜索'
                  value={state.name}
                  onChange={(e) => handleNameChange(e.target.value)}
                />
                <Button type="primary" onClick={() => { onClickDocumentDetail() }}><SearchOutlined /></Button>
              </Space.Compact>
              {
                // ((userInfoAll.id === 1) || userInfoAll.id === params?.createBy) &&
                <p>
                  {exportSlice && <Tooltip title="导出切片">
                    <Button
                      icon={<ExportOutlined />}
                      onClick={() =>
                        onExportDocumentSliceExport(documentids, 1)
                      }
                    >
                    </Button>
                  </Tooltip>}
                  {exportMd && <Tooltip title="导出MD文件">
                    <Button
                      className='ml-3'
                      icon={<FileTextOutlined />}
                      onClick={() =>
                        onExportDocumentSliceExport(documentids, 2)
                      }
                    >
                    </Button>
                  </Tooltip>}
                  {exportOr && <Tooltip title="导出原文件">
                    <Button
                      className='ml-3'
                      icon={<ArrowDownOutlined />}
                      onClick={() =>
                        onExportDocumentSliceExport(documentids, 3)
                      }
                    >
                    </Button>
                  </Tooltip>}
                </p>
              }
            </div>
            <div className='knowledgeLibInfo-table'>
              <Table
                scroll={{ x: 'max-content' }}
                rowSelection={{ type: 'checkbox', ...rowSelection }}
                rowKey={(record) => record.documentId}
                loading={listLoading}
                columns={columns}
                dataSource={list}
                pagination={paginationConfig}
              />
            </div>
            {/* 上传知识文件 */}
            {(uploadModalOpen||knowledgeDetail?.createBy === userInfoAll.id) && <UploadModal
              open={uploadModalOpen}
              knowledgeId={params.knowledgeId || ''}
              knowledgeDetail={knowledgeDetail}
              onCancel={() => setUploadModalOpen(false)}
              onSuccess={() => {
                init(params.knowledgeId, 2);
              }}
            />}
            {
              (infoModalOpen||knowledgeDetail?.createBy === userInfoAll.id) &&
              <InfoModal
                id={infoModalId}
                open={infoModalOpen}
                onClickConfirm={infoModalOnClickConfirm}
                onClickCancel={infoModalOnClickCancel}
              />
            }

            {
              infoModalSettingOpen &&
              <InfoModalSetting
                id={infoModalSettingId}
                open={infoModalSettingOpen}
                record={record}
                onClickConfirm={infoModalSettingOnClickConfirm}
                onClickCancel={infoModalSettingOnClickCancel}
              />
            }
          </>
        }
      </Spin>
      {mdModalOpen && <MdModal open={mdModalOpen} detailDocument={detailDocument} knowledgeDetail={knowledgeDetail} onCancel={(type?: number) => {
        init(params.knowledgeId, 2, '0');
        if (!type) {
          setMdModalOpen(false)
        }
      }}></MdModal>}
      {quoteModalOpen && <QuoteModal open={quoteModalOpen} knowledgeDetail={knowledgeDetail} onCancel={() => { init(params.knowledgeId, 2); setQuoteModalOpen(false) }}></QuoteModal>}
      <PrevewSlice openDrawer={openDrawer} onClose={() => setOpenDrawer(false)} title={detailDocument?.name || '预览切片'} record={detailDocument} />
      
    </div>
  );
};

export default KnowledgeLibInfo;
