/* eslint-disable react/no-danger */
import {
  SearchOutlined,
} from '@ant-design/icons';
import {
  Affix,
  BackTop,
  Button,
  Divider,
  Input,
  Modal,
  Skeleton,
  Space,
  Table,
  Upload,
} from 'antd';
import React, { useEffect, useState } from 'react';
import { StickyContainer } from 'react-sticky';
import InfiniteScroll from 'react-infinite-scroll-component';
import './index.css';

import {
  queryRule,
} from './service';
import { queryAllCategory } from '../Case/Category/service';
import { ColumnsType } from 'antd/lib/table';
import { TableListItem } from '../Case/CasePage/data';
import { history } from 'umi';

const params = {
  pageNum: 1,
  pageSize: 20,
  param: '',
  categoryId: null
};

const Front: React.FC<{}> = () => {
  const [initLoading, setInitLoading] = useState<boolean>(false);
  const [isNoMore, setIsNoMore] = useState<boolean>(false);
  const [secondLevelList, setSecondLevelList] = useState<any[]>([]);
  const [data, setDataList] = useState<any[]>([]);
  const [curLevel2, setCurLevel2] = useState<string>('');
  const [param, setParam] = useState<string>(params.param);
  const [fileList, setFileList] = useState<any>();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const columns: ColumnsType<TableListItem> = [
    {
      title: '名称',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '文号版本',
      dataIndex: 'version',
      key: 'version',
      width: 88
    },
    {
      title: '类型',
      dataIndex: 'categoryName',
      width: 88,
      key: 'categoryName',
    },
    {
      title: '关键字',
      dataIndex: 'keywords',
      key: 'keywords'
    },
    {
      title: '级别',
      dataIndex: 'levelName',
      width: 88,
      key: 'levelName',
    },
    {
      title: '实施日期',
      dataIndex: 'implementationDate',
      width: 110,
      render: (text: string) => text ? text.substring(0,10) : ''
    },
    {
      title: '状态',
      dataIndex: 'currentStatus',
      key: 'currentStatus',
      width: 60,
      render: (text: number) => (text === 1 ? '现行' : '废止'),
    },
    {
      title: '附件',
      dataIndex: 'fileUrls',
      key: 'fileUrls',
      width: 88,
      render: (text: number, record: any) => {
        return <a onClick={(e) => {
          e.stopPropagation();
          showModal(record)
        }}>点击下载</a>
      },
    },
  ];

  const onLoadMore = () => {
    setInitLoading(true);
    params.pageNum += 1;
    queryRule(params).then((res) => {
      setInitLoading(false);
      if (res.retcode) {
        for (let i = 0; i < res.data.list.length; i++) {
          if (res.data.list[i].keywords && res.data.list[i].keywords.length > 30) { 
            res.data.list[i].keywords = res.data.list[i].keywords.substring(0, 30) + "...";  
          }
        }
        const arr = data.concat(...res.data.list);
        if (res.data.list.length < 20) {
          setIsNoMore(true);
        }
        setDataList(arr);
      }
    });
  };

  const fetchData = () => {
    params.pageNum = 1;
    setInitLoading(true);
    setIsNoMore(false);
    queryRule(params).then((res) => {
      setInitLoading(false);
      if (res.retcode) {
        const arr = res.data.list;
        if (res.data.list.length < 20) {
          setIsNoMore(true);
        }
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].keywords && arr[i].keywords.length > 30) { 
            arr[i].keywords = arr[i].keywords.substring(0, 30) + "...";  
          }
        }
        setDataList(arr);
      }
    });
  };

  const getLevel2List = async () => {
    const msg = await queryAllCategory();
    const arr = [
      {
        id: 0,
        categoryName: '全部',
      },
    ];
    if (msg.retcode) {
      arr.push(...msg.data || []);
    }
    setSecondLevelList(arr);
  };

  useEffect(() => {
    params.pageNum = 1;
    getLevel2List();
    fetchData();
  }, []);

  const showModal = (row: any) => {
    let arr: any = [];
    if (row.fileUrls) {
      arr = JSON.parse(row.fileUrls);
    }
    for (let i = 0; i < arr.length; i++) {
      const element = arr[i];
      console.log(element.url)
      arr[i].url = element.url.replace("http://dj-law.oss-cn-shanghai.aliyuncs.com", "http://47.92.229.12:8888/upload")
    }
    setFileList(arr)
    setIsModalOpen(true);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  return (
    <div style={{ minWidth: 1050, minHeight: '100vh', backgroundColor: '#f6f6f6' }}>
      <BackTop />
      <Affix offsetTop={0}>
        <div className="top-header-box">
          <div className="top-header">
            {/* <h2 style={{ margin: '0 30px 0 0', color: '#1890ff' }}>电力工程现行法律法规标准索引</h2> */}
            <Space size="large">
              <Input
                style={{ width: 482, height: 35, borderRadius: 100, backgroundColor: '#f6f6f6' }}
                suffix={<SearchOutlined style={{ fontSize: 18 }} onClick={() => fetchData()} />}
                defaultValue={param}
                value={param}
                onChange={(value) => {
                  setParam(value.currentTarget.value);
                  params.param = value.currentTarget.value;
                }}
                onPressEnter={(e) => {
                  params.param = e.currentTarget.value;
                  setParam(e.currentTarget.value);
                  fetchData();
                }}
                allowClear
              />
            </Space>
          </div>
        </div>
      </Affix>
      <StickyContainer>
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            width: 1050,
            margin: '0 auto',
          }}
        >
          <Affix offsetTop={62}>
            <div style={{ width: 120, textAlign: 'right' }}>
              {secondLevelList.map((item) => (
                <Button
                  style={{
                    borderRight:
                      item.id === (curLevel2 === '' ? 0 : curLevel2)
                        ? '3px solid #000'
                        : 'none',
                    color: '#000',
                  }}
                  type={item.id === (curLevel2 === '' ? 0 : curLevel2) ? 'link' : 'text'}
                  size="large"
                  key={item.id}
                  onClick={() => {
                    setCurLevel2(item.id);
                    params.categoryId = item.id || ''
                    fetchData();
                  }}
                >
                  {item.categoryName}
                </Button>
              ))}
            </div>
          </Affix>
          <div style={{ width: 890 }}>
            <InfiniteScroll
              dataLength={data.length}
              next={onLoadMore}
              hasMore={!isNoMore}
              loader={<Skeleton avatar paragraph={{ rows: 1 }} active />}
              endMessage={<Divider plain>已加载全部</Divider>}
              scrollThreshold="98%"
            >
              <Table
                tableLayout="fixed"
                size="large"
                rowKey="id"
                onRow={(record) => {
                  return {
                    onClick: (event) => {
                      history.push('/home/detail/'+record.id)
                    }, // 点击行
                  };
                }}
                pagination={false}
                loading={initLoading}
                dataSource={data}
                columns={columns}
              />
            </InfiniteScroll>
          </div>
        </div>
      </StickyContainer>
      <Modal title="下载附件" open={isModalOpen} footer={false} onCancel={handleCancel}>
        <div>
          <Upload
            action="#"
            // listType="picture-card"
            fileList={fileList}
            showUploadList={{showDownloadIcon: true, showRemoveIcon: false}}
          />
        </div>
      </Modal>
    </div>
  );
};

export default Front;
