/** 资质考试 */
//import { AlignLeftOutlined, PlusOutlined } from '@ant-design/icons';
import { Switch, Button, Card, Col, List, Menu, Progress, Row, Typography, Space, Divider, Radio, Checkbox, Tag, Dropdown, Upload } from 'antd';
import { 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 { ReactText, useEffect, useState } from 'react';
import { PlusOutlined, DeleteOutlined, DownloadOutlined, UploadOutlined, EditOutlined, EyeOutlined, EyeInvisibleOutlined, DownOutlined } from '@ant-design/icons';
import { exportQuestionTemplate, queryQuestionById, queryQuestionList, queryQuestionType } from './service';
import { useRequest } from 'umi';
import { queryCourseView } from '@/pages/course/option/service';
//const { Paragraph } = Typography;

const parsingMap = new Map()
console.log('first');
const QuestionBank = () => {
  console.log('second');
  const [questionType, setQuestionType] = useState([]);
  
  const [parsing, setParsing] = useState();

  const [selectedRowsState, setSelectedRows] = useState<API.RuleListItem[]>([]);
  const [expandedDescRowKeys, setExpandedDescRowKeys] = useState<readonly ReactText[]>([]); // 展开解析设置
  const [addType, setAddType] = useState(0);

  const labels = ['A','B','C','D','E']

  /** 获取题型 */
  const { data } = useRequest(() => {
    return queryQuestionType();
  },{
    formatResult: (result) => {
      return result.list;
    }
  });
/*
  const { data: template } = useRequest(() => {
    return exportQuestionTemplate();
  });
  */
  useEffect(() => {
    setQuestionType(data || []);
    return ()=>{
      /** 退出当前页面清空Map */
      parsingMap.clear();
    }
  }, [data]);

  
  
  return (
    <PageContainer content={false} extraContent={false} className={styles.questionbank}>
      <ProList<any>
        itemLayout="vertical"
        rowClassName='questionbank-list-item'
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: false,
        }}
        toolBarRender={() => {
          const menuItems = [];
          console.log('toolBarRender', questionType);
          if(questionType?.length > 0){
            console.log('push');
            questionType.forEach((item: {code: number, name: string})=>{
              menuItems.push(<Menu.Item key={item?.code}>{item?.name}</Menu.Item>)
            })
          }
          const menu = (             
            <Menu onClick={(value)=>setAddType(value)}>
              {menuItems}
            </Menu>            
          );
          return [
            <Dropdown overlay={menu}>
              <Button>
              <PlusOutlined /> 新建 <DownOutlined />
              </Button>
            </Dropdown>,
            <Button key="remove" type="default" danger>
              <DeleteOutlined /> 批量删除
            </Button>,
            <Button key="download" onClick={()=>{window.location.href='/dsideal_yy/zygh/training/exportQuestionTemplate'}} >
              <DownloadOutlined /> 下载模板
            </Button>,
            <Upload
              accept='.xlsx'
              showUploadList={false}
              action="/dsideal_yy/res/plupload/"
              data={
                {
                  type: 0,
                }
              }
            >
              <Button key="upload" >
                <UploadOutlined /> 批量上传
              </Button>
            </Upload>,
          ];
        }}
        onRow={(record: any) => {
          /*
          return {
            onMouseEnter: () => {
              console.log(record);
            },
            onClick: () => {
              console.log(record);
            },
          };*/
        }}
        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 questions = await queryQuestionList({
            ...value,
            type: 0,
            page_number: value?.current || 1,
            page_size: value?.pageSize,
          });
          // 课程名称及课程标签
          console.log('data',questions);
          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,
          };
        }}
        //dataSource={dataSource}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
        // grid={{ gutter: 16, column: 1 }}
        showActions="always"
        showExtra="always"
        metas={{
          title: {
            dataIndex: 'question_stem',
            render: (text: React.ReactNode, record: T, index: number) => `1. ${text}`,
          },
          avatar: {
            dataIndex: 'question_type',
            valueType: 'text',
            render: (text: React.ReactNode, record: T, index: number) => {
              const type = questionType?.filter((item, idx, self)=>{
                console.log('FFFF', item, idx, self);
                return item?.code === record.question_type
              });
              console.log('type', type?.name);
              console.log('type', type?.name);
              console.log('questionType::::',questionType);
              return `[${type[0]?.name}]`
            },
          },
          description: {
            dataIndex: 'answers',
            valueType: 'checkbox',
            render: (text: React.ReactNode, record: T, index: number) => {
              console.log('description answers', record)
              return (
                <List
                  header={false}
                  footer={false}
                  bordered={false}
                  dataSource={record.answers || []}
                  rowKey='id'
                  renderItem={ (item, key) => {
                    console.log('item', item);
                    return (
                      <List.Item>
                        <Typography.Text mark={false}>{`${(record?.question_type === 2) ? ['T','F'][key] : labels[key]}. ${item?.answer}`}</Typography.Text>
                      </List.Item>)
                  }}
                />
              );
            },
          },
          subTitle: { },
          content:  {
            render: (text: React.ReactNode, record: T, index: number) => {
              let answer = '';
              const answertrue = record?.answertrue?.split(',');
              console.log('answertrue', answertrue)
              /** 题型 */
              switch(record?.question_type){
                case 0: // 单选
                case 1: // 多选
                  answer = labels?.filter((x, idx, self)=>answertrue[idx] === `${idx}`).toString()
                  break;
                case 2: // 判断
                  answer = ['T', 'F']?.filter((x, idx, self)=>answertrue[idx] === `${idx}`).toString()
                  break;
              } 
              console.log('expandedDescRowKeys', expandedDescRowKeys)
              if(expandedDescRowKeys?.indexOf(record.id) > -1){
                return (
                  <Space direction="vertical" style={{borderTop:'solid 1px #f0f0f0', padding:10, margin: '5px -18px 0 -24px', background: '#fdfdfd'}}>
                    <Typography>正确答案：
                    {answer}
                    </Typography>
                    <Typography>解析：{parsing.get(record.id)}</Typography>
                  </Space>
                );
              }else{
                return (
                  <Space direction="vertical" style={{borderTop:'solid 1px #f0f0f0', padding:10, margin: '5px -18px 0 -24px', background: '#fdfdfd'}}>
                    <Typography>正确答案：
                    {answer}
                    </Typography>
                  </Space>
                )
              }

            },
          },
          actions: {
            cardActionProps: 'extra',
            render: (text: React.ReactNode, record: T, _index: number) => {
              let eye
              if(expandedDescRowKeys?.indexOf(record.id) > -1){
                eye = <><EyeInvisibleOutlined />  隐藏解析</>
              }else{
                eye = <><EyeOutlined />  查看解析</>
              }
              return(
                <Row style={{padding:'10px 24px'}}>
                  <Col flex={1} style={{textAlign:'left'}}>
                    <Space direction="horizontal" size="large">
                      <Typography>创建时间：{record?.create_time}</Typography>
                      <Typography>标签：{record?.tag_name}</Typography>
                      <Typography>所属课程：{record?.course_name}</Typography>
                    </Space>
                  </Col>
                  <Col flex={1} style={{textAlign:'right'}}>
                    <Space direction="horizontal" size="middle">
                      <a href={record.html_url} target="_blank" rel="noopener noreferrer" key="link">
                        <EditOutlined /> 编辑
                      </a>
                      <a href={record.html_url} target="_blank" rel="noopener noreferrer" key="warning" >
                        <DeleteOutlined /> 删除
                      </a>
                      <a
                        key="view"
                        onClick={async ()=>{
                          if(expandedDescRowKeys?.indexOf(record.id) > -1){
                            const descRowKeys = expandedDescRowKeys?.filter((item, idx, self)=>{
                              console.log('FFFF', item, idx, self);
                              return item !== record.id
                            });
                            setExpandedDescRowKeys([...descRowKeys]);
                          }else{
                            const { bean } = await queryQuestionById({id: record.id})
                            parsingMap.set(bean.id, bean.parsing)
                            setParsing(parsingMap);
                            console.log('parsing', parsing);
                            setExpandedDescRowKeys([...expandedDescRowKeys, record.id]);
                          }
                          
                          console.log('record id:', record.id);
                          console.log('expandedDescRowKeys......', expandedDescRowKeys)
                        }} 
                      >
                        {eye}
                      </a>
                    </Space>
                  </Col>
                </Row>          
              )
            }
          },
        }}
      />
    </PageContainer>
  );
};

export default QuestionBank;
