import React, {useRef, useState} from 'react';
import {PageContainer} from "@ant-design/pro-layout";
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {Card, message, Modal, Spin} from "antd";
import {useRequest} from "@@/plugin-request/request";
import {useModel} from "@@/plugin-model/useModel";
import {institutionList} from "@/services/institution";
import {ModalForm, ProFormInstance, ProFormText, ProFormTextArea} from '@ant-design/pro-components';
import {USER_TYPE_INSTITUTION, USER_TYPE_OTHER} from "@/services/constants";
import {deleteReport, download, reportList, updateReport} from "@/services/report";

const ReportList: React.FC = (props) => {
    const ref = useRef<ActionType>();
    const [currentReport, setCurrentReport] = useState<API.Report>();
    const [showDeleteConfirmDialog, setShowDeleteConfirmDialog] = useState(false);
    const {initialState} = useModel('@@initialState');
    const {currentUser} = initialState;
    const [showUpdateReportDialog, setShowUpdateReportDialog] = useState(false);
    const updateReportFormRef = useRef<ProFormInstance>();
    const [downloading, setDownloading] = useState(false);


    const {data: institutions} = useRequest(() => {
      return institutionList({page: 1, size: 100}, true);
    });

    const handleInstitutions = (institutions?: API.Institution[]) => {
      if (institutions) {
        const newList: {} = {};
        institutions.forEach(item => {
          if (item.name) {
            newList[item.id!] = {"text": item.name}
          }
        })
        return newList
      } else {
        return {}
      }
    }

    const clickEditReport = (report: API.Report) => {
      setCurrentReport(report)
      setShowUpdateReportDialog(true)
    }

    const clickDeleteReport = (report: API.Report) => {
      setCurrentReport(report)
      setShowDeleteConfirmDialog(true)
    }

    const handleDeleteReport = () => {
      deleteReport(currentReport!.id!).then(data => {
        setShowDeleteConfirmDialog(false)
        ref.current?.reload();
      })
    }

    const downloadPdf = async (reportId: number) => {
      setDownloading(true)
      const res = await download(reportId);
      if (res) {
        const url = window.URL.createObjectURL(new Blob([res]));
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.download = 'Race报告.pdf';
        document.body.appendChild(link);
        link.click();
        URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      }
      setDownloading(false)
    };

    const columns: ProColumns<API.Report>[] = [
      {
        dataIndex: 'index',
        valueType: 'indexBorder',
        width: 48,
      },
      {
        title: '企业',
        dataIndex: 'institutionName',
        valueType: 'select',
        hideInSearch: currentUser?.type == USER_TYPE_INSTITUTION || currentUser?.type == USER_TYPE_OTHER,
        hideInTable: currentUser?.type == USER_TYPE_INSTITUTION || currentUser?.type == USER_TYPE_OTHER,
        valueEnum: handleInstitutions(institutions?.records),
      },
      {
        title: '问卷标题',
        dataIndex: 'paperTitle',
      },
      {
        title: '总分',
        dataIndex: 'rScore',
        render: (text, record, _, action) => {
          return ([<>
            <div>{record.totalScore?.toFixed(2)}</div>
          </>])
        }
      },
      {
        title: '分位值',
        dataIndex: 'quantile',
        render: (text, record, _, action) => {
          return ([<>
            <div>{record.quantile?.toFixed(2)}</div>
          </>])
        }
      },
      {
        title: 'R得分',
        dataIndex: 'rScore',
        render: (text, record, _, action) => {
          return ([<>
            <div>R({record.rScore?.toFixed(2)})</div>
            <div>R1({record.r1Score?.toFixed(2)})</div>
            <div>R2({record.r2Score?.toFixed(2)})</div>
          </>])
        }
      },
      {
        title: 'A得分',
        dataIndex: 'aScore',
        render: (text, record, _, action) => {
          return ([<>
            <div>A({record.aScore?.toFixed(2)})</div>
            <div>A1({record.a1Score?.toFixed(2)})</div>
            <div>A2({record.a2Score?.toFixed(2)})</div>
            <div>A3({record.a3Score?.toFixed(2)})</div>
            <div>A4({record.a4Score?.toFixed(2)})</div>
          </>])
        }
      },
      {
        title: 'C得分',
        dataIndex: 'cScore',
        render: (text, record, _, action) => {
          return ([<>
            <div>C({record.cScore?.toFixed(2)})</div>
            <div>C1({record.c1Score?.toFixed(2)})</div>
            <div>C2({record.c2Score?.toFixed(2)})</div>
            <div>C3({record.c3Score?.toFixed(2)})</div>
            <div>C4({record.c4Score?.toFixed(2)})</div>
          </>])
        }
      },
      {
        title: 'E得分',
        dataIndex: 'eScore',
        render: (text, record, _, action) => {
          return ([<>
            <div>E({record.eScore?.toFixed(2)})</div>
            <div>E1({record.e1Score?.toFixed(2)})</div>
            <div>E2({record.e2Score?.toFixed(2)})</div>
            <div>E3({record.e3Score?.toFixed(2)})</div>
            <div>E4({record.e4Score?.toFixed(2)})</div>
          </>])
        }
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        hideInSearch: true,
      },
      {
        title: '操作',
        valueType: 'option',
        render: (text, record, _, action) => {
          return (
            [
              <a onClick={() => {
                clickEditReport(record)
                setTimeout(() => {
                  updateReportFormRef?.current?.setFieldsValue({
                    ...record
                  })
                })
              }}>编辑</a>,

              <a onClick={() => {
                setCurrentReport(record)
                downloadPdf(record!.id!)
              }}> {downloading && record.id === currentReport?.id ? <><Spin size="small"/>生成中</> : "下载"}</a>,
              <a onClick={() => clickDeleteReport(record)}>删除</a>,
            ]
          );
        }
      },
    ]

    return (
      <div>
        <PageContainer>
          <Modal title="" visible={showDeleteConfirmDialog} onOk={handleDeleteReport}
                 onCancel={() => setShowDeleteConfirmDialog(false)}>
            <p>删除该报告</p>
          </Modal>

          <ModalForm<API.Report>
            formRef={updateReportFormRef}
            title={"编辑报告"}
            visible={showUpdateReportDialog}
            modalProps={{
              onCancel: () => setShowUpdateReportDialog(false),
            }}
            onFinish={async (values) => {
              console.log(values)
              updateReport({
                ...values
              }).then(data => {
                if (data.code == 200) {
                  message.success("设置成功");
                  ref.current?.reload();
                  setShowUpdateReportDialog(false)
                } else {
                  message.error(data.message)
                }
              }).catch(data => {
                console.log(data)
              })
            }
            }

          >
            <ProFormText name="id" hidden={true}/>
            <ProFormText name="institutionId" hidden={true}/>
            <ProFormTextArea name="rDesc" label="R(综述)" rules={[{max: 200},]}/>
            <ProFormTextArea name="aDesc" label="A(综述)" rules={[{max: 200},]}/>
            <ProFormTextArea name="cDesc" label="C(综述)" rules={[{max: 200},]}/>
            <ProFormTextArea name="eDesc" label="E(综述)" rules={[{max: 200},]}/>
            <ProFormTextArea name="rSuggest" label="R(建议)" rules={[{max: 80},]}/>
            <ProFormTextArea name="aSuggest" label="A(建议)" rules={[{max: 80},]}/>
            <ProFormTextArea name="cSuggest" label="C(建议)" rules={[{max: 80},]}/>
            <ProFormTextArea name="eSuggest" label="E(建议)" rules={[{max: 80},]}/>
          </ModalForm>

          <Card>
            <ProTable<API.Tag>
              actionRef={ref}
              columns={columns}
              request={async (params = {}, sort, filter) => {
                let institutionId = currentUser?.institutionId;
                if (institutionId <= 0) {
                  institutionId = params.institutionName
                }
                const response = await reportList({
                  institutionId: institutionId,
                  title: params.paperTitle,
                  page: params.current,
                  size: params.pageSize,
                });
                if (response.code === 200) {
                  return {
                    data: response.data!.records,
                    success: true,
                    total: response.data!.total,
                  };
                } else {
                  message.error(response.message)
                  return {}
                }
              }}
              editable={{
                type: 'multiple',
              }}
              rowKey={record => record.id!}
              search={{
                labelWidth: 'auto',
              }}
              pagination={{
                pageSize: 5,
              }}
              dateFormatter="string"
              headerTitle="报告列表"
            />
          </Card>
        </PageContainer>
      </div>
    );
  }
;

export default ReportList
