import React, {ReactText, useState} from 'react';
import {PageContainer} from "@ant-design/pro-layout";
import {Button, Card, Col, Progress, Row, Table, Tag} from "antd";
import {getPageQuery} from "@/utils/utils";
import {useRequest} from "@@/plugin-request/request";
import {exportResult, result} from "@/services/paperManager";
import styles from './index.less'
import ProList from '@ant-design/pro-list';
import {
  QUESTION_TYPE_JUDGE,
  QUESTION_TYPE_MULTIPLE_CHOICE,
  QUESTION_TYPE_RATE,
  QUESTION_TYPE_SINGER_CHOICE,
  QUESTION_TYPE_TEXT
} from "@/services/constants";
import {ColumnsType} from "antd/es/table";

const PaperResult: React.FC = (props) => {
    const [expandedRowKeys, setExpandedRowKeys] = useState<readonly ReactText[]>([]);
    const [exportLoading1, setExportLoading1] = useState(false);
    const [exportLoading2, setExportLoading2] = useState(false);

    const paperId = parseInt(getPageQuery().id + '');
    const targetId = getPageQuery().targetId;

    if (!paperId) {
      return <>访问异常</>
    }

    const {data: paperResult} = useRequest(() => {
      return result(paperId, targetId);
    });

    const getPercent = (num1?: number, num2?: number) => {
      if (!num1 || !num2 || num1 == 0 || num2 == 0) {
        return 0
      }
      return (num1 / num2 * 100).toFixed(2)
    }

    const getQuestionType = (type?: number) => {
      if (type == QUESTION_TYPE_RATE) {
        return "评分"
      } else if (type == QUESTION_TYPE_SINGER_CHOICE) {
        return "单选"
      } else if (type == QUESTION_TYPE_MULTIPLE_CHOICE) {
        return "多选"
      } else if (type == QUESTION_TYPE_JUDGE) {
        return "判断"
      } else if (type == QUESTION_TYPE_TEXT) {
        return "简答"
      } else {
        return "未知"
      }
    }

    const getRelationType = (type: number) => {
      if (type == 1) {
        return "下级"
      } else if (type == 2) {
        return "平级"
      } else if (type == 3) {
        return "上级"
      } else if (type == 4) {
        return "自评"
      } else {
        return "未知"
      }
    }

    const columns360: ColumnsType<API.AnswerResult> = [
      {
        title: '账号',
        dataIndex: 'userAccount',
        key: 'userAccount',
        width: 300,
        render: (value) => {
          return <>{value || '-'}</>
        }
      },
      {
        title: '姓名',
        dataIndex: 'userName',
        key: 'userName',
        width: 150,
        render: (value) => {
          return <>{value || '-'}</>
        }
      },
      {
        title: '内容',
        dataIndex: 'content',
        key: 'content',
        width: 300
      },
      {
        title: '关系',
        dataIndex: 'relation',
        key: 'relation',
        width: 150,
        render: (value) => {
          return <>{getRelationType(value)}</>
        }
      },
    ]

    const columnsRace: ColumnsType<API.AnswerResult> = [
      {
        title: '账号',
        dataIndex: 'userAccount',
        key: 'userAccount',
        width: 150,
        render: (value) => {
          return <>{value || '-'}</>
        }
      },
      {
        title: '姓名',
        dataIndex: 'userName',
        key: 'userName',
        width: 150,
        render: (value) => {
          return <>{value || '-'}</>
        }
      },
      {
        title: '内容',
        dataIndex: 'content',
        key: 'content',
        width: 300
      },
    ]

    const exportExcel = async (type: number) => {
      console.log("exportExcel")
      type == 1 ? setExportLoading1(true) : setExportLoading2(true);
      const res = await exportResult(paperId, targetId, type);
      if (res) {
        const url = window.URL.createObjectURL(new Blob([res]));
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.download = paperResult?.paperTitle + '-问题详情.xls';
        document.body.appendChild(link);
        link.click();
        URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      }
      type == 1 ? setExportLoading1(false) : setExportLoading2(false);
    };

    return (
      <div className={styles.content}>
        <PageContainer>
          <Card>

            <div
              className={styles.title}>{paperResult?.paperTitle}{targetId ? "-" + paperResult?.targetUserName + "(" + paperResult?.targetUserAccount + ")" : ""}</div>
            <Row className={styles.row} align={"middle"}>
              <Col span={12}>
                <Progress percent={getPercent(paperResult?.answeredUser, paperResult?.totalUser)}/>
              </Col>
            </Row>
            <Row className={styles.row}>
              <Col span={12}>
                <div>完成人数:{paperResult?.answeredUser} 总人数:{paperResult?.totalUser}</div>
              </Col>
            </Row>

            <ProList<API.QuestionResult>
              className={styles.list}
              rowKey="title"
              headerTitle="问题详情"
              split={true}
              toolBarRender={() => {
                return [
                  <Button key="1" type="primary" onClick={() => exportExcel(1)} loading={exportLoading1}>
                    导出1
                  </Button>,
                  <Button key="1" type="primary" onClick={() => exportExcel(2)} loading={exportLoading2}>
                    导出2
                  </Button>,
                ];
              }}
              // itemLayout="vertical"
              expandable={{expandedRowKeys, onExpandedRowsChange: setExpandedRowKeys}}
              dataSource={paperResult?.questionResultList}

              metas={{
                subTitle: {
                  dataIndex: 'type',
                  render: (item) => {
                    return <Tag color="blue">{getQuestionType(item as number)}</Tag>
                  }
                },
                title: {
                  dataIndex: 'title',
                },
                description: {
                  dataIndex: 'answerResultList',
                  render: (item) => (
                    <Table className={styles.answerTable} columns={targetId ? columns360 : columnsRace}
                           dataSource={item as API.AnswerResult[]}
                           bordered={true} showHeader={false} size={"small"} pagination={false}/>
                  ),
                },
              }}
            />
          </Card>
        </PageContainer>
      </div>
    );
  }
;

export default PaperResult
