import React, { useState, useEffect } from 'react';
import styles from './style/engineering.module.less';
import { Input, Grid, Card, Result, Pagination, Message } from '@arco-design/web-react';
import { IconPlus, IconApps } from '@arco-design/web-react/icon';
import { openWindow, OpenWindowOptions } from '@/utils/common';
import { getPublicSceneList, getMySceneList, deleteScene } from '@/api/scene';
import CardWrap from '@/pages/scene/cardWrap';
import OperationModal from '@/pages/scene/operationModal';

const InputSearch = Input.Search;
const Row = Grid.Row;
const Col = Grid.Col;

interface EngineeringProps {
  dataType: 'my' | 'public',
  showAdd?: boolean,
}

const DEFAULT_PAGE_SIZE = 11;

const Engineering: React.FC<EngineeringProps> = ({ dataType, showAdd = true }) => {
  const [searchValue, setSearchValue] = useState<string>('');
  const [sceneData, setSceneData] = useState({
    list: [],
    totalCount: 0
  });
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(DEFAULT_PAGE_SIZE);
  const [showModal, setShowModal] = useState(false);
  const [operationType, setOperationType] = useState('ADD');
  const [currentItem, setCurrentItem] = useState(null);

  const onSearchHandle = (value: string) => {
    // 搜索时重置到第一页
    setCurrentPage(1);
    fetchData(1, pageSize, value);
  };

  const handleChange = (value: string) => {
    setSearchValue(value);
  };

  const openEngineHandle = (item) => {
    const url = `/ideContainer`;
    const params: OpenWindowOptions = {
      target: '_blank',
      menu: false,
      identity: 'scene',
      id: item.id,
      dataType
    };
    openWindow(url, params);
  };

  const openModalHandle = (type: string, item: any = null) => {
    setShowModal(true);
    setOperationType(type);
    setCurrentItem(item);
  };

  const handleEdit = (item, e) => {
    e.stopPropagation();
    openModalHandle('EDIT', item);
  };

  const handleDelete = async (item, e) => {
    e.stopPropagation();
    const { code }: any = await deleteScene(item.id);
    if (code === 200) {
      Message.success('删除成功');
      fetchData(1, pageSize);
    }
  };

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    fetchData(page, pageSize, searchValue);
  };

  const handlePageSizeChange = (size: number) => {
    setPageSize(size);
    setCurrentPage(1); // 重置到第一页
    fetchData(1, size, searchValue);
  };

  const fetchData = async (page: number = currentPage, size: number = pageSize, search: string = searchValue) => {
    const functions = {
      public: getPublicSceneList,
      my: getMySceneList
    };
    const params = {
      currPage: page,
      pageSize: size,
      name: search
    };
    const res: any = await functions[dataType](params);
    if (res.code === 200) {
      const { data } = res;
      setSceneData({
        list: data.list || [],
        totalCount: data.totalCount || 0
      });
    }
  };

  useEffect(() => {
    setCurrentPage(1);
    fetchData(1, pageSize, searchValue);
  }, [dataType]);

  return (
    <>
      <div className={styles['engineering-container']}>
        {/*搜索*/}
        <Row>
          <Col span={24}>
            <InputSearch
              allowClear
              searchButton="搜索"
              defaultValue=""
              placeholder="输入需要搜索的工程名称"
              style={{ width: 350, marginBottom: 15 }}
              onChange={handleChange}
              onSearch={onSearchHandle}
              value={searchValue}
            />
          </Col>
        </Row>
        {/*卡片模式数据渲染*/}
        <Row style={{ marginBottom: 10 }}>
          <Col
            xs={12}
            sm={12}
            md={12}
            lg={6}
            xl={6}
            xxl={6}>
            {/*新建工程按钮*/}
            {showAdd && (
              <Card
                className={styles['card-style']}
                onClick={() => openModalHandle('ADD')}
              >
                <Result
                  status="info"
                  subTitle={'新建工程'}
                  icon={<IconPlus />}
                ></Result>
              </Card>
            )}
          </Col>
          {/*遍历生成卡片*/}
          {sceneData.list.map((item, index) => (
            <Col
              key={item.id}
              xs={12}
              sm={12}
              md={12}
              lg={6}
              xl={6}
              xxl={6}>
              <Card className={styles['card-style']} hoverable>
                <CardWrap
                  item={item}
                  onEdit={handleEdit}
                  onDelete={handleDelete}
                  onClick={openEngineHandle}
                ></CardWrap>
              </Card>
            </Col>
          ))}
        </Row>
        {/*分页组件*/}
        <Row>
          <Col>
            <Pagination
              style={{ float: 'right' }}
              total={sceneData.totalCount}
              current={currentPage}
              pageSize={pageSize}
              showTotal
              onChange={handlePageChange}
              onPageSizeChange={handlePageSizeChange}
            />
          </Col>
        </Row>
      </div>
      {/*新增/编辑弹窗*/}
      <OperationModal
        show={showModal}
        type={operationType}
        item={currentItem}
        onClose={(status) => setShowModal(status)}
        onRefresh={() => fetchData(1, pageSize)}
      />
    </>
  );
};

export default Engineering;