import { useEffect, useState } from 'react';
import SearchBox from '~/components/search-box';
import { Button, Table, Image, message, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { queryCurriculumInfoListType } from '~/api/interface/mallManageType';
import { InterListType, InterReqType } from '~/api/interface';
import { MallManageAPI } from '~/api';
import { ColumnsType } from 'antd/es/table';
import AddEditModal from './comp/addEditModal';

// 表格数据类型
type TableType = InterListType<queryCurriculumInfoListType>;
// 请求数据的类型
type ReqType = InterReqType<queryCurriculumInfoListType>;
// 搜索表单的数据
let query: ReqType = {};

const CourseManageView = () => {
  const { confirm } = Modal;
  // 是否打开变更弹窗
  const [isAddEditVisModal, setIsAddEditVisModal] = useState<boolean>(false);
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  // 需要编辑的数据
  const [editData, setEditData] = useState<TableType[0]>();
  // 加载列表
  const getTableList = async (value = {}) => {
    // 只需要修改这个地方的接口即可
    const res = await MallManageAPI.queryCurriculumInfoList({
      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);
      // console.log('加载列表 --->', list);
    }
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getTableList({ pageNo, pageSize }).then();
  };
  // 表单提交
  const onFinish = (data: ReqType) => {
    pagination.current = 1;
    query = data;
    getTableList(data).then();
  };
  // 删除数据
  const handleDelete = (value: TableType[0]) => {
    confirm({
      title: '提示',
      content: '是否删除该课程？',
      onOk: async () => {
        const res = await MallManageAPI.removeCurriculum({ id: value.id });
        if (res && res.code === '200') {
          message.success('删除成功');
          paginationChange(
            tableData.length === 1 ? pagination.current - 1 : pagination.current,
            pagination.pageSize,
          );
        }
      },
    });
  };
  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '课程名称',
      dataIndex: 'curriculumName',
      align: 'center',
      width: '150px',
    },
    {
      title: '课程类型',
      dataIndex: 'flightSkillsName1',
      align: 'center',
      width: '150px',
      render: (text, record) => `${text}/${record.flightSkillsName2}`,
    },
    {
      title: '课程类型',
      dataIndex: 'curriculumDesc',
      align: 'center',
      width: '150px',
      ellipsis: true,
    },
    {
      title: '封面图',
      dataIndex: 'surfaceUrl',
      align: 'center',
      width: '150px',
      render: (text, record) => (
        <>
          <Image
            src={text ? text : `${record.videoUrl}?x-oss-process=video/snapshot,t_1000,m_fast`}
            alt={'封面图'}
            style={{ width: '35px', height: '35px' }}
          />
        </>
      ),
    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      fixed: 'right',
      width: '100px',
      render: (_text, record) => (
        <>
          <Button
            type={'link'}
            onClick={() => {
              setEditData(JSON.parse(JSON.stringify(record)));
              setIsAddEditVisModal(true);
            }}
          >
            编辑
          </Button>
          <Button type={'link'} danger onClick={() => handleDelete(record)}>
            删除
          </Button>
        </>
      ),
    },
  ];
  // componentDidMount
  useEffect(() => {
    query = {};
    (async () => {
      await getTableList();
    })();
  }, []);
  return (
    <>
      <SearchBox
        search={[
          {
            label: '课程名称',
            name: 'keyword',
            type: 'input',
            placeholder: '请输入课程名称',
          },
          {
            label: '课程类型',
            name: 'companyAuthStatus',
            type: 'Select',
            placeholder: '请选择是否认证',
            options: [
              { value: 0, label: '未认证' },
              { value: 1, label: '已认证' },
            ],
          },
        ]}
        searchData={onFinish}
        child={
          <>
            <Button
              type={'primary'}
              icon={<PlusOutlined />}
              onClick={() => {
                setIsAddEditVisModal(true);
              }}
            >
              新建课程
            </Button>
          </>
        }
      />
      <Table
        size='small'
        dataSource={tableData}
        columns={columns}
        rowKey='id'
        // scroll={{ x: 1200 }}
        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} 条数据`,
        }}
        // rowSelection={{ selectedRowKeys, onChange: onSelectChange }}
      />
      <AddEditModal
        open={isAddEditVisModal}
        closed={() => {
          setEditData(undefined);
          setIsAddEditVisModal(false);
          paginationChange(pagination.current, pagination.pageSize);
        }}
        data={editData}
        title={editData?.id ? '编辑' : '新增'}
      />
    </>
  );
};

export default CourseManageView;
