import React, { useEffect, useState } from 'react';
import SearchBox 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 AddEditModalView from '~/pages/pilotTraining/courseCategory/comp/addEditModal';
import { InterDataType } from '~/api/interface';
import { selectCurriculumClassifyType } from '~/api/interface/pilotTrainType';
import { PilotTrainAPI } from '~/api';

// 列表类型
type ListType = Array<
  InterDataType<selectCurriculumClassifyType>[0] & {
    children?: InterDataType<selectCurriculumClassifyType>;
  }
>;

const CourseCategoryView: React.FC = () => {
  // 表格列表
  const [tableData, setTableData] = useState<ListType>([]);
  // 主分类是否打开变更弹窗
  const [isMainShow, setIsMainShow] = useState<boolean>(false);
  // 子分类是否打开变更弹窗
  const [isSecondShow, setIsSecondShow] = useState<boolean>(false);
  // 当前编辑的数据
  const [editData, setEditData] = useState<ListType[0]>();
  // 获取分类列表
  const getTableList = async () => {
    // 只需要修改这个地方的接口即可
    const res = await PilotTrainAPI.selectCurriculumClassify();
    if (res && res.code === '200') {
      const list = res.result
        ?.filter((i) => !i.twoCourseId)
        ?.map((i) => {
          const children = res.result?.filter(
            (k) => k.oneCourseId === i.oneCourseId && k.twoCourseId,
          );
          return {
            ...i,
            children: children?.length ? children : undefined,
          };
        });
      // console.log('列表 --->', list, res.result);
      setTableData(list);
    }
  };
  // 删除分类
  const handleDelete = (record: ListType[0]) => {
    Modal.confirm({
      title: '提示',
      content: '是否确认删除该分类？',
      onOk: async () => {
        const res = await PilotTrainAPI.removeCurriculumClassify({ id: record?.id });
        if (res && res.code === '200') {
          await getTableList();
          message.success('操作成功!');
        }
      },
    });
  };
  // 页面挂载
  useEffect(() => {
    getTableList().then();
  }, []);
  // 表格列
  const columns: ColumnsType<ListType[0]> = [
    {
      title: '序号',
      dataIndex: 'id',
      align: 'center',
      render: (_value, _record, index) => index + 1,
    },
    {
      title: '分类名称',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '图片',
      dataIndex: 'classifyUrl',
      align: 'center',
      render: (value, record) =>
        !record?.twoCourseId && <Image width={35} height={35} src={value} />,
    },
    {
      title: '描述',
      dataIndex: 'classifyDesc',
      align: 'center',
      ellipsis: true,
      width: '200px',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      fixed: 'right',
      render: (_value, record) => (
        <>
          {!record?.twoCourseId && (
            <Button
              type={'link'}
              onClick={() => {
                setEditData(record);
                setIsSecondShow(true);
              }}
            >
              新增子分类
            </Button>
          )}
          <Button
            type={'link'}
            onClick={() => {
              setEditData(record);
              if (!record?.twoCourseId) {
                setIsMainShow(true);
              } else {
                setIsSecondShow(true);
              }
            }}
          >
            编辑
          </Button>
          <Button type={'link'} danger onClick={() => handleDelete(record)}>
            删除
          </Button>
        </>
      ),
    },
  ];
  return (
    <>
      <SearchBox
        preFixBtn={
          <Button icon={<PlusOutlined />} type='primary' onClick={() => setIsMainShow(true)}>
            新增分类
          </Button>
        }
      />
      <Table
        size='small'
        dataSource={tableData}
        columns={columns}
        rowKey='id'
        bordered
        // 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} 条数据`,
        }}
      />
      {/*主分类添加编辑*/}
      <AddEditModalView
        open={isMainShow}
        title={editData?.id ? '编辑分类' : '新增分类'}
        data={editData}
        isSub={false}
        onCancel={() => {
          setEditData(undefined);
          setIsMainShow(false);
          getTableList().then();
        }}
      />
      {/*子分类添加编辑*/}
      <AddEditModalView
        open={isSecondShow}
        title={editData?.twoCourseId ? '编辑子分类' : '新增子分类'}
        data={editData}
        isSub={true}
        onCancel={() => {
          setEditData(undefined);
          setIsSecondShow(false);
          getTableList().then();
        }}
      />
    </>
  );
};

export default CourseCategoryView;
