/** 模拟考试 | 资质考试选题 */
//import { AlignLeftOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, InputNumber, message, Space, Form, Input} 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, 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 { queryCourseView } from '@/pages/course/option/service';
import { queryQuestionList, queryQuestionType } from '@/pages/questionbank/service';
//import ProForm, { ProFormSelect } from '@ant-design/pro-form';
import { ActionType, EditableProTable, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import ProForm from '@ant-design/pro-form';

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 ScoreSetter = (props: any, ref: any) => {

  const {questionTypeValues } = props

  console.log('questionTypeValues::::::::::', questionTypeValues)
  //console.log('passScoreValue:::', passScoreValue)
  
  const match = useRouteMatch();
  console.log('match', match);

  const [typeScore, setTypeScore] = useState(questionTypeValues.map(item=>({question_type:item.code, score: item.score, score_harf: item.score_harf}))) ; // 题型分数数组	[{"question_type": "0","score": "3","score_harf": "0"},]
  //const type = history.location.pathname === '/questionbank/attestation' ? 1 : 0 ; // 题库类型
  const [dataSource, setDataSource] = useState([]);
  //const [selectedRowsState, setSelectedRows] = useState<API.RuleListItem[]>([]);
  //const [addType, setAddType] = useState({name: '', value: 0});
  const [sumScore, setSumScore] = useState(0);
  const [passScore, setPassScore] = useState(0); // 设置通过分数线
  
  //let sumScore = 0 // 总分
  console.log('init........', typeScore)
  const formRef = useRef();

  //setTypeScore(questionTypeValues) // 初始化分值
  //const actionRef = useRef<ActionType>();

  /** 列表项定义 */
  const columns: any = [
    {
        title: '题型',
        dataIndex: 'name',
        //key: 'code',
        width: 100,
    },
    {
        title: '分值设置',
        dataIndex: 'score',
        key: 'code',
        width: 400,
        render: (text, record, index) => 
        <Space direction='horizontal'>
            <span>每题</span>
            <Form.Item style={{margin:0}} name={`score[${index}]`}><Input               
              style={{width:100}} 
              min={0} 
              type="number"
              onInput={(e)=>{
                const val = `${e.currentTarget?.value}`;
                e.currentTarget.value = val.replace(/[^\d,^\.]/,'0')
                if(val.length > 3) {
                  e.currentTarget.value = val.slice(0,3)
                }
              }}
              defaultValue={questionTypeValues ? questionTypeValues[index]?.score : 0} 
              placeholder="请输入" 
              size="small"
              onChange={(e)=>{
                const value = e.currentTarget.value;
                console.log('row', index)
                console.log('v1',value)
                const scoreData = typeScore?.map((item, key)=>{
                  return {...item, score: ((index === key) ? Number(value) : Number(item?.score))} // 题型分数
                })
                console.log('question',questionTypeValues)
                console.log('scoreData-----------------',scoreData)
                setTypeScore(scoreData)
              }}/></Form.Item>
            <span>分</span>
            { (record?.code === 1) &&
                <>
                    <span>错选、漏选得:</span>
                    <Form.Item style={{margin:0}} name={`score_harf`} 
                      rules={[
                        /*
                        {
                          required: true,
                          message: '请输入分值!',
                        },*/
                      ]}
                    ><InputNumber min={0} max={99} maxLength={2} type="number" defaultValue={questionTypeValues ? questionTypeValues[index]?.score_harf : 0} placeholder="请输入" size="small" name='score_harf' onChange={(value)=>{
                        //
                      const _data = [];
                      console.log('typeScore',typeScore)
                      typeScore?.forEach((item, key)=>{
                        _data.push({...item, score_harf: ((index === key) ? value : item?.score_harf)})
                      })
                      setTypeScore(_data)
                    }} /></Form.Item>
                    <span>分</span>
                </>
            }
        </Space>,
    },
    {
        title: '题目数量',
        dataIndex: 'count',
        width: 80,
        render: (text, _, index) => <>{questionTypeValues ? questionTypeValues[index]?.count : '0'}</>,
        /*
        editable: (text, record, index) => {
            return true;
        },*/
    },
    {
        title: '总分值',
        dataIndex: 'score_sum',
        //key: 'age',
        width: 80,
        render: (text, _, index) => {
          {/*console.log('typeScore---', typeScore)*/}
          return <>
          {(typeScore && questionTypeValues) ? ((typeScore[index]?.score > 0 ? typeScore[index]?.score : 0) * questionTypeValues[index]?.count).toFixed(1) : '0'}
          </>
        },
        
    }
  ];

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

  /** 获取总题数 */
  let sumQuestion = 0;
  questionTypeValues?.forEach((item) => {
    sumQuestion += item.count;
  });

  // 获取题型
  const { data } = useRequest(() => {
    return queryQuestionType();
  },{
    formatResult: (result) => {
      const _data = [];
      if(result.list){
        result.list.forEach((item)=>{
          _data.push({
              name: item?.name, 
              code: item?.code,
              count: 0,
              score_sum: 0,
              harf: 0
          })
        })
      }
      console.log('_data',_data)
      return _data;
    }
  });

  useEffect(() => {
    setDataSource(data);
    console.log('data', data)
    const _typeScore = [];
    data?.forEach((item)=>{
      _typeScore.push({question_type: item?.code, score: item?.count, score_harf: 0})
    })
    setTypeScore(_typeScore) // 初始值
    //return ()=>{}
  }, [data]);

  /** 计算总分 */
  useEffect(() => {
    console.log('typeScore', typeScore)
    let _sum = 0;
    typeScore?.forEach((item, index)=>{
      _sum += (item.score > 0 ? item.score : 0 ) * questionTypeValues[index]?.count;
    })
    
    setSumScore(_sum)
    //return ()=>{}
  }, [typeScore]);

  // 暴露组件的方法 接受外部获取的ref
  useImperativeHandle(ref, () => ({
    // 构造ref的获取数据方法
    getData: () => {      
      return typeScore?.map((item, idx)=>{return {...item, count: questionTypeValues[idx]?.count, sum: item?.score * questionTypeValues[idx]?.count}});
    },
    getValue: () => {
      return passScore;
    },
    getSum: () => {
      console.log('getSum', sumScore)
      return sumScore;
    },
  }));

  return (
    <Form 
      ref={formRef}
    >
    <EditableProTable
      title={()=>{
        return <Space size="large"><span>共计 {sumQuestion} 题,</span><span>总计 {sumScore} 分</span> 通过分数线 
        <Form.Item style={{margin:0}} name='pass_socre' initialValue={0}><InputNumber min={0} onChange={(value)=>{
          setPassScore(value)
        }} /></Form.Item>       
         分</Space>}}
      //formMapRef={formMapRef}
      //rowKey={'code'}
      bordered
      cardProps={{bodyStyle:{padding:0}}}
      recordCreatorProps={false}
      search={false}
      options={false}
      value={dataSource}
      columns={columns}
    />
  </Form>
 
  );
};
// forwardRef这个组件能够将其接受的 ref 属性转发到其组件树下
export default forwardRef( ScoreSetter );
