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 { InterDataType, InterListType, InterReqType } from '~/api/interface';
import { MallManageAPI, PilotTrainAPI } from '~/api';
import { ColumnsType } from 'antd/es/table';
import AddEditModal from './comp/addEditModal';
import { selectCurriculumClassifyType } from '~/api/interface/pilotTrainType';

// 表格数据类型
type TableType = InterListType<queryCurriculumInfoListType>;
// 请求数据的类型
type ReqType = InterReqType<queryCurriculumInfoListType>;
// 列表类型
type ListType = Array<
  InterDataType<selectCurriculumClassifyType>[0] & {
    children?: InterDataType<selectCurriculumClassifyType>;
  }
>;
// 课程类型列表
const courseAttributeList = [
  { label: '免费', value: 0 },
  { label: '积分兑换', value: 1 },
  { label: '付费', value: 2 },
];
// 搜索表单的数据
let query: ReqType = {};

const CourseManageView = () => {
  // 分类列表
  const [curriculumClassifyList, setCurriculumClassifyList] = useState<ListType>();
  // 是否打开变更弹窗
  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]) => {
    Modal.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 getCurriculumClassify = 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,
          };
        });
      setCurriculumClassifyList(list);
    }
  };
  // 搜索数据
  const handleSearch = (value: ReqType & { courseId: number[] }) => {
    const oneCourseId = curriculumClassifyList?.find((i) => i.id === value?.courseId?.[0]);
    const twoCourseId = oneCourseId?.children?.find((i) => i.id === value?.courseId?.[1]);
    onFinish({
      ...value,
      oneCourseId: oneCourseId?.oneCourseId,
      twoCourseId: twoCourseId?.twoCourseId,
    });
  };
  // 获取当前课程的类型
  const getCurriculumType = (value: TableType[0]) => {
    const oneCourseId = curriculumClassifyList?.find((i) => i.oneCourseId === value?.oneCourseId);
    const twoCourseId = oneCourseId?.children?.find((i) => i.twoCourseId === value?.twoCourseId);
    return twoCourseId?.name ? `${oneCourseId?.name}/${twoCourseId?.name}` : `${oneCourseId?.name}`;
  };
  // componentDidMount
  useEffect(() => {
    query = {};
    (async () => {
      await getCurriculumClassify();
      await getTableList();
    })();
  }, []);
  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '课程名称',
      dataIndex: 'curriculumName',
      align: 'center',
      width: '150px',
    },
    {
      title: '课程类型',
      dataIndex: 'oneCourseId',
      align: 'center',
      width: '150px',
      render: (_text, record) => getCurriculumType(record),
    },
    {
      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: 'isHot',
      align: 'center',
      width: '50px',
      render: (text) => (text === 1 ? '是' : '否'),
    },
    {
      title: '课程属性',
      dataIndex: 'courseAttribute',
      align: 'center',
      width: '50px',
      render: (text) => courseAttributeList?.find((i) => i.value === text)?.label || '免费',
    },
    {
      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>
        </>
      ),
    },
  ];
  return (
    <>
      <SearchBox
        search={[
          {
            label: '课程名称',
            name: 'curriculumName',
            type: 'input',
            placeholder: '请输入课程名称',
          },
          {
            label: '课程类型',
            name: 'courseId',
            type: 'Cascader',
            placeholder: '请选择课程类型',
            options: curriculumClassifyList,
            fieldNames: { label: 'name', value: 'id' },
          },
          {
            label: '课程属性',
            name: 'courseAttribute',
            type: 'Select',
            placeholder: '请选择课程属性',
            options: courseAttributeList,
          },
        ]}
        searchData={handleSearch}
        child={
          <>
            <Button
              type={'primary'}
              icon={<PlusOutlined />}
              onClick={() => {
                setIsAddEditVisModal(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} 条数据`,
        }}
      />
      <AddEditModal
        open={isAddEditVisModal}
        closed={() => {
          setEditData(undefined);
          setIsAddEditVisModal(false);
          paginationChange(pagination.current, pagination.pageSize);
        }}
        data={editData}
        title={editData?.id ? '编辑' : '新增'}
      />
    </>
  );
};

export default CourseManageView;
