/*
 * @Author: zhoujianlong
 * @Date: 2021-06-09 15:29:07
 * @Last Modified by: zhoujianlong
 * @Last Modified time: 2021-08-16 16:09:49
 */
import { getFileBidList, SnowflakeID } from '@/services/untilService';
import { Button, Modal } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
import React, { useEffect, useState, useImperativeHandle } from 'react';

interface WebOfficeProps {
  DOCFileCode?: string; //word 文件id *必填*
  PDFFileCode?: string; //PDF 文件id
  HTMLFileCode?: string; //HTML 文件id
  savePDF?: boolean; //是否保存为PDF true-保存 false-不保存 可以不传默认为false
  saveHTML?: boolean; //是否保存为HTML true-保存 false-不保存 可以不传默认为false
  readOnly?: boolean; //只读 true-查看 false-可编辑 *必填*
  webOfficeRef?: React.MutableRefObject<WebOfficeRefProps | undefined>; //父组件传入的ref参数 用于实时调取子组件内部参数 *必填*
  afterSaveFunc?: () => void //weboffice保存成功后执行的方法
}

export interface WebOfficeRefProps {
  DocFileCode: string;
  PDFFileCode: string;
  HTMLFileCode: string;
  uploadDocType: boolean;
  uploadPDFType: boolean;
  uploadHTMLType: boolean;
}

const WebOffice0609: React.FC<WebOfficeProps> = (props) => {
  const { DOCFileCode, PDFFileCode, HTMLFileCode, savePDF, saveHTML, readOnly, webOfficeRef, afterSaveFunc } = {
    DOCFileCode: '',
    PDFFileCode: '',
    HTMLFileCode: '',
    savePDF: false,
    saveHTML: false,
    readOnly: false,
    afterSaveFunc: () => {},
    ...props,
  };

  //存储weboffice渲染状态
  const [renderCode, setRenderCode] = useState<number>(-1);
  //按钮显示文字
  const [btnName, setBtnName] = useState<string>('');
  //按钮前提示文字
  const [beforeBtnText, setBeforeBtnText] = useState<string>('');
  //存储docFileCode
  const [docFileCode_, setDocFileCode_] = useState<string>(DOCFileCode);
  //存储pdfFileCode
  const [pdfFileCode_, setPdfFileCode_] = useState<string>(PDFFileCode);
  //存储htmlFileCode
  const [htmlFileCode_, setHtmlFileCode_] = useState<string>(HTMLFileCode);
  //word上传状态
  const [uploadDocType_, setUploadDocType_] = useState<boolean>(false);
  //pdf上传状态
  const [uploadPDFType_, setUploadPDFType_] = useState<boolean>(false);
  //html上传状态
  const [uploadHTMLType_, setUploadHTMLType_] = useState<boolean>(false);

  //选择暴露给父组件的参数或方法
  useImperativeHandle(
    webOfficeRef,
    () => ({
      DocFileCode: uploadDocType_ ? docFileCode_ : '',
      PDFFileCode: uploadPDFType_ ? pdfFileCode_ : '',
      HTMLFileCode: uploadHTMLType_ ? htmlFileCode_ : '',
      uploadDocType: uploadDocType_,
      uploadPDFType: uploadPDFType_,
      uploadHTMLType: uploadHTMLType_,
    }),
    [docFileCode_, pdfFileCode_, htmlFileCode_, uploadDocType_, uploadPDFType_, uploadHTMLType_],
  );
  useEffect(() => {
    updateWebOffice();
  }, [DOCFileCode]);

  useEffect(() => {
    window.addEventListener('message', receiveMessage, false); // 监听message事件,用于接收从子页面返回的参数
    return () => window.removeEventListener('message', receiveMessage);
  }, [docFileCode_, pdfFileCode_, htmlFileCode_]);

  //获取雪花id方法（新建状态的文档id）
  const getSnowflakeId = async () => {
    let id: string = '';
    let status: number = 0; //与父级的状态码参数一致
    await SnowflakeID()
      .then((res) => {
        id = res?.id;
      })
      .catch((item) => {
        status = 3;
      });
    return {
      id: id,
      status: status,
    };
  };

  //点击按钮后的弹窗遮罩
  const editLoading = () => {
    let text = '编辑';
    text = readOnly ? '查看' : '编辑';
    Modal.info({
      title: `文档编辑器打开中，请在弹出窗口${text}正文`,
      okText: <></>,
      okButtonProps: { hidden: true },
      cancelButtonProps: { hidden: true },
      centered: true,
    });
  };

  /**
   * 文字显示初始化和fileCode存储
   */
  const updateWebOffice = async () => {
    let errorStatus = 0; //错误状态码参数 0-正常 1-未安装控件提示下载 2-状态为查看但未获取到docFileCode 3-获取雪花id接口报错
    //判断安装环境
    if (!window.ntkoBrowser.ExtensionInstalled()) {
      setRenderCode(1); //错误类型为1，即未安装控件
      return;
    }
    //WORD文档部分
    if (
      DOCFileCode == '' ||
      DOCFileCode == null ||
      DOCFileCode == undefined ||
      DOCFileCode == 'null' ||
      DOCFileCode == 'undefined'
    ) {
      if (readOnly) {
        setBtnName('查看');
        setRenderCode(2); //错误类型为2，即状态为查看但未获取到docFileCode
        return;
      } else {
        setBtnName('新建');
        setBeforeBtnText('无正文内容，点击');
        //无doc文档id,获取雪花id
        await getSnowflakeId().then((res) => {
          setDocFileCode_(res?.id);
          errorStatus = res?.status;
        });
      }
    } else {
      let name = readOnly ? '查看' : '编辑';
      setBtnName(name);
      setBeforeBtnText('已保存正文内容，点击');
      //doc状态更新
      await getFileBidList(DOCFileCode).then((res) => {
        if (res?.length > 0) {
          setUploadDocType_(true);
        } else {
          setUploadDocType_(false);
        }
      });
    }
    //PDF文档部分
    if (savePDF) {
      if (
        PDFFileCode == '' ||
        PDFFileCode == null ||
        PDFFileCode == undefined ||
        PDFFileCode == 'null' ||
        PDFFileCode == 'undefined'
      ) {
        //无pdf文档id,获取雪花id
        await getSnowflakeId().then((res) => {
          setPdfFileCode_(res?.id);
          errorStatus = res?.status;
        });
      } else {
        //pdf状态更新
        await getFileBidList(PDFFileCode).then((res) => {
          if (res?.length > 0) {
            setUploadPDFType_(true);
          } else {
            setUploadPDFType_(false);
          }
        });
      }
    }
    //HTML文档部分
    if (saveHTML) {
      if (
        HTMLFileCode == '' ||
        HTMLFileCode == null ||
        HTMLFileCode == undefined ||
        HTMLFileCode == 'null' ||
        HTMLFileCode == 'undefined'
      ) {
        //无html文档id,获取雪花id
        await getSnowflakeId().then((res) => {
          setHtmlFileCode_(res?.id);
          errorStatus = res?.status;
        });
      } else {
        //pdf状态更新
        await getFileBidList(HTMLFileCode).then((res) => {
          if (res?.length > 0) {
            setUploadHTMLType_(true);
          } else {
            setUploadHTMLType_(false);
          }
        });
      }
    }
    //最终渲染规则
    setRenderCode(errorStatus);
  };

  //接收子页面返回参数方法
  const receiveMessage = async (event: any) => {
    if (event !== undefined && event?.data) {
      /*文件保存状态*/
      if (event?.data != null && event?.data != undefined) {
        let FileMsg = event?.data;
        if (FileMsg?.type == 'FROM_RETURN_DOC' && FileMsg?.text == docFileCode_) {
          //回调参数DOC专用标记
          setUploadDocType_(true);
          //调用回调方法（可能没有）
          afterSaveFunc();
          setBeforeBtnText('已保存正文内容，点击');
          setBtnName('编辑');
        } else if (FileMsg?.type == 'FROM_RETURN_HTML' && FileMsg?.text == htmlFileCode_) {
          //回调参数HTML专用标记
          setUploadHTMLType_(true);
        } else if (FileMsg?.type == 'FROM_RETURN_PDF' && FileMsg?.text == pdfFileCode_) {
          //回调参数PDF专用标记
          setUploadPDFType_(true);
        } else if (
          FileMsg?.type == 'FROM_NTKO_CLOSE' &&
          FileMsg?.text == window.ntkoBrowser.thisNTKOGUID
        ) {
          Modal.destroyAll();
        }
      }
    }
  };

  return (
    <div>
      {renderCode == 0 ? (
        <>
          <span>{beforeBtnText}</span>&nbsp;&nbsp;
          <Button
            size="small"
            key="openWebOffice"
            onClick={() => {
              editLoading();
              let openUrl = '/webofficeIeComponent';
              if (window.ntkoBrowser.NtkoBrower()) {
                //判断浏览器
                openUrl = '/webofficeComponent';
              }
              openUrl += `.html?readonly=${readOnly}&DocfileCode=${docFileCode_}&PDFfileCode=${pdfFileCode_}&HTMLfileCode=${htmlFileCode_}&savePDF=${savePDF}&saveHTML=${saveHTML}`;
              window.ntkoBrowser.openWindow(openUrl);
            }}
          >
            {btnName}
          </Button>
        </>
      ) : renderCode == 1 ? (
        <div>
          <span>
            您尚未安装文档控件，请您点击&nbsp;
            <Button
              key="download"
              size="small"
              onClick={() =>
                (window.location.href = '/officecontrol/NTKO控件安装程序-联通数字科技有限公司.exe')
              }
            >
              下载
            </Button>
            &nbsp;并安装后，重新访问当前页面
          </span>
        </div>
      ) : renderCode == 2 ? (
        <div>
          <span>无正文内容</span>
        </div>
      ) : renderCode == 3 ? (
        <div>
          <span>新建正文内容参数获取失败，请联系管理员</span>
        </div>
      ) : (
        <div style={{ height: '24px' }}>
          <LoadingOutlined />
          &nbsp;&nbsp;文档控件加载中，请稍等···
        </div>
      )}
    </div>
  );
};

export default WebOffice0609;
