import Global from '@/appConfig';
import darkcd from '@/assets/dark/application-two.png';
import badTwo from '@/assets/dark/bad-two-l.png';
import darkdz2 from '@/assets/dark/bad-two.png';
import darkfz from '@/assets/dark/bring-to-front.png';
import dxDarkLogo from '@/assets/dark/dx.png';
import goodTwo from '@/assets/dark/good-two-l.png';
import darkdz from '@/assets/dark/good-two.png';
import darkLogo from '@/assets/dark/logo.png';
import sendIcon from '@/assets/home/send.png';
import taiyang from '@/assets/home/taiyang.svg';
import upIcon from '@/assets/home/up.png';
import userLogo from '@/assets/home/user.png';
import yueliang from '@/assets/home/yueliang.svg';
import lightcd from '@/assets/light/application-two.png';
import lightdz2 from '@/assets/light/bad-two.png';
import lightfz from '@/assets/light/bring-to-front.png';
import dxLightLogo from '@/assets/light/dx.png';
import lightdz from '@/assets/light/good-two.png';
import lightLogo from '@/assets/light/logo.png';
import { getUuid } from '@/utils';
import {
  ConfigProvider,
  Dropdown,
  Image,
  Input,
  MenuProps,
  Spin,
  Switch,
  message,
} from 'antd';
import classNames from 'classnames';
import { useEffect, useState } from 'react';
import { menuList } from './data';
import styles from './index.less';

const { TextArea } = Input;

// 对话历史

const typeList = [
  {
    id: 1,
    name: '日常对话',
  },
  {
    id: 2,
    name: '公文撰写',
  },
];

const Home: React.FC = () => {
  const [hisDialogList, setHisDialogList] = useState<any[]>(); // 历史记录对话
  const [content, setContent] = useState<string>(); // 当前发送的问题
  const [active, setActive] = useState<number>(2);
  const [serachValue, setSerachValue] = useState<string>(''); // 历史搜索条件
  const [type, setType] = useState<any>(typeList[1]); // 对话类型
  const [mode, setMode] = useState<'dark' | 'light'>(); // 页面模式
  const [typeDisabled, setTypeDisabled] = useState<boolean>(false); // 对话类型是否可以切换
  const [curDialogue, setCurDialogue] = useState<any>(); // 当前对话
  const [btnLoading, setbtnLoading] = useState<boolean>(false);

  // 闲聊

  // 公文

  const onChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) => {
    setContent(e.target.value);
  };

  const items: MenuProps['items'] = typeList.map((item) => {
    return {
      label: (
        <div
          onClick={() => {
            setType(item);
          }}
        >
          {item.name}
        </div>
      ),
      key: item.id,
    };
  });

  /**
   * 获取公文写稿的搜索结果
   */
  const getSpecialtySearchValue = async () => {
    const resp = await fetch(
      // `http://136.6.202.47:8888/ai/aiFactoryServer/v1/apis/1/nlp-llm-digital-cq-baichuan2-service:1.0@alpha.fixed/LLM4Writing`,
      Global.Specialty,
      {
        method: 'post',
        headers: {
          'Content-Type': 'application/json; charset=UTF-8',
        },
        body: JSON.stringify({
          text_list_json: [
            {
              text_id: getUuid(),
              text: content,
            },
          ],
        }),
      },
    ).catch((error) => {
      console.error(error);
    });
    const { message, result } = (await resp?.json()) || { message: '' };
    if (message === 'success') {
      console.log('result', result);

      const dialogue = {
        id: getUuid(), // 唯一标识
        problem: content,
        rtnResult: result?.list[0]?.answer,
        feel: '', // 对话的感受
      };

      setTypeDisabled(true); // 当前会话有内容后就禁用切换
      // 如果是新开启的对话
      if (!curDialogue) {
        const curObj = {
          id: getUuid(), // 唯一标识
          type: type?.id, // 对话类型：闲聊 or 公文
          msgList: [dialogue], // 对话记录
        };
        // 写到对话历史
        setHisDialogList([curObj, ...(hisDialogList || [])]);
        // 写到当前对话
        setCurDialogue(curObj);
      } else {
        // 更新当前对话
        curDialogue?.msgList.unshift(dialogue);
        setCurDialogue(curDialogue);
        // 更新历史对话
        const newList = hisDialogList?.map((item: any) => {
          if (item?.id === curDialogue.id) {
            item.msgList = curDialogue?.msgList;
          }
          return item;
        });
        setHisDialogList(newList);
      }
      setContent('');
    } else {
      console.error('接口报错了');
    }
    setbtnLoading(false);
  };

  /**
   * 获取闲聊的搜索结果
   */
  const getLeisureSearchValue = async () => {
    const resp = await fetch(
      // `http://136.6.202.47:8888/ai/aiFactoryServer/v1/apis/1/nlp-llm-digital-cq-chat-service:1.0@alpha.fixed`,
      Global.LeisurePath,
      {
        method: 'post',
        headers: {
          'Content-Type': 'application/json; charset=UTF-8',
        },
        body: JSON.stringify({
          text_list_json: [
            {
              text_id: getUuid(),
              text: content,
              history:
                curDialogue?.msgList?.map((item: any) => item.problem) || [],
            },
          ],
        }),
      },
    ).catch((error) => {
      console.error(error);
    });
    const { message, result } = (await resp?.json()) || { message: '' };
    if (message === 'success') {
      const dialogue = {
        id: getUuid(), // 唯一标识
        problem: content,
        rtnResult: result?.list[0]?.answer,
        feel: '', // 对话的感受
      };

      setTypeDisabled(true); // 当前会话有内容后就禁用切换
      // 记录对话内容
      // 如果是新开启的对话
      if (!curDialogue) {
        const curObj = {
          id: getUuid(), // 唯一标识
          type: type?.id, // 对话类型：闲聊 or 公文
          msgList: [dialogue], // 对话记录
        };
        // 写到对话历史
        setHisDialogList([curObj, ...(hisDialogList || [])]);
        // 写到当前对话
        setCurDialogue(curObj);
      } else {
        // 更新当前对话
        curDialogue?.msgList.unshift(dialogue);
        setCurDialogue(curDialogue);
        // 更新历史对话
        const newList = hisDialogList?.map((item: any) => {
          if (item?.id === curDialogue.id) {
            item.msgList = curDialogue?.msgList;
          }
          return item;
        });
        setHisDialogList(newList);
      }
      setContent('');
    } else {
      console.error('接口报错了');
    }
    setbtnLoading(false);
  };

  /**
   * 发送问题
   */
  const send = () => {
    console.log('btnLoading', btnLoading);

    if (!btnLoading) {
      setbtnLoading(true);
      if (type?.id === 2) {
        getSpecialtySearchValue();
      } else {
        getLeisureSearchValue();
      }
    }
  };

  const switchModeHandler = (value: 'dark' | 'light') => {
    const doc = document.querySelector('body');
    if (doc) {
      doc.removeAttribute('class');
      doc.classList.add(value);
      setMode(value);
    }
  };
  /**
   * 风格切换
   */
  const onChangeStyle = (checked: boolean) => {
    if (checked) {
      switchModeHandler('light');
    } else {
      switchModeHandler('dark');
    }
  };

  /**
   * 复制到粘贴板
   */
  const onCopy = (value: string) => {
    navigator?.clipboard
      ?.writeText(value)
      ?.then(() => {
        message.info('复制成功！');
      })
      ?.catch(() => {
        message.info('复制失败！');
      });
  };

  /**
   * 更新当前点赞状态
   * @param feel
   * @param curResult
   */
  const onUploadFeel = (feel: string, curResult: any) => {
    // 更新当前对话的内容的感受
    const curList = curDialogue?.msgList?.map((item: any) => {
      if (item.id === curResult?.id) {
        item.feel = feel;
      }
      return item;
    });
    const curD = { ...curDialogue, msgList: curList };
    setCurDialogue(curD);
    // 同步更新到历史列表
    const list = hisDialogList?.map((item: any) => {
      if (item?.id === curD?.id) {
        item.msgList = curD.msgList;
      }
      return item;
    });
    setHisDialogList(list);
  };

  /**
   * 新建一个对话
   */
  const onAddDialogue = () => {
    // 清空当前内容
    setCurDialogue(undefined);
    // 放开切换
    setTypeDisabled(false);
    setContent('');
    setbtnLoading(false);
  };

  useEffect(() => {
    switchModeHandler('light');
  }, []);

  return (
    <div className={styles.container}>
      <div className={styles.sidebar}>
        <img
          className={styles.logo}
          src={mode === 'dark' ? darkLogo : lightLogo}
        />
        <div className={styles.addBtn} onClick={onAddDialogue}>
          新建对话
        </div>
        <ConfigProvider
          theme={{
            token: {
              lineWidth: 0,
              controlOutlineWidth: 0,
              fontSize: 16,
              colorBgContainer: 'transparent',
              colorPrimaryActive: 'transparent',
              colorPrimaryHover: 'transparent',
              colorText: mode === 'dark' ? '#fff' : 'rgba(0, 0, 0, 0.88)',
              colorTextPlaceholder:
                mode === 'dark'
                  ? 'rgba(255,255,255,.52)'
                  : 'rgba(0, 0, 0, 0.20)',
            },
            components: {
              Input: {
                activeBorderColor: 'transparent',
                hoverBorderColor: 'transparent',
                addonBg: 'transparent',
              },
            },
          }}
        >
          <Input
            addonBefore={<div className={styles.searchIcon} />}
            placeholder="历史搜索记录"
            onChange={(e) => {
              setSerachValue(e.target.value);
            }}
            style={{ borderBottom: '1px solid var(--search-borderColor)' }}
          />
        </ConfigProvider>
        <div className={styles.listBox}>
          {hisDialogList
            ?.filter((item) =>
              item?.msgList[
                item?.msgList?.length - 1 || 0
              ]?.rtnResult?.includes(serachValue),
            )
            ?.map((item: any) => (
              <div
                key={item.id}
                className={classNames(
                  styles.siderItem,
                  curDialogue?.id === item.id ? styles.active : '',
                )}
              >
                <div className={styles.con}>
                  {item?.msgList[item?.msgList?.length - 1 || 0]?.rtnResult}
                </div>
                <div
                  className={styles.editIcon}
                  onClick={() => {
                    if (item?.type === 1) {
                      // 如果是闲聊
                      setType(typeList[0]);
                    } else if (item?.type === 2) {
                      setType(typeList[1]);
                    }
                    setCurDialogue(item);
                  }}
                />
                <div
                  className={styles.delIcon}
                  onClick={() => {
                    setHisDialogList(
                      hisDialogList?.filter((i) => i.id !== item.id),
                    );
                    if (curDialogue?.id === item.id) {
                      setCurDialogue(undefined);
                    }
                  }}
                />
              </div>
            ))}
        </div>
      </div>
      <div className={styles.rightContent}>
        <div className={styles.content}>
          {curDialogue?.msgList?.map((item: any, index: number) => (
            <div key={index} className={styles.dialogItem}>
              <div className={styles.dialogText}>
                <div className={styles.textIcon}>
                  <img src={userLogo} />
                </div>
                <div className={styles.text}>{item.problem}</div>
              </div>
              <div className={styles.dialogReturn}>
                <div className={styles.returnIcon}>
                  <img src={mode === 'dark' ? dxDarkLogo : dxLightLogo} />
                </div>
                <div className={styles.return}>
                  <div className={styles.returnText}>
                    {item.rtnResult.split('\n\n').map((it: any, i: number) => {
                      return (
                        <p
                          key={i}
                          className={
                            i === 0 && type?.id === 2
                              ? styles.firstTitle
                              : styles.otherTitle
                          }
                        >
                          {it}
                          <br />
                        </p>
                      );
                    })}
                  </div>
                  <div className={styles.returnBtn}>
                    {item?.feel === 'good' && (
                      <img
                        onClick={() => {
                          onUploadFeel('', item);
                        }}
                        src={goodTwo}
                      />
                    )}
                    {(item?.feel === '' || item?.feel === 'bad') && (
                      <img
                        onClick={() => {
                          onUploadFeel('good', item);
                        }}
                        src={mode === 'dark' ? darkdz : lightdz}
                      />
                    )}
                    {/* <img src={mode === 'dark' ? darkdz : lightdz} /> */}
                    <img
                      title="复制到粘贴板"
                      src={mode === 'dark' ? darkfz : lightfz}
                      onClick={() => {
                        onCopy(item.rtnResult);
                      }}
                    />
                    {/* <img src={mode === 'dark' ? darkdz2 : lightdz2} /> */}
                    {item?.feel === 'bad' && (
                      <img
                        onClick={() => {
                          onUploadFeel('', item);
                        }}
                        src={badTwo}
                      />
                    )}
                    {(item?.feel === '' || item?.feel === 'good') && (
                      <img
                        onClick={() => {
                          onUploadFeel('bad', item);
                        }}
                        src={mode === 'dark' ? darkdz2 : lightdz2}
                      />
                    )}
                    <img src={mode === 'dark' ? darkcd : lightcd} />
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
        <div className={styles.footer}>
          <div className={styles.footerMenu}>
            <div className={styles.menuBox}>
              {menuList.map((item: any) => (
                <div
                  key={item.id}
                  className={classNames(
                    styles.menu,
                    active === item.id ? styles.active : '',
                  )}
                  onClick={() => {
                    setActive(item.id);
                  }}
                >
                  <div className={styles.name}>{item.name}</div>
                  <div className={styles.icon}>
                    {mode === 'dark' ? (
                      <img
                        src={
                          active === item.id
                            ? item.darkIconActive
                            : item.darkIcon
                        }
                      />
                    ) : (
                      <img
                        src={
                          active === item.id
                            ? item.lightIconActive
                            : item.lightIcon
                        }
                      />
                    )}
                  </div>
                </div>
              ))}
            </div>
            <ConfigProvider
              theme={{
                token: {
                  controlItemBgActive: mode === 'dark' ? '#31323E' : '#D7EAFF',
                  controlItemBgActiveHover:
                    mode === 'dark' ? '#31323E' : '#D7EAFF',
                  controlItemBgHover: mode === 'dark' ? '#31323E' : '#D7EAFF',
                  colorText: mode === 'dark' ? '#616161' : '#A4B5D0',
                  colorBgElevated: mode === 'dark' ? '#1E1E26' : '#fff',
                  boxShadowSecondary:
                    mode === 'dark'
                      ? '0px 0px 20px 0px #15161B'
                      : '0px 0px 16px 0px #CBE7FF',
                },
              }}
            >
              <Dropdown
                menu={{ items }}
                disabled={typeDisabled}
                placement="topRight"
              >
                <div className={styles.type}>
                  <span>{type?.name}</span>
                  <img src={upIcon} />
                </div>
              </Dropdown>
            </ConfigProvider>
          </div>
          <ConfigProvider
            theme={{
              token: {
                colorText: mode === 'dark' ? '#fff' : 'rgba(0, 0, 0, 0.88)',
                colorTextPlaceholder: mode === 'dark' ? '#999AAA' : '#C6CFDB',
                colorBgContainer: 'transparent',
              },
            }}
          >
            <TextArea
              placeholder="请输入问题或“”获取收藏指令，可通过shift+ 回车换行"
              allowClear
              onChange={onChange}
              value={content}
              autoSize={{ minRows: 3, maxRows: 15 }}
              style={{
                paddingBottom: '10px',
                borderColor: mode === 'dark' ? '#727491' : 'transparent',
                background: mode === 'dark' ? '#31323E' : '#fff',
                boxShadow:
                  mode === 'dark'
                    ? 'none'
                    : '0px 0px 16px 0px rgba(203, 231, 255, 0.60)',
                borderRadius: '12px',
                padding: '12px 12px 54px 12px',
              }}
            />
          </ConfigProvider>

          <div className={styles.send} onClick={send}>
            <Spin spinning={btnLoading}>
              <span>发送</span>
              <img src={sendIcon} />
            </Spin>
          </div>
        </div>
      </div>
      <div
        className={classNames(
          mode === 'dark' ? styles.pageNameDark : styles.pageNameBright,
          styles.pageNameBasics,
        )}
      >
        数字重庆大模型
      </div>
      <Switch
        className={styles.switchStyle}
        onChange={onChangeStyle}
        checkedChildren={<Image src={taiyang} width={15} />}
        unCheckedChildren={<Image src={yueliang} width={15} />}
        defaultChecked
      />
    </div>
  );
};

export default Home;
