import {
  DeleteOutlined,
  EditFilled,
  EditOutlined,
  FieldTimeOutlined,
  FileAddOutlined,
  InfoCircleOutlined,
} from "@ant-design/icons";
import {
  Button,
  Card,
  DatePicker,
  Image,
  Input,
  Popconfirm,
  Space,
  Switch,
  Table,
  Modal,
  Tooltip,
  Form,
} from "antd";
import dayjs, { Dayjs } from "dayjs";
import { useEffect, useState } from "react";
import {
  removeCourse,
  selectChapterList,
  selectCourseList,
  updateChapter,
  updateCourse,
  createChapter,
  removeChapter,
} from "../../../api";
import { IChapter } from "../../../api/dto";
import { useMount } from "../../../hooks";
import "./index.less";

interface IEditItem {
  key: string;
  value: string | boolean | number;
}

const defaultEditItem = { key: "", value: "" };

export default function List() {
  const [courseList, setCourseList] = useState<any>([]);
  const [chapterList, setChapterList] = useState([]);
  const [editChapterItem, setEditChapterItem] =
    useState<IEditItem>(defaultEditItem);
  const [editCourseItem, setEditCourseItem] =
    useState<IEditItem>(defaultEditItem);
  const [addChapterForm] = Form.useForm();

  const onConfirmEditCourseItem = (record: any) => {
    const { key, value } = editCourseItem;
    updateCourse({ ...record, [key]: value }).then((res: any) => {
      if (res?.code === 10000) {
        renderCourseTable();
        setEditCourseItem(defaultEditItem);
      }
    });
  };

  const onConfirmEditChapterItem = (record: any) => {
    const { key, value } = editChapterItem;
    updateChapter({ ...record, [key]: value }).then((res: any) => {
      if (res?.code === 10000) {
        const { chapter_course_id } = record;
        renderChapterList(chapter_course_id);
        setEditChapterItem(defaultEditItem);
      }
    });
  };

  const onConfirmDeleteCourseItem = (record: any) => {
    const { course_id } = record;
    removeCourse({ course_id }).then((res: any) => {
      if (res?.code === 10000) renderCourseTable();
    });
  };

  const onAddChapter = (record: any) => {
    const { course_id: chapter_course_id } = record;
    Modal.info({
      title: "添加章节",
      icon: <InfoCircleOutlined />,
      content: (
        <Form form={addChapterForm}>
          <Form.Item name="chapterList">
            <Input.TextArea
              placeholder="级别 | 章节名 | 文件FileID"
              autoSize={{ minRows: 12, maxRows: 20 }}
            />
          </Form.Item>
        </Form>
      ),
      onOk: async () => {
        const origin = addChapterForm.getFieldValue("chapterList");
        const chapterList = origin
          .split("\n")
          .filter((i: string) => i.replace(/\s/, "").length > 0)
          .map((row: string) => {
            const [chapter_level, chapter_title, chapter_file_id] =
              row.split("|");
            return !chapter_file_id
              ? { chapter_level, chapter_title, chapter_course_id }
              : {
                  chapter_level,
                  chapter_title,
                  chapter_file_id,
                  chapter_course_id,
                };
          });
        createChapter(chapterList).then((res: any) => {
          if (res?.code === 10000) renderChapterList(chapter_course_id);
        });
      },
      okText: "确认",
      cancelText: "取消",
    });
  };

  const onConfirmDeleteChapterItem = (record: any) => {
    const { chapter_id, chapter_course_id } = record;
    removeChapter({ chapter_id }).then((res: any) => {
      if (res?.code === 10000) renderChapterList(chapter_course_id);
    });
  };

  const columns = [
    {
      title: "课程",
      dataIndex: "course_title",
      key: "course_title",
      render: (_: any, record: any) => {
        return (
          <Space>
            <span>{record.course_title}</span>
            <Popconfirm
              placement="top"
              title="修改课程标题"
              description={
                <Input
                  defaultValue={record.course_title}
                  onChange={(e: any) =>
                    setEditCourseItem({
                      key: "course_title",
                      value: e.target.value,
                    })
                  }
                />
              }
              onConfirm={() => onConfirmEditCourseItem(record)}
              okText="确定"
              cancelText="取消"
            >
              <Button type="text" icon={<EditFilled />} />
            </Popconfirm>
          </Space>
        );
      },
    },
    {
      title: "摘要",
      dataIndex: "course_summary",
      key: "course_summary",
      render: (_: any, record: any) => {
        return (
          <Space>
            <span>{record.course_summary}</span>
            <Popconfirm
              placement="top"
              title="修改摘要"
              description={
                <Input
                  defaultValue={record.course_summary}
                  onChange={(e: any) =>
                    setEditCourseItem({
                      key: "course_summary",
                      value: e.target.value,
                    })
                  }
                />
              }
              onConfirm={() => onConfirmEditCourseItem(record)}
              okText="确定"
              cancelText="取消"
            >
              <Button type="text" icon={<EditFilled />} />
            </Popconfirm>
          </Space>
        );
      },
    },
    {
      title: "创建时间",
      dataIndex: "course_createtime",
      key: "course_createtime",
      render: (_: any, record: any) => {
        return (
          <Space>
            <span>
              {dayjs(+record.course_createtime).format("YYYY-MM-DD HH:mm:ss")}
            </span>
            <Popconfirm
              placement="top"
              title="时间"
              description={
                <DatePicker
                  onChange={(date: any) => {
                    setEditCourseItem({
                      key: "course_createtime",
                      value: "" + new Date(date).getTime(),
                    });
                  }}
                  format="YYYY-MM-DD HH:mm:ss"
                  showTime={{ defaultValue: dayjs("00:00:00", "HH:mm:ss") }}
                />
              }
              onConfirm={() => onConfirmEditCourseItem(record)}
              okText="确定"
              cancelText="取消"
            >
              <Button type="text" icon={<FieldTimeOutlined />} />
            </Popconfirm>
          </Space>
        );
      },
    },
    {
      title: "封面",
      dataIndex: "course_cover_url",
      key: "course_cover_url",
      render: (_: any, record: any) => {
        return <Image width={120} src={record.course_cover_url} />;
      },
    },
    {
      title: "可见",
      dataIndex: "visible",
      key: "visible",
      render: (_: any, record: any) => {
        return (
          <Switch
            checkedChildren="开启"
            unCheckedChildren="关闭"
            defaultChecked={record.valid}
            onChange={(value: boolean) =>
              updateCourse({ ...record, valid: value }).then((res: any) => {
                if (res?.code === 10000) {
                  renderCourseTable();
                  setEditCourseItem(defaultEditItem);
                }
              })
            }
          />
        );
      },
    },
    {
      title: "操作",
      dataIndex: "operation",
      key: "operation",
      render: (_: any, record: any) => {
        return (
          <Space>
            <Popconfirm
              placement="top"
              title="确定删除课程嘛"
              onConfirm={() => onConfirmDeleteCourseItem(record)}
              okText="确定"
              cancelText="取消"
            >
              <Button type="dashed" danger icon={<DeleteOutlined />}></Button>
            </Popconfirm>
            <Tooltip title="添加章节">
              <Button
                type="default"
                onClick={() => onAddChapter(record)}
                icon={<FileAddOutlined />}
              ></Button>
            </Tooltip>
          </Space>
        );
      },
    },
  ];

  useEffect(() => {}, [courseList]);

  const renderCourseTable = () => {
    selectCourseList({ all: true }).then((res) => {
      const { data } = res;
      setCourseList(data.map((i: any) => ({ ...i, key: i.course_id })));
    });
  };

  useMount(() => {
    renderCourseTable();
  });

  const expandedRowRender = () => {
    const col: any = [
      {
        title: "级别",
        dataIndex: "chapter_level",
        key: "chapter_level",
        render: (_: any, record: any) => {
          return (
            <Space>
              <span>{record.chapter_level}</span>
              <Popconfirm
                placement="top"
                title="修改级别"
                description={
                  <Input
                    defaultValue={record.chapter_level}
                    onChange={(e: any) =>
                      setEditChapterItem({
                        key: "chapter_level",
                        value: e.target.value,
                      })
                    }
                  />
                }
                onConfirm={() => onConfirmEditChapterItem(record)}
                okText="确定"
                cancelText="取消"
              >
                <Button type="text" icon={<EditOutlined />} />
              </Popconfirm>
            </Space>
          );
        },
      },

      {
        title: "章节",
        dataIndex: "chapter_title",
        key: "chapter_title",
        render: (_: any, record: any) => {
          return (
            <Space>
              <span>{record.chapter_title}</span>
              <Popconfirm
                placement="top"
                title="修改章节标题名"
                description={
                  <Input
                    defaultValue={record.chapter_title}
                    onChange={(e: any) =>
                      setEditChapterItem({
                        key: "chapter_title",
                        value: e.target.value,
                      })
                    }
                  />
                }
                onConfirm={() => onConfirmEditChapterItem(record)}
                okText="确定"
                cancelText="取消"
              >
                <Button type="text" icon={<EditOutlined />} />
              </Popconfirm>
            </Space>
          );
        },
      },
      {
        title: "FileID",
        dataIndex: "chapter_file_id",
        key: "chapter_file_id",
        render: (_: any, record: any) => {
          return +record.chapter_level === 2 ? (
            <Space>
              <span>{record.chapter_file_id}</span>
              <Popconfirm
                placement="top"
                title="修改FileID"
                description={
                  <Input
                    defaultValue={record.chapter_file_id}
                    onChange={(e: any) =>
                      setEditChapterItem({
                        key: "chapter_file_id",
                        value: e.target.value,
                      })
                    }
                  />
                }
                onConfirm={() => onConfirmEditChapterItem(record)}
                okText="确定"
                cancelText="取消"
              >
                <Button type="text" icon={<EditOutlined />} />
              </Popconfirm>
            </Space>
          ) : (
            "-"
          );
        },
      },
      {
        title: "顺序",
        dataIndex: "order",
        key: "order",
        render: (_: any, record: any) => {
          return (
            <Space>
              <span>{record.order}</span>
              <Popconfirm
                placement="top"
                title="修改顺序"
                description={
                  <Input
                    defaultValue={record.order}
                    onChange={(e: any) =>
                      setEditChapterItem({
                        key: "order",
                        value: +e.target.value,
                      })
                    }
                  />
                }
                onConfirm={() => onConfirmEditChapterItem(record)}
                okText="确定"
                cancelText="取消"
              >
                <Button type="text" icon={<EditOutlined />} />
              </Popconfirm>
            </Space>
          );
        },
      },
      {
        title: "时长",
        dataIndex: "media_time",
        key: "media_time",
        render: (_: any, record: any) => {
          return +record.chapter_level === 2 ? (
            <Space>
              <span>{record.media_time}</span>
            </Space>
          ) : (
            "-"
          );
        },
      },
      {
        title: "操作",
        dataIndex: "operation_chapter",
        key: "operation_chapter",
        render: (_: any, record: any) => {
          return (
            <Space>
              <Popconfirm
                placement="top"
                title="确定删除章节嘛"
                onConfirm={() => onConfirmDeleteChapterItem(record)}
                okText="确定"
                cancelText="取消"
              >
                <Button type="dashed" danger icon={<DeleteOutlined />}></Button>
              </Popconfirm>
            </Space>
          );
        },
      },
    ];
    return <Table columns={col} dataSource={chapterList} pagination={false} />;
  };

  const renderChapterList = (chapter_course_id: string) => {
    selectChapterList({ chapter_course_id }).then((res: any) => {
      const { data = [] } = res;
      setChapterList(data.map((i: any) => ({ ...i, key: i.chapter_id })));
    });
  };

  const onExpand = (expand: boolean, record: any) => {
    if (expand) {
      const { course_id: chapter_course_id } = record;
      renderChapterList(chapter_course_id);
    }
  };

  return (
    <div className="list">
      <Card>
        <Table
          dataSource={courseList}
          columns={columns}
          expandable={{ expandedRowRender }}
          onExpand={onExpand}
        />
      </Card>
    </div>
  );
}
