/** 模拟考试 | 资质考试选题 */
//import { AlignLeftOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, message } from 'antd';
//import { FooterToolbar, PageContainer } from '@ant-design/pro-layout';
//import { useRequest } from 'umi';
//import { queryFakeList } from './service';
//import type { CardListItemDataType } from './data';
//import styles from '../style.less';
//import SubMenu from 'antd/lib/menu/SubMenu';
//import ProCard from '@ant-design/pro-card';
//import ProList from '@ant-design/pro-list';
import { forwardRef, Key, ReactText, useEffect, useImperativeHandle, useRef, useState } from 'react';
//import { PlusOutlined, DeleteOutlined, DownloadOutlined, UploadOutlined, EditOutlined, EyeOutlined, EyeInvisibleOutlined, DownOutlined } from '@ant-design/icons';
import { useParams, useRequest, history, useRouteMatch } from 'umi';
import { queryCourseListByTag, queryCourseView, queryTagList } from '@/pages/course/option/service';
import { queryQuestionList, queryQuestionType } from '@/pages/questionbank/service';
//import ProForm, { ProFormSelect } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { FooterToolbar } from '@ant-design/pro-layout';
import { constant } from 'lodash';
import { queryQuestionWithoutList } from '../service';

export type TableListItem = {
  id: string;
  code: number;
  name: string;
  creator: string;
  status: string;
  createdAt: number;
  progress: number;
  money: number;
  memo: string;
};

// React.forwardRef 接受渲染函数作为参数。React 将使用 props 和 ref 作为参数来调用此函数。此函数应返回 React 节点。
const QuestionSelector = (props: any, ref: any) => {
  console.log('props', props)
  const actionRef = useRef<ActionType>();
  /** 列表项定义 */
  const columns: ProColumns<TableListItem>[] | ProColumns<TableListItem>[] = [
    {
      title: '序号',
      key: 'index',
      valueType: 'indexBorder',
      render: (text: React.ReactNode, _: any, index: number) => {
        if (actionRef && actionRef?.current && actionRef?.current?.pageInfo) {
          return `${(actionRef?.current?.pageInfo?.current - 1) * actionRef.current.pageInfo?.pageSize + (index + 1)
            }`;
        } else {
          return '';
        }
      },
      width: 48,
    },
    {
      title: '类型',
      dataIndex: 'question_type',
      valueType: 'select',
      hideInTable: false,
      hideInForm: true,
      hideInSearch: false,
      // width: 100,
      request: async () => {
        const { list: Items } = await queryQuestionType();
        const types = []
        for (let i = 0; i < Items.length; i++) {
          types.push({text: Items[i]?.name, label: Items[i]?.name, value: Items[i]?.code })
        }
        return types;
      },
      render: (text: React.ReactNode, _: any, index: number) => {
        return text;
      },
      
    },
    {
      title: '标签',
      dataIndex: 'tag_ids',
      valueType: 'text',
      hideInTable: true,
      hideInForm: true,
      hideInSearch: false,
      request: async () => {
        const { data: Items } = await queryTagList({});
        const tags = []
        for (let i = 0; i < Items.length; i++) {
          tags.push({ label: Items[i].tag_name, value: Items[i].tag_id })
        }
        return tags;
      },
    },
    {
      title: '课程',
      dataIndex: 'course',
      valueType: 'text',
      dependencies: ['tag_ids'],
      request: async (arr) => {
        // console.log('arr',arr)
        // const {tags} = arr;
        const { data: Items } = await queryCourseListByTag({ tag_ids: arr?.tag_ids?.toString() });
        const courses = []
        for (let i = 0; i < Items?.length; i++) {
          courses.push({ label: Items[i]?.course_name, value: Items[i]?.course_id })
        }
        return courses;
      },
      hideInTable: true,
      hideInForm: true,
      hideInSearch: false,
    },
    {
      title: '题干',
      dataIndex: 'question_stem',
      valueType: 'text',
      hideInTable: false,
      hideInForm: true,
      hideInSearch: true,
    },
  ];
  const match = useRouteMatch();
  console.log('match', match);

  const type = history.location.pathname === '/questionbank/attestation' ? 1 : 0 ; // 题库类型
  const [questionType, setQuestionType] = useState([]);
  const [selectedRowsState, setSelectedRows] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  
  //const [addType, setAddType] = useState({name: '', value: 0});

  //const labels = ['A','B','C','D','E','F','G','H','I']

  /** 获取题型 */
  const { data } = useRequest(() => {
    return queryQuestionType();
  },{
    formatResult: (result) => {
      return result.list;
    }
  });

  useEffect(() => {
    setQuestionType(data || []);
    return ()=>{
    }
  }, [data]);

  // 暴露组件的方法 接受外部获取的ref
  useImperativeHandle(ref, () => ({
    // 构造ref的获取数据方法
    getSelectedRowKeys: () => {
      return selectedRowKeys;
    },
    getSelectedRows: () => {
      return selectedRowsState;
    },
  }));
  
  
  return (
    <>

    <ProTable      
      pagination={{
        defaultPageSize: 10,
        showSizeChanger: false,
      }}
      search={
        {
          className:'questionSeatch',
          //optionRender: false,
          defaultCollapsed: false,
          collapsed: false,
          labelWidth: 'auto',
          span:6
        }
      }
      actionRef={actionRef}
      toolBarRender={false}
      rowKey="id"
      headerTitle={false}
      tooltip={false}
      request={async (value) => {
        console.log('value', value)
        /*
        const { create_time } = value;
        if (create_time) {
          value.begin_time = create_time[0]
          value.end_time = create_time[1]
        }*/
        const _data = {
          ...value,
          rules_id: props?.data?.rules_id,
          subject_id: props?.data?.subject_id,
          type: type,
          page_number: value?.current || 1,
          page_size: value?.pageSize,
        } 
        
        const questions = await queryQuestionWithoutList(props?.data?.paper_uuid ? {..._data, paper_uuid: props?.data?.paper_uuid} : _data);
        //console.log('**', props?.data?.paper_uuid,{paper_uuid: props?.data?.paper_uuid})
        //
        const data = []
        for(let i=0; i<questions?.table_List.length; i++){
          const { data: course } = await queryCourseView({
            course_id: questions?.table_List[i]?.course_id
          });
          data[i] = {...questions?.table_List[i], course_name:course?.course_name, tag_name:course?.tag_name, };
        }         
        return {
          current: questions?.pageNumber,
          data: data,
          pageSize: questions?.pageSize,
          success: true,
          total: questions?.totalRow || 0,
        };
      }}
      rowSelection={{
        selectedRowKeys: selectedRowKeys,
        onChange: (selectedKeys, _) => {
          const res = selectedRowsState?.filter(item=>(item.page === actionRef.current?.pageInfo?.current)).length
          let rows = [];
          rows = selectedRowsState?.map(item=>(item?.page === actionRef.current?.pageInfo?.current ? {page: actionRef.current?.pageInfo?.current, selected: selectedKeys} : item))
          if(res === 0){
            rows.push({page: actionRef.current?.pageInfo?.current, selected: selectedKeys})
          }
          const _data: any = []
          rows?.forEach((item)=>{
            _data.push(...item?.selected)
          })
          setSelectedRowKeys(_data)
          setSelectedRows(rows); // selectedRowsState
        },
      }}
      columns={columns}
      // grid={{ gutter: 16, column: 1 }}
    />
  </>
  );
};
// forwardRef这个组件能够将其接受的 ref 属性转发到其组件树下
export default forwardRef( QuestionSelector );
