import { useEffect, useState } from 'react';
import SearchBox from '~/components/search-box';
import { Button, message, Modal, Table } from 'antd';
import { PlusOutlined, DownloadOutlined } from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import { ResourceManageAPI } from '~/api';
import { InterListType, InterReqListType } from '~/api/interface';
import { releaseTenderNews } from '~/api/interface/resourceManageType';
import AddEditModal from './comp/addEditModal';
import qs from 'query-string';
import { useNavigate } from 'react-router-dom';
import saveAs from 'file-saver';
// 列表类型
type TableType = InterListType<releaseTenderNews>;
// 请求的参数
type ReqType = InterReqListType<releaseTenderNews>;
// 搜索表单的数据
let query: ReqType = {};

const TenderManageView = () => {
  const { confirm } = Modal;
  // 路由钩子
  const navigate = useNavigate();
  // 新增弹窗
  const [addModalVisible, setAddModalVisible] = useState<boolean>(false);
  // 需要编辑的数据
  const [editData, setEditData] = useState<TableType[0]>();
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 加载列表
  const getTableList = async (value = {}) => {
    // 只需要修改这个地方的接口即可
    const res = await ResourceManageAPI.releaseTenderNews({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...value,
      ...query,
    });
    if (res && res.code === '200') {
      const { list, pageNo, totalCount, pageSize, totalPage } = res.result; // 解构
      setPagination({
        total: totalCount,
        current: pageNo,
        pageSize,
        totalPage,
      });
      setTableData(list);
    }
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getTableList({ pageNo, pageSize }).then();
  };
  // 表单提交
  const onFinish = (data: ReqType & { rangeTime: string[] }) => {
    pagination.current = 1;
    query = {
      startTime: data.rangeTime ? data.rangeTime[0] : undefined,
      endTime: data.rangeTime ? data.rangeTime[1] : undefined,
      tenderName: data.tenderName,
      using: data.using,
    };
    getTableList(query).then();
  };
  // 删除数据
  const handleDelete = (record: TableType[0]) => {
    confirm({
      title: '提示',
      content: '是否删除该记录？',
      onOk: async () => {
        const res = await ResourceManageAPI.releaseTenderNewsDelete({ id: record.id });
        if (res && res.code === '200') {
          message.success('删除成功');
          paginationChange(
            tableData.length === 1 ? pagination.current - 1 : pagination.current,
            pagination.pageSize,
          );
        }
      },
    });
  };
  // 跳转详情
  const handleDetail = (record: TableType[0]) => {
    const search = {
      id: record.id,
    };
    navigate(`/resourceManage/tenderManage/detail?${qs.stringify(search)}`);
  };
  // 跳转反馈
  const handleFeedback = (record: TableType[0]) => {
    const search = {
      id: record.id,
    };
    navigate(`/resourceManage/tenderManage/feedback?${qs.stringify(search)}`);
  };
  // componentDidMount
  useEffect(() => {
    query = {};
    getTableList().then();
  }, []);
  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '招标快讯名称',
      dataIndex: 'tenderName',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '发布时间',
      dataIndex: 'createTime',
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'using',
      align: 'center',
      render: (text) => (text === 1 ? '上架' : '下架'),
    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      width: '200px',
      fixed: 'right',
      render: (_text, record) => (
        <>
          <Button type={'link'} onClick={() => handleDetail(record)}>
            详情
          </Button>
          <Button
            type={'link'}
            onClick={() => {
              setEditData(JSON.parse(JSON.stringify(record)));
              setAddModalVisible(true);
            }}
          >
            编辑
          </Button>
          <Button type={'link'} onClick={() => handleFeedback(record)}>
            用户反馈
          </Button>
          <Button type={'link'} danger onClick={() => handleDelete(record)}>
            删除
          </Button>
        </>
      ),
    },
  ];
  return (
    <>
      <SearchBox
        search={[
          { name: 'tenderName', label: '名称', type: 'input', placeholder: '请输入招标快讯名称' },
          {
            name: 'rangeTime',
            label: '发布时间',
            type: 'rangePicker',
            placeholder: '请选择开始时间和结束时间',
          },
        ]}
        searchData={onFinish}
        child={
          <>
            <Button
              type={'primary'}
              icon={<PlusOutlined />}
              onClick={() => {
                setAddModalVisible(true);
              }}
            >
              新增
            </Button>
          </>
        }
        otherChild={
          <>
            <Button
              type={'primary'}
              icon={<DownloadOutlined />}
              onClick={() => {
                saveAs(
                  'https://pad-video-x.oss-cn-shenzhen.aliyuncs.com/doc/tender-news-template.xlsx',
                  `招标快讯模板_${new Date().getTime()}.xlsx`,
                );
              }}
            >
              下载模板
            </Button>
          </>
        }
      />
      <Table
        size='small'
        dataSource={tableData}
        columns={columns}
        rowKey='id'
        // scroll={{ x: 1500 }}
        bordered
        pagination={{
          total: pagination.total,
          pageSize: pagination.pageSize,
          current: pagination.current,
          showSizeChanger: true,
          showQuickJumper: true,
          onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
          showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
        }}
      />
      <AddEditModal
        open={addModalVisible}
        title={editData?.id ? '编辑' : '新增'}
        data={editData}
        closed={() => {
          setAddModalVisible(false);
          setEditData(undefined);
          paginationChange(pagination.current, pagination.pageSize);
        }}
      />
    </>
  );
};

export default TenderManageView;
