import React, { useEffect, useRef, useState } from 'react'
import Button from 'antd/lib/button'
import { Drawer, message, Modal, Skeleton, Spin } from 'antd'
import { CloseOutlined, ExclamationCircleFilled, QuestionOutlined } from '@ant-design/icons'
import { debounce } from 'lodash'
import './index.scss'
import FlowProcess from '../FlowProcess'
import { Api, SchemaNode } from '../../../types'
import { FlowButtonUI, FlowDetail } from '../type'
import { RendererEnv } from '../../../env'
import { ImageThumbProps } from '../../../renderers/Image'
import { isMobile } from '../../../utils/helper'
import { Icon } from '../../icons'
import { copy } from '../../../renderers/Lion/utils/utils'
import { tools } from '../../../utils/shell/tools'

const statusObj = {
  submit: '提交申请',
  waiting: '待签核',
  doing: '签核中',
  revert: '撤销',
  refuse: '拒绝',
  pass: '通过',
  return: '退回'
}
interface FlowModalProps {
  visible: boolean
  render: (region: string, node: SchemaNode, props?: any) => JSX.Element
  onClose: (reload: boolean) => void
  env: RendererEnv
  flowDetail?: FlowDetail
  onImageEnlarge: (
    info: Pick<ImageThumbProps, 'src' | 'originalSrc' | 'title' | 'caption'> & {
      index?: number;
      list?: Array<
        Pick<ImageThumbProps, 'src' | 'originalSrc' | 'title' | 'caption'>
      >;
    }
  ) => void;
  language: (data: string) => string
  classnames: (...args: any[]) => string;
  flowPrintTempApi?: Api
  flowPrintDataApi?: Api
}

const ModalFlow: React.FC<FlowModalProps> = (props) => {
  const {
    visible,
    render,
    onClose,
    env,
    flowDetail,
    onImageEnlarge,
    language,
  } = props
  const Mobile: boolean = isMobile()
  // 移动端按钮
  const [form, setForm] = useState<any>();

  const [visibleOpen, setVisibleOpen] = useState(false)
  const replacedString = flowDetail?.flowDesc?.replace(/\r\n/g, '<br>');
  const [spinning, setSpinning] = useState(false)
  const currentaudit = (value: string, title = '', titletype = false) => {

    if (title !== 'doneItem' || titletype) {
      switch (value) {
        case "doing":
          // 待审批
          return <span className={`process_content_icon ${!Mobile ? 'process_content_' + value : ""}`}>
            {Mobile ? <Icon icon={"under-approval"} className="icon" /> : '签核中'}
          </span>
        case "refuse":
          // 已拒绝
          return <span className={`process_content_icon ${!Mobile ? 'process_content_' + value : ""}`}>
            {Mobile ? <Icon icon={"refuse"} className="icon" /> : '已拒绝'}
          </span>
        case "pass":
          // 已通过
          return <span className={`process_content_icon ${'process_content_' + value}`}>
            {Mobile ? <Icon icon={"passed"} className="icon" /> : '已通过'}
          </span>
        case "revert":
          // 已撤回
          return <span className={`process_content_icon ${'process_content_' + value}`}>
            {Mobile ? <Icon icon={"withdrawn"} className="icon" /> : '已撤回'}
          </span>
        case "return":
          // 已退回
          return <span className={`process_content_icon ${'process_content_' + value}`}>
            {Mobile ? <Icon icon={"returnicon"} className="icon" /> : '已退回'}
          </span>
        default:
          // 未定义
          return <span >
            {value}
          </span>
      }
    } else {
      switch (value) {
        case "refuse":
          // 已拒绝
          return <span className={`process_content_icon ${'process_content_' + value}`}>
            <Icon icon={"rejected-icon"} className="icon" />
          </span>
        case "pass":
          // 已通过
          return <span className={`process_content_icon ${'process_content_' + value}`}>
            <Icon icon={"passed-icon"} className="icon" />
          </span>
        case "revert":
          // 已撤回
          return <span className={`process_content_icon ${'process_content_' + value}`}>
            <Icon icon={"refuse-icon"} className="icon" />
          </span>
        case "return":
          return <span className={`process_content_icon ${'process_content_' + value}`}>
            <Icon icon={"return-icon"} className="icon" />
          </span>
        default:
          // 未定义
          return <span >
          </span>
      }
    }
  }
  // 抽屉头部
  const handleTltle = (flowDetail: FlowDetail) => {
    return flowDetail ? <>
      <div className={`detailed_title ${!Mobile ? "detailed_border detailed_Mobile" : ""}`}>
        {/* 左 */}
        <div className='detailed_title_left'>
          {/* 头像 */}
          <div className='detailed_title_img_text'>
            <span className='detailed_title_img'>
              <Icon icon='camera' className="icon"></Icon>
            </span>
            {/* 标题 */}
            <span className='detailed_title_text'>
              {flowDetail && flowDetail.flowProcess.processDefinitionName}
            </span>
          </div>
          {/* icon */}
          {flowDetail && currentaudit(flowDetail.flowProcess.processStatus)}
        </div>
        {/* 右 */}
        <div className='detailed_title_right'></div>
      </div>

      <div className='characteristic'>
        {language('Flow.approval.id') + ":" + flowDetail?.flowProcess.approvalNo}
        <Button type="text"
          icon={<Icon icon={"copy"} className="icon" size />}
          size='small'
          className="characteristic_but"
          onClick={() => {
            copy(flowDetail?.flowProcess.approvalNo).then((_) => {
              message.success(language('System.copy'))
            })
          }}
        />
      </div>
    </> : <Skeleton avatar paragraph={{ rows: 5 }} />
  }
  const handleHeader = () => {
    return (
      flowDetail ? <div className={`flow-drawer-header ${!Mobile ? 'flow-drawer-header-mobile' : ''}`}>
        {Mobile && <div className='left-text' onClick={() => onClose(false)}>
          <Icon icon="title-left" style={{ width: '16px', height: '16px' }} />
        </div>
        }
        <div className="flow-drawer-header-title">
          <div className="flow-drawer-title">
            {tools.isComWx ? (Mobile ? '' : (flowDetail && handleTltle(flowDetail))) :
              Mobile ? language('Flow.editDetail') : (flowDetail && handleTltle(flowDetail))}
          </div>
        </div>
        <div className="flow-drawer-extra">
          {!Mobile && <>
            <div className='flow-drawer-icon'>
              <span className='right-text-icon' onClick={infoDetails}>
                <QuestionOutlined />
              </span>
              <span className="right-text">
                {
                  <div style={{ fontSize: '17px', cursor: 'pointer' }}
                    onClick={() => { onClose(false) }}>
                    <CloseOutlined />
                  </div>
                }
              </span>
            </div>
            <div className='flow-drawer-file'>
              <span className='right-text-icon'>
                {/* <Icon icon={"printfile"} className="icon" /> */}
              </span>
              <span className='right-text-icon' onClick={() => handlePrint()}>
                <Icon icon={"print"} className="icon" />
              </span >
            </div>
          </>}
        </div>
      </div>
        :
        <Skeleton avatar paragraph={{ rows: 2 }} />
    )
  }

  // 发起请求
  const handleRadios = debounce(async (api: Api, spin: boolean) => {
    spin && setSpinning(true)
    let data: any = {
      ...(flowDetail && flowDetail.flowProcess)
    }
    const res = await env.fetcher(api, data).finally()
    if (res.status === 0) {
      onClose(true)
    } else {
      message.error(res.msg)
    }
    spin && setSpinning(false)
  }, 600)

  // 确定按钮文字 二次确定
  const showModal = (item: FlowButtonUI) => {
    if (item.name == "flow_cancel") {
      onClose(false)
      return
    }
  };

  const InPosition = () => {
    const data = flowDetail?.processNodeList.find(item => item.nodeStatus === "doing")
    if (data) {
      return `${language('Flow.process.to')}${data.nodeName}，${language('Flow.withdraw')}？`
    } else {
      return `${language('Flow.the.process.has.ended')}，${language('Flow.withdraw')}？`
    }
  }

  // 底部按钮
  const handleFooter = () => {
    return (
      flowDetail ? <div className={`handling_opinions`}>
        {/* 按钮 */}
        <Spin spinning={spinning} indicator={<></>}>
          {
            flowDetail?.flowButtonList?.map((item, index) => {
              return (
                <Button
                  className={`flowButtonList_button ${item.name}`}
                  onClick={() => {
                    showModal(item)
                    item.name == 'flow_revert' && info(item)
                    item.name == 'flow_urge' && infoUrge(item)
                  }}
                  type="primary"
                  key={index}>
                  {item.label}
                </Button>
              )
            })
          }
        </Spin>
      </div> : <></>
    )
  }
  // 撤回按钮
  const info = (item: FlowButtonUI) => {
    Modal.confirm({
      // '确认撤回当前表单'
      title: '确认撤回当前表单',
      content: (
        isMobile() ? '' :
          <div style={{ clear: 'both', paddingLeft: 14 }}>
            <p >
              {InPosition()}
            </p>
          </div>
      ),
      centered: true,
      icon: <ExclamationCircleFilled style={{ color: "#FDA71E", fontSize: 36 }} />,
      async onOk() {
        await handleRadios(item.api, true)
      },
      getContainer: env.getModalContainer,
      zIndex: 1010,
      className: `${isMobile() ? 'infoModalConfirm' : ''}`,
      okText: language('Flow.determine'),
      cancelText: language('cancel'),

      okButtonProps: {
        style: {
          background: '#FDA71E', // 自定义背景颜色
          color: 'white', // 自定义文字颜色
          borderColor: '#FDA71E', // 自定义边框样式\
          borderRadius: '4px',
        },
      },
    });
  };
  // 催办按钮
  const infoUrge = (item: FlowButtonUI) => {
    Modal.confirm({
      // // '确认撤回当前表单'
      title: '是否催办当前表单',
      async onOk() {
        await handleRadios(item.api, false)
      },
      getContainer: env.getModalContainer,
      zIndex: 1011,
      centered: true,
      className: `${isMobile() ? 'infoModalConfirm' : ''}`,
      icon: <></>,
      okText: language('Flow.determine'),
      cancelText: language('cancel')
    });
  };

  const infoDetails = () => {
    Modal.info({
      content: (
        <div className='custom-modal-container-body'>
          <div dangerouslySetInnerHTML={{
            __html: replacedString || ''
          }}>
          </div>
        </div>
      ),
      icon: <></>,
      className: 'custom-modal-container',
    });
  };

  const handlePrint = () => {
    if (flowDetail) {
      form.handleAction(undefined, {
        actionType: "form-print",
        type: "button",
        level: "info",
        name: Math.random().toString(),
        label: "打印",
        printInfo: {
          title: flowDetail.flowProcess.processDefinitionName,
          subTitle: statusObj[flowDetail.flowProcess.processStatus] ?? flowDetail.flowProcess.processStatus,
          extraTitle: `审批编号:${flowDetail.flowProcess.approvalNo}`,
          printFlow: true
        }
      })
    }
  }

  return (<>
    {visible &&
      <Drawer
        style={Mobile ? {} : {
          height: 'calc(100vh - 50px)',
          top: '50px'
        }}
        maskClosable
        className={`process_drawer flow_dom_drawer ${Mobile ? 'mobile' : 'pc'}`}
        closable={false}
        width={Mobile ? "100%" : '100%'}
        visible={visible}
        onClose={() => onClose(false)}
        getContainer={env.getDrawerContainer}
        destroyOnClose={true}
        zIndex={Mobile ? 1010 : 9}
        footer={handleFooter()}
        placement="right"
        bodyStyle={{ overflow: 'hidden' }}
      >
        <Spin spinning={spinning} indicator={<></>}>
          {handleHeader()}
        </Spin>
        <Spin spinning={spinning} tip='请稍后...'>
          {flowDetail ?
            <FlowProcess getFilterForm={setForm} render={render} flowDetail={flowDetail} env={env} onImageEnlarge={onImageEnlarge} language={language} visibleOpen={visibleOpen} handleVisible={(body) => setVisibleOpen(body)} />
            :
            <Skeleton paragraph={{ rows: 20 }} />
          }
        </Spin>
      </Drawer>
    }
  </>
  )
}

export default ModalFlow