import SearchBox, { searchColumns } from '~/components/search-box';
import { Button, Image, message, Modal, Table } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import AddOrEditNewsModal from './components/addOrEditNewsModal';
import PreviewNewsModal from './components/previewNewsModal';
import { useEffect, useState } from 'react';
import { ResourceManageAPI } from '~/api';
import { InterDataType, InterReqListType, PaginationProps } from '~/api/interface';
import { industryNewsListType } from '~/api/interface/resourceManageType';

//行业新闻返回类型
type industryNewsType = InterDataType<industryNewsListType>['list'];
//行业新闻列表参数类型
type industryNewsParameters = InterReqListType<industryNewsListType>;

const IndustryNews = () => {
  const searchColumnsData: searchColumns[] = [
    {
      label: '文章名称',
      type: 'input',
      name: 'newsTitle',
      placeholder: '请输入文章名称',
    },
  ];
  const tableColumns: ColumnsType<industryNewsType[0]> = [
    {
      title: '序号',
      align: 'center',
      render: (_text: string, _record, index: number) =>
        (pagination.pageNo - 1) * pagination.pageSize + index + 1,
    },
    {
      title: '文章名称',
      align: 'center',
      dataIndex: 'newsTitle',
      width: '20%',
    },
    {
      title: '发布时间',
      align: 'center',
      dataIndex: 'createTime',
      width: '15%',
    },
    {
      title: '来源',
      align: 'center',
      dataIndex: 'origin',
    },
    {
      title: '作者',
      align: 'center',
      dataIndex: 'newsAuthor',
    },
    {
      title: '封图片',
      align: 'center',
      dataIndex: 'surfaceImg',
      render: (text: string) => <Image src={text} width={50} height={50} />,
    },
    {
      title: '操作',
      align: 'center',
      width: '20%',
      render: (_text: string, record) => (
        <>
          <Button type='link' onClick={() => addOrEditIndustryNewsClick(record)}>
            编辑
          </Button>
          <Button type='link' onClick={() => previewClick(record)}>
            预览
          </Button>
          <Button type='link' danger onClick={() => deleteIndustryNews(record)}>
            删除
          </Button>
        </>
      ),
    },
  ];
  const [tableData, setTableData] = useState<industryNewsType>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [currentIndustryNews, setCurrentIndustryNews] = useState<industryNewsType[0]>();
  const [addOrEditNewsModalShow, setAddOrEditNewsModalShow] = useState<boolean>(false);
  const [previewNewsModalShow, setPreviewNewsModalShow] = useState<boolean>(false);
  const [query, setQuery] = useState<industryNewsParameters>();
  const [pagination, setPagination] = useState<PaginationProps & { totalCount: number }>({
    pageNo: 1,
    pageSize: 10,
    totalCount: 0,
  });

  //获取行业新闻-列表
  const getIndustryNewsList = (query?: industryNewsParameters) => {
    setLoading(true);
    ResourceManageAPI.getIndustryNewsList({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      ...query,
    }).then(({ result }) => {
      setLoading(false);
      setTableData(result.list || []);
      pagination.totalCount = result.totalCount;
      setPagination(pagination);
    });
  };
  //分页
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    getIndustryNewsList(query);
  };
  //筛选
  const searchSuccessEvent = (value?: industryNewsParameters) => {
    pagination.pageNo = 1;
    pagination.pageSize = 10;
    setQuery(value);
    getIndustryNewsList(value);
  };
  //新增、编辑
  const addOrEditIndustryNewsClick = (record?: industryNewsType[0]) => {
    setCurrentIndustryNews(record ? { ...record } : undefined);
    setAddOrEditNewsModalShow(true);
  };
  const addOrEditNewsModalCancel = () => {
    setAddOrEditNewsModalShow(false);
  };
  const addOrEditNewsModalOk = () => {
    getIndustryNewsList();
    setAddOrEditNewsModalShow(false);
  };
  //预览
  const previewClick = (record: industryNewsType[0]) => {
    setCurrentIndustryNews({ ...record });
    setPreviewNewsModalShow(true);
  };
  const previewNewsModalCancel = () => {
    setPreviewNewsModalShow(false);
  };
  //删除
  const deleteIndustryNews = (record: industryNewsType[0]) => {
    Modal.confirm({
      title: '行业新闻删除',
      content: '确认删除该行业新闻?',
      onOk: () => {
        ResourceManageAPI.removeIndustryNews({ id: record.id }).then(({ code }) => {
          if (code === '200') {
            message.success('删除成功');
            if (pagination.pageNo !== 1 && tableData.length === 1) {
              pagination.pageNo -= 1;
            }
            getIndustryNewsList(query);
          }
        });
      },
    });
  };
  useEffect(() => {
    getIndustryNewsList();
  }, []);
  return (
    <div className='industry-news'>
      <SearchBox
        search={searchColumnsData}
        child={
          <Button
            type='primary'
            icon={<PlusOutlined />}
            onClick={() => addOrEditIndustryNewsClick()}
          >
            新建
          </Button>
        }
        searchData={searchSuccessEvent}
      />
      <Table
        bordered
        columns={tableColumns}
        dataSource={tableData}
        loading={loading}
        rowKey='id'
        pagination={{
          total: pagination.totalCount,
          pageSize: pagination.pageSize,
          current: pagination.pageNo,
          showSizeChanger: true,
          showQuickJumper: true,
          onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
          showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
        }}
      />
      <AddOrEditNewsModal
        open={addOrEditNewsModalShow}
        onCancel={addOrEditNewsModalCancel}
        handleOk={addOrEditNewsModalOk}
        currentIndustryNews={currentIndustryNews}
      />
      <PreviewNewsModal
        open={previewNewsModalShow}
        onCancel={previewNewsModalCancel}
        currentIndustryNews={currentIndustryNews}
      />
    </div>
  );
};
export default IndustryNews;
