/** 模拟考试 | 资质考试选题 */
import { InputNumber, Space, Form, Input} from 'antd';
//import styles from '../style.less';
import { forwardRef, useImperativeHandle, useRef, useState } from 'react';
//import { useParams, useRequest, history, useRouteMatch } from 'umi';
//import { queryCourseView } from '@/pages/course/option/service';
import { 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, passScore: passScoreValue } = props
console.log('passScorepassScorepassScorepassScore',questionTypeValues)
  const [flag, setFlag] = useState<any>([]) // 分数变更标记
  const [typeScore, setTypeScore] = useState(questionTypeValues.map((item: { code: number; score: number; score_harf: number; })=>({question_type:item.code, score: item.score!==undefined?item.score:0, score_harf: item.score_harf}))) ; // 题型分数数组	[{"question_type": "0","score": "3","score_harf": "0"},]
  //const type = history.location.pathname === '/questionbank/attestation' ? 1 : 0 ; // 题库类型
  //const [sumScore, setSumScore] = useState();
  const [passScore, setPassScore] = useState(passScoreValue); // 设置通过分数线
  const [maxScore, setMaxScore] = useState(0); // 设置通过分数线
  console.log('哈哈哈哈哈',passScore)
  const formRef = useRef<any>();

  /** 列表项定义 */
  const columns: any = [
    {
        title: '题型',
        dataIndex: 'name',
        //key: 'code',
        width: 100,
    },
    {
        title: '分值设置',
        dataIndex: 'score',
        key: 'code',
        width: 400,
        render: (_text: any, record: { code: number; }, index: string | number) =>
        <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.target.value = val.replace(/[^\d,^\.]/,'0')
                if(val.length > 3) {
                  e.currentTarget.value = val.slice(0,3)
                }
              }}
              defaultValue={questionTypeValues ? questionTypeValues[index]?.score || 0 : 0}
              placeholder="请输入"
              size="small"
              onChange={(e)=>{
                console.log('record',record)
                console.log('e.target.value',e.target.value)
                const value = e.target.value;
                const scoreData = typeScore?.map((item: { score: any; }, key: string | number)=>{
                  return {...item, score: ((index === key) ? Number(value) : Number(item?.score))} // 题型分数
                })
                console.log('scoreDatascoreDatascoreDat11111a',scoreData)
                // 标记重新设置项（序号）
                if(flag.indexOf(index) === -1){
                  setFlag([...flag, index])
                }
                setTypeScore(scoreData)
                if(record?.code === 1){
                  setMaxScore(e.target.value)
                }
              }}/></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={maxScore} maxLength={2} type="number" defaultValue={questionTypeValues ? questionTypeValues[index]?.score_harf || 0 : 0} placeholder="请输入" size="small" name='score_harf' onChange={(value)=>{
                    const harf = typeScore?.map((item: { score_harf: any; }, key: number)=>{
                      return {...item, score_harf: ((index === key) ? value : item?.score_harf)}
                    })
                    setTypeScore(harf)
                  }} /></Form.Item>
                  <span>分</span>
                </>
            }
        </Space>,
    },
    {
        title: '题目数量',
        dataIndex: 'count',
        width: 80,
        render: (_text: any, _: any, index: number) => <>{questionTypeValues ? questionTypeValues[index]?.count || 0 : '0'}</>,
    },
    {
        title: '总分值',
        dataIndex: 'score_sum',
        //key: 'age',
        width: 80,
        render: (_text: any, _: any, index: number) => {
          console.log('questionTypeValues-------------',questionTypeValues)
          return <>
          {flag?.indexOf(index) === -1 ?
            (questionTypeValues[index]?.score || 0) * (questionTypeValues[index]?.count || 0) :
            (typeScore && questionTypeValues) ? ((typeScore[index]?.score > 0 ? typeScore[index]?.score : 0) * (questionTypeValues[index]?.count || 0)) : '0'
          }
          </>
        },

    }
  ];

  /** 获取总题数 */
  let sumQuestion = 0;
  questionTypeValues?.forEach((item: any) => {
    console.log('item---------',item)
    sumQuestion += item.count;
  });

  // 暴露组件的方法 接受外部获取的ref
  useImperativeHandle(ref, () => ({
    // 构造ref的获取数据方法
    getData: () => {
      return typeScore?.map((item: any, idx: number)=>{
        return {
        ...item,
        count: questionTypeValues[idx]?.count,
        sum: item?.score * questionTypeValues[idx]?.count,
        }
      })
    },
    getValue: () => {
      return passScore
    },
    getSum: () => {
      return typeScore?.map((item: any, key: number)=>{return item?.score * questionTypeValues[key].count})?.reduce((total: number, item: number)=>(total + item)) || 0 ;
    },
  }));

  return (
    <>
      <Form
        ref={formRef}
      >
        <ProTable
          title={()=>{
            return <Space size="large"><span>共计 {sumQuestion || 0} 题,</span>
                {console.log('typeScore---',typeScore)}
              <span>总计 {
              typeScore?.length > 0 &&typeScore?.map((item: any, key: number)=>{return item?.score * questionTypeValues[key].count})?.reduce((total: number, item: number)=>(total + item)) || 0
              } 分</span> 通过分数线
            <Form.Item style={{margin:0}} name='pass_socre' initialValue={passScore || 0}><InputNumber min={0} defaultValue={passScore || 0} onChange={(value)=>{
              console.log('valuefensh',value)
              setPassScore(value)
            }} /></Form.Item>
            分</Space>}}
          //formMapRef={formMapRef}
          rowKey={'code'}
          request={async ()=>{
            console.log('questionTypeValues1111', questionTypeValues)
            const result = await queryQuestionType() // 从字典获取题型数据 [{code: 0, name:"单选题"},]
            setTypeScore(questionTypeValues?.map((item: { score: any; score_harf: any; }, key: number)=>{
              return {question_type: result.list[key]?.code, score: item?.score, score_harf: (item?.score_harf || 0)}
            }))

            return {data:questionTypeValues?.map((item: any, key: number)=>({
              ...item,
              code: result.list[key]?.code,
              question_type: result.list[key]?.code,
              name: result.list[key]?.name,
              count: result.list[key]?.count
            }))}

            /*
            return {data:result?.list?.map((item: any)=>({
              ...item,
              code: item?.code,
              question_type: item?.code,
              name: item?.name,
              count: item?.count || 0
            }))}
            */

          }}
          bordered
          cardProps={{bodyStyle:{padding:0}}}
          search={false}
          options={false}
          columns={columns}
          pagination={false}
        />
      </Form>
    </>
  );
};
// forwardRef这个组件能够将其接受的 ref 属性转发到其组件树下
export default forwardRef( ScoreSetter );
