/** 资质考试 */
import { AlignLeftOutlined, ConsoleSqlOutlined, PlusOutlined } from '@ant-design/icons';
import { Switch, Button, Card, Col, List, Menu, Progress, Row, Typography, Space, Divider, Radio, Checkbox, Form ,message} from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { useParams, useRequest, history } from 'umi';
import { useEffect, useRef, useState } from 'react';
const { Text, Link } = Typography;
import { getRulesPaper, getPaperQuestionList, finishExamination, getCurrentDate } from '../service';
import type { CardListItemDataType } from '../data';
import styles from './style.less';
import cookie from 'react-cookies';

import ProCard from '@ant-design/pro-card';
const CheckboxGroup = Checkbox.Group;

const { Paragraph } = Typography;

//  秒数转化为时分秒
const formatSeconds = (value) => {
  //  秒
  let second = parseInt(value)
  //  分
  let minute = 0
  //  小时
  let hour = 0
  //  天
  //  let day = 0
  //  如果秒数大于60，将秒数转换成整数
  if (second > 60) {
    //  获取分钟，除以60取整数，得到整数分钟
    minute = parseInt(second / 60)
    //  获取秒数，秒数取佘，得到整数秒数
    second = parseInt(second % 60)
    //  如果分钟大于60，将分钟转换成小时
    if (minute > 60) {
      //  获取小时，获取分钟除以60，得到整数小时
      hour = parseInt(minute / 60)
      //  获取小时后取佘的分，获取分钟除以60取佘的分
      minute = parseInt(minute % 60)
      //  如果小时大于24，将小时转换成天
      //  if (hour > 23) {
      //    //  获取天数，获取小时除以24，得到整天数
      //    day = parseInt(hour / 24)
      //    //  获取天数后取余的小时，获取小时除以24取余的小时
      //    hour = parseInt(hour % 24)
      //  }
    }
  }

  let result = '' + parseInt(second) + ' 秒 '
  if (minute > 0) {
    result = '' + parseInt(minute) + ' 分 ' + result
  }
  if (hour > 0) {
    result = '' + parseInt(hour) + ' 小时 ' + result
  }
  //  if (day > 0) {
  //    result = '' + parseInt(day) + '天' + result
  //  }
  console.log('result：', result)
  return result
}





const CardList = () => {
  const formRef = useRef<ActionType>();
  const params = useParams();

  // 组卷详情查询
  const [rulesPaperInfo, setRulesPaperInfo] = useState({
    question_type_count: []
  });
  // 试题分数
  const [rulesPaperScore, setRulesPaperScore] = useState([]);
  // 试题列表
  const [paperInfo, setPaperInfo] = useState([]);
  //答题卡列表
  const [questionTypeList, setQuestionTypeList] = useState([])
  // 当前答题id
  const [questionNow, setQuestionNow] = useState({})
  // 解析可见
  const [parsingShow, setParsingShow] = useState(false)


  const [lastBtnShow, setLastBtnShow] = useState(true)
  const [nextBtnShow, setNextBtnShow] = useState(true)

  // 当前题号
  const [questionNowNum, setQuestionNowNum] = useState(0)
  const [questionNum, setQuestioNum] = useState(0)

  const [timeData, setTimeData] = useState(0);






  useEffect(() => {
    let secondValue = params.rules_time * 60; // 秒  截至时间 - 服务器当前时间
    setTimeData(secondValue)

    const timer = setInterval(() => {      //
      setTimeData((secondValue >= 1) ? secondValue-- : 0);
      console.log(questionTypeList, 'secondValue', rulesPaperInfo);
      if (secondValue === 0) {
        handelFinishExamination()
        clearInterval(timer)
        return
      }

    }, 1000);
    return () => {
      clearInterval(timer) // 清理计算器
    }
  }, [questionTypeList, rulesPaperInfo])






  const { loading, data } = useRequest(() => {
    return getRulesPaper({
      rules_id: params.rules_id
    });
  },
    {
      formatResult: (result) => {
        return result;
      },
      onSuccess: (result) => {
        // console.log(result, 111111111111111);

        if (result.success) {
          setRulesPaperInfo(result.question_list[0] || [])
          // 设置分数
          setRulesPaperScore(result.question_type_score || [])
          run({ paper_id: result.question_list[0].paper_id, question_type_count: result.question_list[0].question_type_count })
          // setQuestionTypeList(result.question_list[0].question_type_count)
        }
      }
    });

  const { run } = useRequest(getPaperQuestionList,
    {
      refreshDeps: [rulesPaperInfo],
      manual: true,
      formatResult: (result) => {
        return result;
      },
      onSuccess: (result, params) => {
        // setRulesPaperInfo(result || [])
        if (result.success) {
          // 试题列表
          const paperList = result.question_list;

          const qList = params[0].question_type_count
          const questionList: any[] = []
          qList.map((e, i) => {
            if (e.count > 0) {
              questionList.push({
                children: [],
                ...e
              })

            }
          })


          // 根据分类拆分试题 左侧答题卡   state:0 未答题 1 ： 已答题
          paperList.map((e) => {
            questionList.map((item, index) => {
              if (item.question_type == e.question_type) {
                questionList[index].children.push({ ...e, question_type: item.question_type, answerSelect: "", state: 0, answerId: "" })
              }
            })
          })

          // 根据答题卡生成考试顺序
          const questionInfo = []
          for (let i = 0; i < questionList.length; i++) {
            questionList[i].children.map((e, index) => {
              questionInfo.push({ ...e, index: [i, index] })
              questionList[i].children[index].index = [i, index]
            })
          }


          setPaperInfo(questionInfo || [])
          setQuestionNow(questionInfo[0] || [])
          setQuestionTypeList(questionList || [])

          setQuestioNum(questionInfo.length)
        }
      }
    });



  const { run: runFinishExamination } = useRequest(finishExamination,
    {
      refreshDeps: [rulesPaperInfo],
      manual: true,
      formatResult: (result) => {
        return result;
      },
      onSuccess: (result) => {

        if (result.success) {
          const res = result.data
          const time = params.rules_time * 60 - timeData
          console.log(res, 'questionFinish server111', rulesPaperInfo)

          history.push(`/mockExamination/index/success/${time}/${res.pass_score}/${res.score}/${res.sum_score}/${rulesPaperInfo.rules_name}`);

        }
      },
      onError:(error)=>{
        // console.log('resultshib1==============',result.response)
        message.error(error.response.data.info)
      }
    });





  useEffect(() => {
    // 已选择题目回显
    formRef?.current?.setFieldsValue({ note: questionNow.answerId });
    paperInfo.map((item, index) => {
      if (item.id === questionNow.id) {
        setQuestionNowNum(index + 1)
      }
    })
  }, [questionNow]);

  useEffect(() => {
    console.log(questionNowNum, questionNum, 'questionNowNum');
    setLastBtnShow(questionNowNum == 1 ? true : false)
    setNextBtnShow(questionNowNum == questionNum ? true : false)
  }, [questionNowNum, questionNum])



  // 提交试卷
  const handelFinishExamination = () => {

    const questionFinishId = []
    questionTypeList.map((e, i) => {
      questionTypeList[i].children.map((e, index) => {
        const answerId = e.answerId
        answerId !== "" ? questionFinishId.push({
          answer_id: (answerId instanceof Array) ? answerId.join(',') : answerId,
          question_id: e.id,
          question_type: e.question_type
        }) : ""
      })
    })

    const questionFinish = {
      answers: JSON.stringify(questionFinishId),
      rules_id: rulesPaperInfo.rules_id,
      person_id: cookie.load('person_id'),
      paper_id: rulesPaperInfo.paper_id
    }
    console.log(questionFinish, 'questionFinish', rulesPaperInfo)
    runFinishExamination(questionFinish)
  }

  // console.log(rulesPaperInfo, 'rulesPaperInfo', questionList)

  const numbers = [];
  for (let i = 0; i < 50; i++) {
    numbers.push({ id: `${i}` })
  }

  // 序号回数字
  const tiNum = (a: number) => {
    switch (a) {
      case 0:
        return "A："
        break;
      case 1:
        return "B："
        break;
      case 2:
        return "C："
        break;
      case 3:
        return "D："
        break;
      case 4:
        return "E："
        break;
      case 5:
        return "F："
        break;
      case 6:
        return "G："
        break;
      case 7:
        return "H："
        break;
      case 8:
        return "I："
        break;
      case 9:
        return "J："
        break;
      default:
        return ""
        break;
    }

  }
  // 题型回数字
  const tiTypeNum = (a: number) => {
    switch (a) {
      case 0:
        return "一、"
        break;
      case 1:
        return "二、"
        break;
      case 2:
        return "三、"
        break;
      default:
        return ""
        break;
    }
  }



  // 根据题型返回题数、分数、总分
  const showQuestionTypeSocore = (questionType) => {

    let questionName = ""
    // switch (questionType) {
    //   case 0:
    //     questionName = "单选题"
    //     break;
    //   case 1:
    //     questionName = "多选题"
    //     break;
    //   case 2:
    //     questionName = "判断题"
    //     break;

    // }


    let num = 0
    let score = 0

    // 当前分类下试题总数
    if (JSON.stringify(rulesPaperInfo) !== "{}" && rulesPaperInfo.length !== 0) {

      rulesPaperInfo.question_type_count.map((e, i) => {
        console.log(e, 'eeeeee');

        if (e.question_type === questionType) {

          num = e.count
          questionName = e.type_name+'题'
        }

      })


      console.log(rulesPaperScore, rulesPaperInfo, ' console.log(rulesPaperScore)')
      rulesPaperScore.map((e, i) => {
        if (e.question_type === questionType) {
          score = e.score
        }
      })


    }


    // if (rulesPaperInfo.id) {

    // }



    return `${questionName} (共${num}题,每题${score}分)`
  }





  const content = (
    <div>
      <p style={{ textAlign: "center", fontSize: 24 }}>
        {rulesPaperInfo.rules_name}
      </p>
    </div >
  );

  return (
    <PageContainer content={content} extraContent={false} title={false}>
      <Row>
        {console.log(questionTypeList, 'questionTypeList')}

        <Col span={6} style={{ paddingRight: 24 }}>
          <ProCard
            title="题号列表"
            bordered
            className='answerSheet'
            headStyle={{ padding: 24, border: '#d9d9d9 solid 1px' }}
          >
            {

              questionTypeList && (

                questionTypeList.map((e, i) => {

                  return <List
                    key={i}
                    header={tiTypeNum(e.question_type) + e.type_name+'题'}
                    footer={false}
                    bordered
                    dataSource={e.children}
                    renderItem={(item, index) => {
                      // console.log(item, 'list')
                      return <List.Item
                        id={item.id}
                      > <Button
                        className={
                          `pdefault  ${item.state === 1 ? "pok" : ""} ${questionNow.id === item.id ? "pact" : ""}`

                        }
                        onClick={() => {
                          // 查看答案关闭
                          setParsingShow(false)

                          paperInfo.map((e) => {
                            if (e.id === item.id) {
                              // 重写单选的label、value，index：保存当前试题的index。
                              setQuestionNow({ ...item, index: e.index })
                            }
                          })

                        }}
                      >{index + 1}</Button> </List.Item>
                    }}
                    style={{ background: '#ffffff', margin: '-25px -24px 24px -24px' }}
                  />
                }
                )


              )}
            <div>
              <div style={{ float: 'right', lineHeight: "28px" }}>未答
              </div><div className='pdefault dt-demo' />
              <div style={{ float: 'right', lineHeight: "28px" }}>已答
              </div><div className='pok dt-demo' />
            </div>
          </ProCard>
        </Col>
        <Col span={13} style={{ background: '#ffffff', padding: 0 }}>
          <ProCard
            title={tiTypeNum(questionNow.question_type) + showQuestionTypeSocore(questionNow.question_type)}
            extra={false}
            split='vertical'
            bordered
            headerBordered
          >
            <Space direction="vertical" style={{ width: '100%', padding: '24px 48px' }}>
              <Typography style={{ marginBottom: 16, fontSize: 18 }}>
                {console.log('questionNow',questionNow)}
                {questionNow.id ? questionNow.index[1] + 1 : ""} 、{questionNow?.question_stem}
                {/* {console.log(questionNow.answerId, 'answerId', questionNow.answerId)} */}
              </Typography>
              <Space direction="vertical" style={{ fontSize: 16 }}>
                <Form
                  ref={formRef} name="control-ref"
                >
                  <Form.Item name="note">

                    {questionNow.question_type === 0 ?

                      (

                        <Radio.Group>
                          <Space direction="vertical">{questionNow?.answers?.map((item, index) => {

                            return <Radio key={item.id}
                              onChange={(e) => {
                                const qArr = []
                                // 默认输出答案0，0，0，0
                                questionNow?.answers?.map((qitem) => {
                                  qitem.id === e.target.value ? qArr.push("1") : qArr.push("0")
                                })

                                const questionList = questionTypeList
                                const questionAnswer = qArr.join(",")
                                // 修改答题卡状态 写入答案以及修改答题状态
                                questionList[questionNow.index[0]].children[questionNow.index[1]].answerSelect = questionAnswer;
                                // 答题状态
                                questionList[questionNow.index[0]].children[questionNow.index[1]].state = 1
                                questionList[questionNow.index[0]].children[questionNow.index[1]].answerId = item.id
                                // 提交答题卡
                                setQuestionTypeList(questionList)

                                // console.log('0', questionList, questionNow, item, qX, qI)
                              }}
                              value={item.id}
                              style={{ padding: 5, fontSize: 16 }}
                            >{tiNum(index)}{item.answer}</Radio>

                          })}</Space></Radio.Group>
                      ) : questionNow.question_type === 1 ? <Checkbox.Group onChange={(e) => {
                        const qArr = []
                        // 默认输出答案0，0，0，0
                        questionNow?.answers?.map((item) => {
                          if (e.indexOf(item.id) > -1) {
                            qArr.push("1")
                          } else {
                            qArr.push("0")
                          }
                        })
                        const questionList = questionTypeList
                        const questionAnswer = qArr.join(",")

                        questionList[questionNow.index[0]].children[questionNow.index[1]].answerSelect = questionAnswer;
                        // 答题状态
                        questionList[questionNow.index[0]].children[questionNow.index[1]].state = 1
                        questionList[questionNow.index[0]].children[questionNow.index[1]].answerId = e
                        // 提交答题卡
                        setQuestionTypeList(questionList)

                        // console.log('0', questionList, questionNow, item, qX, qI)
                      }}>
                        {questionNow?.answers?.map((item, index) => {

                          return <Checkbox key={item.id}

                            value={item.id}
                            style={{ padding: 5, fontSize: 16 }}
                          >{tiNum(index)}{item.answer}</Checkbox>

                        })}
                      </Checkbox.Group> : questionNow.question_type === 2 ? (

                        <Radio.Group>
                          <Space direction="vertical">{questionNow?.answers?.map((item, index) => {

                            return <Radio key={item.id}
                              onChange={(e) => {
                                const qArr = []
                                // 默认输出答案0，0，0，0
                                questionNow?.answers?.map((qitem) => {
                                  qitem.id === e.target.value ? qArr.push("1") : qArr.push("0")
                                })

                                const questionList = questionTypeList
                                const questionAnswer = qArr.join(",")
                                // 修改答题卡状态 写入答案以及修改答题状态
                                questionList[questionNow.index[0]].children[questionNow.index[1]].answerSelect = questionAnswer;
                                // 答题状态
                                questionList[questionNow.index[0]].children[questionNow.index[1]].state = 1
                                questionList[questionNow.index[0]].children[questionNow.index[1]].answerId = item.id
                                // 提交答题卡
                                setQuestionTypeList(questionList)

                                // console.log('0', questionList, questionNow, item, qX, qI)
                              }}
                              value={item.id}
                              style={{ padding: 5, fontSize: 16 }}
                            >{tiNum(index)}{item.answer}</Radio>

                          })}</Space></Radio.Group>
                      ) : ""
                    }
                  </Form.Item>
                </Form>
              </Space>

              <Radio.Group onChange={() => { return true }} value={0} size="large">
                <Space direction="vertical" style={{ fontSize: 16 }}>
                  <Button type="primary" onClick={() => {
                    setParsingShow(!parsingShow)
                  }}>查看答案</Button>
                  <div style={{ display: (parsingShow ? 'block' : 'none') }} dangerouslySetInnerHTML={{ __html: questionNow.parsing }} />
                </Space>
              </Radio.Group>
            </Space>
          </ProCard>
        </Col>
        <Col span={5} style={{ paddingLeft: 24 }}>
          <div style={{ background: '#ffffff', padding: 24 }}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <strong>剩余时间</strong>
              <Typography>{formatSeconds(timeData)}</Typography>
              <Divider style={{ margin: '6px 0', opacity: 0.5 }} />
              <strong>答题序号</strong>
              <Typography>{questionNowNum}/{questionNum}</Typography>
              <Divider style={{ margin: '6px 0', opacity: 0.5 }} />
              <Button
                size="large"
                disabled={lastBtnShow}

                onClick={() => {

                  paperInfo.map((e, i) => {

                    if (e.id === questionNow.id) {
                      const nextTemp = paperInfo[i - 1]
                      const questionList = questionTypeList
                      let nextData = {}
                      questionList[nextTemp.index[0]].children.map((item, index) => {
                        if (item.id === nextTemp.id) {
                          nextData = item
                        }
                      })
                      setQuestionNow(nextData)
                    }

                  })

                  // console.log(nextQuestionData, "下一题")
                }}

                block>上一题</Button>

              <Button size="large"
                disabled={nextBtnShow}
                block onClick={() => {

                  paperInfo.map((e, i) => {

                    if (e.id === questionNow.id) {
                      const nextTemp = paperInfo[i + 1]
                      const questionList = questionTypeList
                      let nextData = {}
                      questionList[nextTemp.index[0]].children.map((item, index) => {
                        console.log(item, 'item next');

                        if (item.id === nextTemp.id) {
                          nextData = item
                        }
                      })
                      setQuestionNow(nextData)
                    }

                  })

                  // console.log(nextQuestionData, "下一题")
                }}>下一题</Button>
              <Button size="large" type="primary"
                onClick={() => {
                  console.log(questionTypeList, 'questionFinish')
                  handelFinishExamination()

                }}
                block>提交答卷</Button>
            </Space>
          </div>
        </Col>
      </Row >
    </PageContainer >
  );
};

export default CardList;
