import * as React from 'react';
import { observer } from 'mobx-react';
import {
  List,
  Button,
  Divider,
  Flex,
  Layout,
  Empty,
  Image,
  Modal,
  Tag,
  message,
  Tooltip,
  Select,
  Form,
  Space,
  Row,
  Col,
  Input,
  Cascader,
  Pagination,
} from 'antd';
import {
  HeartFilled,
  BookOutlined,
  TeamOutlined,
  AppstoreOutlined,
  HeartOutlined,
  GlobalOutlined
} from '@ant-design/icons';
import { apis } from '@/apis';
import './style.less';
import { PaginationConfig } from 'antd/es/pagination';
import router from '@/router';
import LocalStorage from '@/LocalStorage';
import IconSvg from "@/assets/public/icon.svg";
import bg1 from "@/assets/public/bg1.png";
const FormItem = Form.Item;
import * as AllIcons from '@ant-design/icons';
import { getContrastColor } from '@/utils';


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

  interface Item {
    name: string,
    desc: string,
    appId: string,
    createBy: string,
    typeId: string;
    status: string;
    comment: string;
    auditStatus: string;
    projectName: string;
    updateTime: string;
    isCollect: boolean;
    iconType: string;
    iconColor: string;
    groupVisible?: string;
  };

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

  type AppTypeList = {
    label: string,
    value: string,
    dictCode: 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: 12,
    total: 0,
  });
  const [appTypeList, setAppTypeList] = React.useState<AppTypeList>([]);
  const [showSubPanel, setShowSubPanel] = React.useState(false);
  const [selectedType, setSelectedType] = React.useState<string>('全部');
  const wrapperRef = React.useRef<HTMLDivElement>(null);
  const selectRef = React.useRef<any>(null);
  const [levelTypeList, setLevelTypeList] = React.useState<AppTypeList>([]);

  const appApi = {
    fetchList: async (typeId: any, projectId: any) => {
      setListLoading(true);
      try {
        const userInfo = LocalStorage.getUserInfo();
        const userId = (userInfo?.id ?? '').toString();
        const keyword = form.getFieldValue('keyword');
        const res = await apis.fetchTakaiAppList({
          pageSize: page.pageSize,
          pageNum: page.pageNum,
          userId: userId,
          isCollect: typeId==='收藏' ? '1' : null,
          typeId: typeId==='收藏'|| typeId==='全部' ? null : typeId,
          projectId: projectId?.toString(),
          keyword: keyword,
        })
        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,
            isCollect: item.isCollect,
            iconType: item.iconType,
            iconColor: item.iconColor,
            groupVisible: item.groupVisible,
          }
        });
        const c = LocalStorage.getStatusFlag('deepseek:application:create');
        const u = LocalStorage.getStatusFlag('deepseek:application:delete');
        const filteredList = list.filter((item: any) => {
          // 如果有 createFlag 或 updateFlag 权限，显示所有数据
          if (c || u) {
            return true;
          }
          // 没有权限时排除 status='5' 的数据
          return item.status !== '5';
        });
        setList(filteredList);
        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: string) => {
    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 appTypeApi = {
    fetchAppType: async () => {
      try {
        const res = await apis.fetchTakaiAppTypeList('app_type');
        const list = res.data.map((item: any) => {
          return {
            label: item.dictLabel,
            value: item.dictValue,
            dictCode: item.dictCode,
          }
        });
        setAppTypeList([{
          label: '收藏',
          value: '收藏',
          dictCode: '收藏',
        },{
          label: '全部',
          value: '全部',
          dictCode: '全部',
        },...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.dictValue,
          }
        });
        setLevelTypeList(list);
      } catch (error: any) {
        console.error(error);
      }
    },
  };

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

    // 设置默认选择"全部"
    form.setFieldsValue({ typeId: '全部' });
  }

  React.useEffect(() => {
    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,
      });
    },
  };

  /** 点击外部关闭面板 */
  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);
    };
  }, []);


  // Tab切换逻辑
  const handleTabChange = (key: string) => {
    setSelectedType(key);
    form.setFieldsValue({ typeId: key });
    if (key === '全部') {
      appApi.fetchList(null, null);
    } else {
      appApi.fetchList(key, null);
    }
  };

  return (
    <div className="h-full bg-cover bg-center" style={{ backgroundImage: `url(${bg1})`, overflowX: 'hidden' }}>
      <div className="flex flex-col items-center justify-center pt-2 pb-5">
        <Form form={form} layout="inline" colon={false}>
          <FormItem name="typeId" style={{ marginBottom: 0 }}>
            <div className="w-full flex justify-center">
              <div className="w-fit">
                <div className="flex gap-8 border-b border-transparent">
                  {/* Tabs */}
                  {[...appTypeList.map(item => item.value)].map((key, idx) => {
                    const label = key === '全部'
                      ? '全部'
                      : appTypeList.find(i => i.value === key)?.label || key;
                    const icon = key === '全部'
                      ? null
                      : label === '专业知识' ? <BookOutlined className="mr-1" />
                        : label === '职能管理' ? <TeamOutlined className="mr-1" />
                          : label === '项目级应用' ? <AppstoreOutlined className="mr-1" />
                            : null;
                    const selected = selectedType === key;
                    return (
                      <button
                        key={key}
                        type="button"
                        className={`px-6 py-2 text-base font-medium flex items-center justify-center transition-colors duration-200 relative bg-transparent border-none outline-none ${selected ? 'text-blue-600' : 'text-gray-700'} `}
                        onClick={() => handleTabChange(key)}
                      >
                        {icon}
                        {label}
                        {selected && (
                          <span className="absolute left-0 right-0 -bottom-1 h-[3px] bg-blue-600 rounded-full" />
                        )}
                      </button>
                    );
                  })}
                </div>
              </div>
            </div>
          </FormItem>
        </Form>
      </div>
      <div className="app-plaza-list flex flex-col items-center justify-center">
        { (
          <>
            <div className="w-full px-8">
              <div className='overflow-hidden' style={{ height: 'calc(100vh - 155px)', width: '100%', display: 'flex', flexDirection: 'column', boxSizing: 'border-box' }}>
                {/* 列表滚动区 */}
                <div className='h-[calc(100%)] overflow-y-auto overflow-x-hidden px-30' style={{ flex: '1 1 auto' }}>
                  <List
                    style={{ padding: 0, margin: 0 }}
                    grid={{
                      gutter: 36,
                      xs: 1,
                      sm: 2,
                      md: 2,
                      lg: 3,
                      xl: 4,
                      xxl: 4,
                    }}
                    dataSource={list}
                    loading={listLoading}
                    renderItem={(item) => (
                      <List.Item style={{ padding: 0 }}>
                        <div key={item.appId} style={{ boxSizing: 'border-box', width: '100%', minWidth:'290px', padding: '16px 26px' }} className="bg-[#F0F8FF] rounded-xl shadow-md p-6 flex flex-col items-center relative">
                          {/* 1. 头像居中显示 */}
                          <div className="flex justify-center items-center mb-4 pt-2">
                            <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>
                            {/* 2. 名称+类型 */}
                            <div className="text-left mb-2 w-full">
                              <div className="font-bold text-[17px] text-gray-900 flex items-center justify-between" title={item.name}>
                                <Tooltip title={item.name}>
                                    <p className='truncate w-[68%]'>{item.name.length > 20 ? `${item.name.substring(0, 30)}...` : item.name}</p>
                                </Tooltip>
                                {item.groupVisible==='1'&&<p className='font-normal text-[10px]'> <GlobalOutlined /> 集团RAG应用 </p>}
                              </div>
                            </div>
                            {/* 3. 描述，两行高度，溢出省略 */}
                            <div className="w-full text-gray-700 text-[12px] mb-4 min-h-11 flex items-center">
                              <Tooltip title={item.desc || '暂无描述'}>
                                <div className="line-clamp-2 w-full" style={{ minHeight: 40 }}>
                                  {item.desc || '暂无描述'}
                                </div>
                              </Tooltip>
                            </div>
                            {/* 4. 底部按钮组 */}
                            <div className="w-full flex justify-between items-center mt-auto pt-2">
                              <Tag
                                style={{
                                  // padding: '4px 8px',
                                  marginRight: 0,
                                  fontSize: 12,
                                  fontWeight: 600,
                                  background: '#f8f8f8',
                                  // border: '1px solid #d9d9d9'
                                }}
                              >
                                {
                                  appTypeList
                                    .find(item1 => item1.dictCode.toString() === item.typeId)?.label || levelTypeList.find(item2 => item2.value.toString() === item.typeId)?.label || '未分类'
                                }
                              </Tag>
                                {item.isCollect && <Button size='small' icon={< HeartFilled style={{ color: '#F5E663' }} />} onClick={async () => {
                                if (item.isCollect) {
                                  const res: any = await apis.delCollectApi(item.appId);
                                  if (res.code === 200) {
                                    message.success('取消收藏成功')
                                    await appApi.fetchList(selectedType, null);
                                  }
                                }
                              }} >已收藏</Button>}
                              {!item.isCollect && <Button size='small' icon={<HeartOutlined />} onClick={async () => {
                                if (!item.isCollect) {
                                  const res: any = await apis.setCollectApi(item.appId);
                                  if (res.code === 200) {
                                    message.success('收藏成功')
                                    await appApi.fetchList(selectedType, null);
                                  }
                                }
                              }} >收藏</Button>}
                              <Button size="small" type="primary" className="font-medium" onClick={() => useNowAppLication(item.appId)}>
                                立即使用
                              </Button>
                            </div>
                          </div>
                      </List.Item>
                    )}
                  />
                </div>
                {/* 分页固定在底部 */}
                <div style={{ paddingTop: 16, display: 'flex', justifyContent: 'end' }}>
                  <Pagination {...paginationConfig} />
                </div>
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
};

export default observer(QuestionAnswerList);
