import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Pagination, Space, Select, Button, Input, Checkbox, Spin, Row, Col } from 'antd';

import TopicItem from './topicItem';

import { getList, typeAllList, bookNameList } from '../request';

const topicStyle = [
  { id: 1, name: '单选题' },
  { id: 2, name: '多选题' },
  { id: 3, name: '判断题' },
  { id: 4, name: '填空题' },
  { id: 5, name: '简答题' },
];

const ListTopic = forwardRef((props, ref) => {
  const { addTopicList, chooseList, setChooseList, bookId, bookNameIdData, practiceStatus, customerType } = props;

  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [source, setSource] = useState([]);
  const [total, setTotal] = useState(0);

  const [typeList, setTypeList] = useState([]);
  const [checkedArr, setCheckedArr] = useState([]);

  const [selectedBookId, setSelectedBookId] = useState(bookId);

  useEffect(() => {
    let arr = [];
    chooseList.forEach((item) => {
      arr.push(item.choose_id);
    });
    setCheckedArr(arr);
  }, [chooseList]);

  // 筛选条件设置
  const [questionStyle, setQuestionStyle] = useState('');
  const [typeId, setTypeId] = useState(customerType || '');
  const [titles, setTitles] = useState('');

  useImperativeHandle(ref, () => {
    return {
      setPage,
    };
  });

  // 页码选择
  const onChange = (number) => {
    setPage(number);
  }
  const onShowSizeChange = (current, size) => {
    setPageSize(size);
  }

  const getTypeList = async () => {
    const data = await typeAllList({ page: 1, page_size: 100000 });
    if (data) setTypeList(data.list);
  };
  useEffect(() => {
    getTypeList();
  }, []);

  const getData = async (bool) => {
    setLoading(true);
    let obj = { page, page_size: pageSize };
    if (questionStyle) obj.question_style = questionStyle;
    if (typeId) obj.type_id = typeId;
    if (titles) obj.titles = titles;
    if (selectedBookId) obj.book_id = selectedBookId;
    if (bool) {
      setPage(1);
      obj.page = 1;
    }

    const data = await getList(obj);
    if (data) {
      let dataSource = [];
      data.list.forEach((item, index) => {
        dataSource.push({ ...item, choose_id: item.id });
      });
      setTotal(data.total);
      setSource(dataSource);
    }
    setLoading(false);
  };
  
  useEffect(() => {
    if (selectedBookId !== null && !practiceStatus && customerType) {
      getData(true);
    } else {
      getData();
    }
    
  }, [page, pageSize, practiceStatus, customerType]);

  const topicChange = (e, record) => {
    const temp = JSON.parse(JSON.stringify(chooseList));
    let newTemp = [];
    if (e.target.checked) {
      newTemp = [...temp, record];
    } else {
      newTemp = temp.filter((item) => item.choose_id !== record.choose_id);
    }
    setChooseList(newTemp);
  };

  return (
    <div className='list-topic-container'>
      <div className='list-topic-filter'>
        <div className='list-topic-filter-list'>
          <div className='filter-item'>
            <Space>
              <span className='label'>书籍名称：</span>
              <Select
                placeholder='请选择书籍名称'
                allowClear
                defaultValue={bookId}
                value={selectedBookId}
                onChange={(value) => {
                  setSelectedBookId(value);
                }}
              >
                {bookNameIdData &&
                  bookNameIdData.length > 0 &&
                  bookNameIdData.map((item, index) => (
                    <Select.Option key={index} value={item.book_id}>
                      {item.name}
                    </Select.Option>
                  ))}
              </Select>
            </Space>
          </div>
          <div className='filter-item'>
            <Space>
              <span className='label'>题目类型：</span>
              <Select
                placeholder='请选择题目类型'
                value={questionStyle}
                onChange={(value) => setQuestionStyle(value)}
                allowClear
              >
                {topicStyle &&
                  topicStyle.length > 0 &&
                  topicStyle.map((item, index) => (
                    <Select.Option key={index} value={item.id}>
                      {item.name}
                    </Select.Option>
                  ))}
              </Select>
            </Space>
          </div>
          <div className='filter-item'>
            <Space>
              <span className='label'>题目分类：</span>
              <Select
                placeholder='请选择题目分类'
                value={typeId}
                onChange={(value) => setTypeId(value)}
                allowClear
              >
                {typeList &&
                  typeList.length > 0 &&
                  typeList.map((item, index) => (
                    <Select.Option key={index} value={item.id}>
                      {item.typename}
                    </Select.Option>
                  ))}
              </Select>
            </Space>
          </div>
          <div className='filter-item'>
            <Space>
              <span className='label'>题干名称：</span>
              <Input
                placeholder='请输入题干名称'
                value={titles}
                onChange={(e) => setTitles(e.target.value)}
                allowClear
              />
            </Space>
          </div>
        </div>
        <div className='list-topic-filter-btn'>
          <Space>
            <Button type='default' onClick={() => getData(true)}>
              筛选
            </Button>
          </Space>
        </div>
      </div>
      <div className='list-topic-box'>
        <Spin spinning={loading}>
          {/* <Checkbox.Group> */}
          {source &&
            source.length > 0 &&
            source.map((item, index) => {
              return (
                <div className='topic-item' key={index}>
                  <div className='checkbox'>
                    <Checkbox
                      checked={checkedArr.includes(item.choose_id)}
                      onChange={(e) => topicChange(e, item)}
                    />
                  </div>
                  <div className='topic-info'>
                    <TopicItem topic={item} index={(page - 1) * pageSize + index + 1} />
                  </div>
                </div>
              );
            })}
          {/* </Checkbox.Group> */}
        </Spin>
      </div>
      <div className='list-page'>
        <Pagination
          showQuickJumper
          showSizeChanger
          defaultCurrent={page}
          total={total}
          onChange={onChange}
          onShowSizeChange={onShowSizeChange}
        />

        <Button type='primary' onClick={addTopicList}>
          添加
        </Button>
      </div>
    </div>
  );
});

export default ListTopic;
