import * as React from 'react';
import {
  List,
  Button,
  Divider,
  Flex,
  Layout,
  Empty,
  Image,
  Modal,
  Tag,
  message,
  Tooltip,
  Select,
  Form,
  Space,
  Row,
  Col,
  Input, Drawer
} from 'antd';
import {
  SearchOutlined,
  ReloadOutlined,
  BulbOutlined,
  CloseOutlined,
  HeartOutlined,
  SnippetsOutlined,
  CopyOutlined,
  ScissorOutlined,
  HeartFilled
} from '@ant-design/icons';
import * as AllIcons from '@ant-design/icons';

import { apis } from '@/apis';
import './style.less';
import { PaginationConfig } from 'antd/es/pagination';
import LocalStorage from '@/LocalStorage';
import IconSvg from "@/assets/public/icon.svg";
import dayjs from 'dayjs';
import Step from '@/components/step';
import { getContrastColor } from '@/utils';

import { useNavigate } from 'react-router-dom'
import PreviewModal from '../../audit/components/PreviewModal';


const FormItem = Form.Item;


const QuestionAnswerList: React.FC = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();

  interface Item {
    name: string,
    desc: string,
    appId: number,
    createBy: string,
    typeId: string;
    status: string;
    comment: string;
    auditStatus: string;
    projectName: string;
    updateTime: string;
  };

  interface PageInfo {
    pageNum: number,
    pageSize: number,
    total: number,
  };

  type AppTypeList = {
    label: string,
    value: string,
  }[];

  type ProjectTypeList = {
    label: string,
    value: string,
  }[];

  const [listLoading, setListLoading] = React.useState(false);
  const [list, setList] = React.useState<Item[]>([]);
  const [page, setPage] = React.useState<PageInfo>({
    pageNum: 1,
    pageSize: 10,
    total: 0,
  });
  const [knowCount, setKnowCount] = React.useState<string>();
  const { Header, Footer, Sider, Content } = Layout;
  const [appTypeList, setAppTypeList] = React.useState<AppTypeList>([]);
  const [appProjectList, setAppProjectList] = React.useState<AppTypeList>([]);
  const [showSubPanel, setShowSubPanel] = React.useState(false);
  const [selectedType, setSelectedType] = React.useState<string | null>('全部');
  const wrapperRef = React.useRef<HTMLDivElement>(null);
  const selectRef = React.useRef<any>(null);
  const [levelTypeList, setLevelTypeList] = React.useState<AppTypeList>([]);
  const [name, setName] = React.useState<string>('');
  const appApi = {
    fetchList: async (typeId: any, projectId: any) => {
      setListLoading(true);
      try {
        const res = await apis.fetchTakaiMyAppListApi({
          pageSize: page.pageSize,
          pageNum: page.pageNum,
          name: name,
        })
        const list = res.rows.map((item: any) => {
          return {
            name: item.name,
            desc: item.desc,
            appId: item.appId,
            createBy: item.createBy,
            typeId: item.typeId,
            status: item.status,
            comment: item.comment,
            auditStatus: item.auditStatus,
            projectName: item.projectName,
            updateTime: item.updateTime,
            iconType: item.iconType,
            iconColor: item.iconColor,
            knowledgeSize: item.knowledgeSize,
            documentSize: item.documentSize,
            sliceSize: item.sliceSize,
            userName: item.userName,
            isCollect: item.isCollect,
          }
        });
        setList(list);
        setPage({
          pageNum: page.pageNum,
          pageSize: page.pageSize,
          total: res.total,
        });
      } catch (error) {
        console.error(error);
      } finally {
        setListLoading(false);
      }
    },

    auditApplication: async (appId: string, userId: string) => {
      const res = await apis.auditTakaiApplicationLibApi(appId, userId);
      if (res.data === 9) {
        message.error('您没有添加审核人');
      }
      await appApi.fetchList(null, null);
    }
  };

  // 立即使用应用
  const useNowAppLication = (appId: number) => {
    const userInfo = LocalStorage.getUserInfo();
    const getToken = LocalStorage.getToken();
    // const baseUrl = import.meta.env.VITE_JUMP_URL;
    const baseUrl = 'https://llm.jkec.info:11432/#/knowledgeChat?showMenu=false&chatMode=LOCAL'
    window.open(`${baseUrl}&appId=${appId}&userId=${userInfo?.id}&nickName=${userInfo?.name}&token=${getToken}`, '_blank');
  }

  // 删除应用
  const delApplication = async (appId: string) => {
    try {
      await apis.deleteTakaiApplicationApi(appId);
      await appApi.fetchList(null, null);
    } catch (error) {
      console.error(error);
    }
  }

  // 获取应用类型
  const appTypeApi = {
    fetchAppType: async () => {
      try {
        const res = await apis.fetchTakaiAppTypeList('app_type');
        const list = res.data.map((item: any) => {
          return {
            label: item.dictLabel,
            value: item.dictCode,
          }
        });
        setAppTypeList(list);
      } catch (error: any) {
        console.error(error);
      }
    },
  };

  // 项目级应用下的类型
  const appProTypeApi = {
    fetchAppProType: async () => {
      try {
        const res = await apis.fetchTakaiAppTypeList('projectTree');
        // const list: AppTypeList = res.data;
        const list: AppTypeList = res.data?.reduce((acc: any, item: any) => {
          if (item.children.length > 0) {
            item.children.forEach((val: any) => {
              acc.push({
                label: val.label,
                value: `${val.value}`,
              })
            })
          }
          return acc;
        }, []);
        setAppProjectList(list);
      } catch (error: any) {
        console.error(error);
      }
    },
  };

  // 获取应用类型
  const levelTypeApi = {
    fetchLevelAppType: async () => {
      try {
        const res = await apis.fetchTakaiAppTypeList('project_type');
        const list = res.data.map((item: any) => {
          return {
            label: item.dictLabel,
            value: item.dictCode,
          }
        });
        setLevelTypeList(list);
      } catch (error: any) {
        console.error(error);
      }
    },
  };

  const init = async () => {
    await appApi.fetchList(null, null);
    await appTypeApi.fetchAppType();
    await appProTypeApi.fetchAppProType();
    await levelTypeApi.fetchLevelAppType();

    // 设置默认选择"全部"
    form.setFieldsValue({ typeId: '全部' });
  }
  const [evaluationTool, setEvaluationTool] = React.useState(false); // 评测工具 appCenter:questionAnswer:evaluationTool
  const [deleteFlag, setDeleteFlag] = React.useState(false); // 删除
  const [updateFlag, setUpdateFlag] = React.useState(false); // 编辑
  const [userInfoAll, setUserInfoAll] = React.useState<any>({});

  const selectOptions = React.useMemo(() => {
    const baseOptions: any[] = [
      { value: '1', label: '查看' },
      { value: '3', label: <Tooltip title="API服务" ><span>API服务</span></Tooltip> },
      // { value: '4', label: '编辑' },
      // { value: '6', label: '删除' },
    ];
    if (evaluationTool) {
      baseOptions.splice(1, 0, { value: '2', label: <Tooltip title="评测工具" ><span>评测工具</span></Tooltip> });
    }
    if (updateFlag) {
      baseOptions.splice(3, 0, { value: '4', label: '编辑' });
    }
    if (deleteFlag) {
      baseOptions.splice(5, 0, { value: '6', label: '删除' });
    }
    return baseOptions;
  }, [evaluationTool, updateFlag, deleteFlag]);
  React.useEffect(() => {
    setEvaluationTool(LocalStorage.getStatusFlag('appCenter:questionAnswer:evaluationTool'));
    setUpdateFlag(LocalStorage.getStatusFlag('appCenter:questionAnswer:edit'));
    setDeleteFlag(LocalStorage.getStatusFlag('appCenter:questionAnswer:del'));
    setUserInfoAll(LocalStorage.getUserInfo());
    init();
  }, [page.pageSize, page.pageNum])

  const paginationConfig: PaginationConfig = {
    // 显示数据总量
    showTotal: (total: number) => {
      return `共 ${total} 条`;
    },
    // 展示分页条数切换
    showSizeChanger: true,
    // 指定每页显示条数
    // pageSizeOptions: ['2', '20', '50', '100'],
    // 快速跳转至某页
    showQuickJumper: true,
    current: page.pageNum,
    pageSize: page.pageSize,
    total: page.total,
    onChange: (pageNum, pageSize) => {
      setPage({
        pageNum: pageNum,
        pageSize: pageSize,
        total: page.total,
      });
    },
  };

  // 点击查询
  const handleClickSearch = async () => {
    form.validateFields().then(async (values) => {
      if (values.proTypeId) {
        values.typeId = values.proTypeId;
      }
      if (values.typeId === '全部') {
        values.typeId = null;
      }
      if (values.projectId instanceof Array && values.projectId.length == 2) {
        values.projectId = values.projectId[1];
      }
      await appApi.fetchList(values.typeId, values.projectId);
    }).catch((error) => {
      console.error(error);
    });
  };
  const [drawerFlag, setDrawerFlag] = React.useState<boolean>(false);
  const [drawerData, setDrawerData] = React.useState<any>({});
  // 点击跳转
  const handleChange = async (e: string, item: any) => {
    if (e === '1') {
      // setDrawerFlag(true)
      // setDrawerData(item)
      const userInfo = LocalStorage.getUserInfo();
      const getToken = LocalStorage.getToken();
      const baseUrl = import.meta.env.VITE_JUMP_URL;
      // const baseUrl = 'https://llm.jkec.info:11432/#/knowledgeChat?showMenu=false&chatMode=LOCAL'
      window.open(`${baseUrl}&appId=${item.appId}&userId=${userInfo?.id}&nickName=${userInfo?.name}&token=${getToken}`, '_blank');
    }
    if (e === '2') {
      // evaluationTool/evaluationTask
      navigate({ pathname: '/evaluationTool/evaluationTask' }, {});
    }
    if (e === '4') {
      navigate({ pathname: '/appCenter/questionAnswer/modify' }, { state: { id: item.appId } });
    }
    if (e === '6') {
      Modal.confirm({
        title: '删除',
        content: `确定删除应用: ` + item.name + ` 吗？`,
        okType: 'danger',
        onOk: async () => {
          await delApplication(item.appId.toString());
        }
      });
    }
  };

  /** 点击外部关闭面板 */
  React.useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (wrapperRef.current && !wrapperRef.current.contains(event.target as Node)) {
        setShowSubPanel(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside, true);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside, true);
    };
  }, []);


  const handleAppTypeChange = (value: string) => {
    if (value === '41') {
      // 如果是项目级应用，切换面板状态
      // setShowSubPanel(prev => !prev);
      setShowSubPanel(true);
    } else {
      // 其他选项，隐藏面板
      setShowSubPanel(false);
    }
    setSelectedType(value);
    form.setFieldsValue({ typeId: value });

    // 自动提交逻辑
    if (value === '全部') {
      // 全部选项，传递null给后端
      appApi.fetchList(null, null);
    } else {
      // 其他选项，传递对应的typeId
      appApi.fetchList(value, null);
    }
  };

  const handleAppProTypeChange = (value: string) => {
    console.log(value, 'valuevalue');

    setSelectedType(value);
    form.setFieldsValue({ typeId: value });
  };
  const [showGuide, setShowGuide] = React.useState<boolean>(() => localStorage.getItem('questionAnswer') !== 'true');
  const hideGuide = () => { localStorage.setItem('questionAnswer', 'true'); setShowGuide(false); };
  const steps = [
    {
      title: '创建RAG应用',
      description: '按特定场景/领域管理知识库，当前仅创建空的知识库集合。',
      number: 1,
    },
    {
      title: '参数配置',
      description: '选择知识库、调试Prompt、配置参数；',
      number: 2,
    },
    {
      title: '发布应用，支持API调用',
      description: '成功发布应用后，支持API形式调用，管理员也会挑选推荐至应用广场',
      number: 3,
    }
  ]
  return (
    <div>
      <div style={{ padding: '16px 20px' }}>

        {showGuide && <> <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
          <div style={{ fontSize: 13, color: '#333', display: 'flex', alignItems: 'center', gap: 6 }}>
            <BulbOutlined style={{ color: '#faad14' }} />
            提示: 如何创建并管理自己的应用？
          </div>
          <CloseOutlined onClick={hideGuide} style={{ color: '#999', cursor: 'pointer' }} />
        </div>
          <Step steps={steps} className='mb-3' /></>}
        <Form
          form={form}
          layout='inline'
          colon={false}
          style={{ flex: 1, display: 'flex', alignItems: 'center' }}
        >
          <p>我创建的RAG应用：</p>
          <Space.Compact style={{ width: '300px' }}>
            <Input
              placeholder='请输入应用名称进行搜索'
              value={name}
              onChange={(e) => { setName(e.target.value) }}
            />
            <Button type="primary" onClick={() => { init() }}><SearchOutlined /></Button>
          </Space.Compact>
        </Form>
      </div>
      {
        // list.length
        //   ?
        <div className='questionAnswerList'>
          <div className='applicationList'>
            <List grid={{
              gutter: 16,
              xs: 1,
              sm: 1,
              md: 2,
              lg: 2,
              xl: 3,
              xxl: 4, // 展示的列数
            }}
              loading={listLoading}
              dataSource={list}
              renderItem={(item: any) => (
                <List.Item>
                  <div className='card group relative overflow-visible' tabIndex={0}>
                    <div style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                      overflow: 'hidden',
                    }}>
                      <div style={{ display: 'flex', alignItems: 'center', overflow: 'auto' }}>
                        <div style={{ marginRight: 10, overflow: 'auto', background: item.iconColor, width: 50, height: 50, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                          {item.iconType ? (() => {
                            const C = (AllIcons as any)[item.iconType];
                            const iconColor = getContrastColor(item.iconColor);
                            return C ? <C style={{ fontSize: 28, color: iconColor }} /> : <span style={{ fontSize: 12 }}>{item.iconType}</span>
                          })()
                            : <Image
                              width={32}
                              height={32}
                              src={IconSvg}
                              preview={false}
                            />}
                        </div>
                        {/* <div style={ { overflow: 'auto' } }> */}
                        {/*  { item.name }*/}
                        {/*</div>*/}

                        <div style={{
                          display: 'flex',
                          flexDirection: 'column',
                          justifyContent: 'center',
                          overflow: 'hidden',
                          maxWidth: '85%',
                          height: '100%'
                        }}>
                          <Tooltip title={item.name} placement="top">
                            <div style={{
                              lineHeight: '18px',
                              fontSize: 14,
                              fontWeight: 500,
                              overflow: 'hidden',
                              textOverflow: 'ellipsis',
                              whiteSpace: 'nowrap',
                              // maxWidth: '200px', // 可以根据需要调整宽度
                              cursor: 'pointer'
                            }}>
                              <span>
                                {item.name.length > 20 ? `${item.name.substring(0, 30)}...` : item.name}
                              </span>
                            </div>
                          </Tooltip>
                          <Space size={4} style={{ lineHeight: '18px' }}>
                            <span style={{
                              color: '#999',
                              fontSize: 12,
                              margin: 0
                            }}>创建者:{item.userName}</span>
                            <Divider type="vertical" style={{ color: '999', margin: 0, height: 12 }} />
                            <span style={{ color: '#999', fontSize: 12 }}>
                              {
                                item.projectName && item.projectName.length > 8 ?
                                  `${item.projectName.substring(0, 8)}...` :
                                  item.projectName
                              }
                            </span>
                          </Space>
                        </div>

                      </div>
                      <div>
                        <>
                          {/*{ item.projectName } 移动599 line*/}
                          <div className='w-full flex flex-col items-end justify-end'>
                            <div className='chak'>
                              {item.isCollect && <HeartFilled style={{ color: '#F5E663' }} className='mr-2' onClick={async () => {
                                if (item.isCollect) {
                                  const res: any = await apis.delCollectApi(item.appId);
                                  if (res.code === 200) {
                                    message.success('取消收藏成功')
                                    await appApi.fetchList(null, null);
                                  }
                                }
                              }} />}
                              {!item.isCollect && <HeartOutlined onClick={async () => {
                                if (!item.isCollect) {
                                  const res: any = await apis.setCollectApi(item.appId);
                                  if (res.code === 200) {
                                    message.success('收藏成功')
                                    await appApi.fetchList(null, null);
                                  }
                                }
                              }} className='mr-2' />}
                              <Select
                                defaultValue="1"
                                style={{ width: 70 }}
                                onSelect={(e) => { handleChange(e, item) }}
                                size='small'
                                options={(() => {
                                  const opts = [...selectOptions];
                                  if (userInfoAll && String(userInfoAll.id) === String(item.createBy)) {
                                    if (!opts.some((o: any) => String(o.value) === '4')) {
                                      opts.push({ value: '4', label: '编辑' });
                                    }
                                    if (!opts.some((o: any) => String(o.value) === '6')) {
                                      opts.push({ value: '6', label: '删除' });
                                    }
                                  }
                                  return opts;
                                })()}
                              /></div>
                          </div>
                        </>
                      </div>
                    </div>
                    <p style={{ margin: '8px 0' }}></p>
                    {/* <Divider plain style={{ margin: '16px 0' }}></Divider> */}
                    <div style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center'
                    }}>
                      <span style={{
                        color: '#999',
                        fontSize: 12,
                        margin: 0
                      }}>更新时间: {dayjs(item.updateTime).format("YYYY-MM-DD HH:mm:ss")}</span>
                      <Tag
                        style={{
                          // padding: '4px 8px',
                          marginRight: 0,
                          fontSize: 12,
                          fontWeight: 600,
                          background: '#f8f8f8',
                          // border: '1px solid #d9d9d9'
                        }}
                      >
                        {
                          appTypeList
                            .find(item1 => item1.value.toString() === item.typeId)?.label || levelTypeList.find(item2 => item2.value.toString() === item.typeId)?.label || '未分类'
                        }
                      </Tag>
                    </div>
                    <div className='desc'>
                      {
                        item.desc !== '' && item.desc !== null && item.desc.length > 40 ? item.desc.substring(0, 40) + '......' : item.desc
                      }
                    </div>
                    <div className='flex justify-between'>
                      <div className='' style={{ display: 'flex', width: '100%', alignItems: 'center', justifyContent: 'space-between', gap: 16, background: '#fafafa', padding: '8px 12px', borderRadius: 8 }}>
                        <div style={{ color: '#595959', fontSize: 13 }}>
                          API调用：<a style={{ color: '#1677ff' }} href="#">接口文档</a>
                        </div>
                        <div>
                          {/* < Tag style={{
                            // marginLeft: 16,
                            backgroundColor: item.status === '1' ? '#D26900' : item.status === '2' ? '#408080' : item.auditStatus === '4' ? '#CE0000' : item.status === '5' ? '#5151A2' : ''
                          }}>
                            审核通过
                          </Tag> */}
                          {
                            (item.status !== null && item.status !== '3') &&
                            < Tag style={{
                              // marginLeft: 16,
                              backgroundColor: item.status === '1' ? '#D26900' : item.status === '2' ? '#408080' : item.auditStatus === '4' ? '#CE0000' : item.status === '5' ? '#5151A2' : '',
                              color: item.status === '1' ? '#000000' : item.status === '2' ? '#ffffff' : item.auditStatus === '4' ? '#000000' : item.status === '5' ? '#000000' : ''
                            }}>
                              {item.status === '1' ? '待审核' : item.status === '2' ? '审核中' : item.auditStatus === '4' ? '审核拒绝' : item.status === '5' ? '待提交' : '未知'}
                            </Tag>
                          }
                          {
                            (item.auditStatus === '4') &&
                            <Tooltip title={item.comment}>
                              {
                                item.comment !== '' && item.comment !== null && item.comment.length > 10 ?
                                  item.comment.substring(0, 10) + '......' :
                                  item.comment
                              }
                            </Tooltip>
                          }
                        </div>
                        <div className='flex items-center'>
                          <Divider type="vertical" style={{ height: 20, color: '#d9d9d9' }} />
                          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', fontSize: 12, color: '#595959' }}>
                            <Tooltip title='知识库数量' placement="top">
                              <div className='cursor-pointer' style={{ fontWeight: 600, marginTop: 4 }}>
                                <SnippetsOutlined /> {item.knowledgeSize}
                              </div>
                            </Tooltip>
                          </div>
                          <Divider type="vertical" style={{ height: 20, color: '#d9d9d9' }} />
                          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', fontSize: 12, color: '#595959' }}>
                            {/* <div></div> */}
                            <Tooltip title='文档数量' placement="top">
                              <div className='cursor-pointer' style={{ fontWeight: 600, marginTop: 4 }}>
                                <CopyOutlined /> {item.documentSize}
                              </div>
                            </Tooltip>
                          </div>
                          <Divider type="vertical" style={{ height: 20, color: '#d9d9d9' }} />
                          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', fontSize: 12, color: '#595959' }}>
                            <Tooltip title='切片数量' placement="top">
                              <div className='cursor-pointer' style={{ fontWeight: 600, marginTop: 4 }}><ScissorOutlined />{item.sliceSize}</div>
                            </Tooltip>

                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </List.Item>
              )}
              pagination={paginationConfig} // 分页
            />
          </div>
        </div>
      }
      <Drawer
        title={drawerData.name}
        closable={{ 'aria-label': 'Close Button' }}
        onClose={() => { setDrawerFlag(false) }}
        width="80%"
        open={drawerFlag}
      >
        {/* {drawerFlag && <PreviewModal isComponent={true} AuditAppId={drawerData.appId} />} */}
      </Drawer>
    </div>
  )
};

export default observer(QuestionAnswerList);
