import React, { useState, useEffect } from 'react';
import { IconFont, LabelValue, AuthComponent } from '@zenview/micro-components'
import { cache, SocketEmitter } from '@zenview/micro-utils'
import { LMConfig } from '@zenview/micro-basic-library'
import { Modal, Input, Button, message } from 'antd'
import Service from './service'
import { observer, useLocalStore } from "mobx-react"
import PersonDetailStore from './store'
import './index.less'

// micro-component

const cacheDesInfoObj = {
  isDesensitization: 'isDesensitization',
  desensitizationTime: 'desensitizationTime',
}

const EventNames = {  // eslint-disable-line
  refreshDesensitization:'refreshDesensitization'//脱敏刷新人员
}

let closeEyesTimer = null
export const DesensitizationInformation = observer(({ name, val = '', noName, noEye = true, RSA }) => {
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [userPassword, setUserPassword] = useState('')
  const pageStore = useLocalStore(() => PersonDetailStore.getInstance())
  const DefaultDesensitizationTimer = LMConfig?.BSConfig?.desensitizationTime ? Number(LMConfig?.BSConfig?.desensitizationTime) * 1000 : 1000 * 60 * 5
  // console.log('默认脱敏时间', DefaultDesensitizationTimer / 1000 + '秒')

  const ModalClick = () => {
    const desensitizationTime = cache.getCache(cacheDesInfoObj.desensitizationTime, 'session')
    const isOverdue = Number(desensitizationTime) - new Date().getTime() > 0

    // console.log(isOverdue)
    // window.sessionStorage?.isDesensitization只要存在，不管是true还是false都不需要重新请求
    // 除非设置时间过期
    if (window.sessionStorage[cacheDesInfoObj.isDesensitization] && isOverdue) {
      SocketEmitter.emit(EventNames.refreshDesensitization, {});
      cache.setCache(cacheDesInfoObj.isDesensitization, true, 'session')
      pageStore.setDesensitizationFun(true)

      closeEyesTimer = setTimeout(() => {
        SocketEmitter.emit(EventNames.refreshDesensitization, {});
        cache.setCache(cacheDesInfoObj.isDesensitization, false, 'session')
        pageStore.setDesensitizationFun(false)
      }, DefaultDesensitizationTimer) // 5分钟后，页面中所有字段眼睛自动关闭，防止信息泄漏；
    } else {
      setIsModalVisible(true)
      setUserPassword('')
    }
  }

  const handleCancel = () => {
    setIsModalVisible(false)
    setUserPassword('')
  }

  const CloseDesensitization = () => {
    cache.setCache(cacheDesInfoObj.isDesensitization, false, 'session')
    SocketEmitter.emit(EventNames.refreshDesensitization, {});
    pageStore.setDesensitizationFun(false)
    clearTimeout(closeEyesTimer)
  }

  const ok = async (RSA) => {
    const password = await Service.getPwKey(userPassword, RSA)

    // local中有isDesensitization字段说明已经请求过了，没有的情况下请求
    const userId = cache.getCache('userId', 'session')
    Service.desensitization({
      userId,
      userPassword: password
    }).then((res) => {
      if (+res.code === 0) {
        SocketEmitter.emit(EventNames.refreshDesensitization, {});
        pageStore.setDesensitizationFun(true)
        cache.setCache(cacheDesInfoObj.isDesensitization, true, 'session')
        cache.setCache(cacheDesInfoObj.desensitizationTime, new Date().getTime() + DefaultDesensitizationTimer, 'session')
        setIsModalVisible(false)

        closeEyesTimer = setTimeout(() => {
          cache.setCache(cacheDesInfoObj.isDesensitization, false, 'session')
          pageStore.setDesensitizationFun(false)
        }, DefaultDesensitizationTimer) // 5分钟后，页面中所有字段眼睛自动关闭，防止信息泄漏；

        setUserPassword('')
        // setTimeout(() => {
        //   window.sessionStorage.removeItem(cacheDesInfoObj.isDesensitization)
        //   window.sessionStorage.removeItem(cacheDesInfoObj.desensitizationTime)
        //   pageStore.setDesensitizationFun(false)
        // }, DefaultDesensitizationTimer) // 用户持续15分钟不操作系统，则页面锁定，需要再次输入登录密码
      } else {
        message.error(res.message)
      }
    })
  }

  // 脱敏值转换
  const changeTheValue = (t) => {
    let isHideText = t
    if (Number(t.replace(/\*/g, ''))) { // 证件号码，手机号脱敏
      const middleNum = t?.length >= 7 ? t?.length - 7 : 1
      const middleText = new Array(middleNum).toString().split(',').map(() => '*').join('')
      isHideText = t?.substring(0, 3) + middleText + t?.substring(t.length - 4)
    } else { // 姓名脱敏
      const middleNum = t?.length > 1 ? t?.length - 1 : 100
      isHideText = t.length === 1 ? t : t?.substring(0, 1) + (middleNum !== 100 ? new Array(middleNum).toString().split(',').map(() => '*').join('') : '')
    }
    return pageStore.state.isDesensitization ? t : isHideText
  }

  const desensitizationText = changeTheValue(val) || '暂无'

  let Default = null
  if (name.includes('人') || name.includes('电话') || name.includes('号码') || name === '手机号' || name.includes('姓名')) {
    Default = <div className="desensitization-information" key={name}>
      <div className="d-i-num">
        {
          noName ? desensitizationText : <LabelValue
            key={name}
            label={name}
            className="info-num"
            value={desensitizationText}
            emptyValue="暂无"
            fontSize={12}
          />
        }
      </div>
      {
        !noEye && desensitizationText !== '暂无' ? (
          pageStore.state.isDesensitization ? <div className="d-i-icon" onClick={() => CloseDesensitization()}>
            <IconFont type={'icon-xianshi'}></IconFont>
          </div> :
            <div className="d-i-icon" onClick={() => ModalClick()}>
              <IconFont type={'icon-yincang'}></IconFont>
            </div>
        ) : <></>
      }
      <Modal title="安全校验" visible={isModalVisible} onCancel={()=> handleCancel()}
        width={280}
        footer={[
          <Button key="back" type="primary" onClick={() => ok(RSA)}>
            提交
          </Button>
        ]}
      >
        <>
          <div>请输入用户密码</div>
          <Input type="password" placeholder="请输入登录密码" onChange={(e) => setUserPassword(e.target.value)} />
        </>
      </Modal>
    </div>
  }
  return Default
})

// 查看脱敏信息按钮
export const QueryDesensitizationButton = observer((props) => {
  const [buttonState, setButtonState] = useState(true)
  const [userPassword, setUserPassword] = useState(false)
  const [isModalVisible, setIsModalVisible] = useState(false)
  const pageStore = useLocalStore(() => PersonDetailStore.getInstance())
  const DefaultDesensitizationTimer = LMConfig?.BSConfig?.desensitizationTime ? Number(LMConfig?.BSConfig?.desensitizationTime) * 1000 : 1000 * 60 * 5
  const modalRef = React.useRef()
  const { RSA } = props

  useEffect(() => {
    const isDesensitization = cache.getCache(cacheDesInfoObj.isDesensitization, 'session')
    setButtonState(!isDesensitization)
  }, [])

  const StateChangeHandle = () => {
    if (buttonState) {
      ModalClick()
    } else {
      CloseDesensitization()
    }
  }

  const ModalClick = () => {
    const desensitizationTime = cache.getCache(cacheDesInfoObj.desensitizationTime, 'session')
    const isOverdue = Number(desensitizationTime) - new Date().getTime() > 0

    // console.log(isOverdue)
    // window.sessionStorage?.isDesensitization只要存在，不管是true还是false都不需要重新请求
    // 除非设置时间过期
    if (window.sessionStorage[cacheDesInfoObj.isDesensitization] && isOverdue) {
      SocketEmitter.emit(EventNames.refreshDesensitization, {});
      cache.setCache(cacheDesInfoObj.isDesensitization, true, 'session')
      pageStore.setDesensitizationFun(true)
      setButtonState(!buttonState)

      closeEyesTimer = setTimeout(() => {
        SocketEmitter.emit(EventNames.refreshDesensitization, {});
        cache.setCache(cacheDesInfoObj.isDesensitization, false, 'session')
        pageStore.setDesensitizationFun(false)
      }, DefaultDesensitizationTimer) // 5分钟后，页面中所有字段眼睛自动关闭，防止信息泄漏；
    } else {
      setIsModalVisible(true)
      setUserPassword('')
    }
  }

  const handleCancel = () => {
    setIsModalVisible(false)
  }

  const CloseDesensitization = () => {
    cache.setCache(cacheDesInfoObj.isDesensitization, false, 'session')
    SocketEmitter.emit(EventNames.refreshDesensitization, {});
    pageStore.setDesensitizationFun(false)
    clearTimeout(closeEyesTimer)
    setButtonState(!buttonState)
  }

  const ok = async (RSA) => {
    const password = await Service.getPwKey(userPassword, RSA)

    // local中有isDesensitization字段说明已经请求过了，没有的情况下请求
    const userId = cache.getCache('userId', 'session')
    Service.desensitization({
      userId,
      userPassword: password
    }).then((res) => {
      if (+res.code === 0) {
        SocketEmitter.emit(EventNames.refreshDesensitization, {});
        pageStore.setDesensitizationFun(true)
        cache.setCache(cacheDesInfoObj.isDesensitization, true, 'session')
        cache.setCache(cacheDesInfoObj.desensitizationTime, new Date().getTime() + DefaultDesensitizationTimer, 'session')
        setIsModalVisible(false)

        closeEyesTimer = setTimeout(() => {
          cache.setCache(cacheDesInfoObj.isDesensitization, false, 'session')
          pageStore.setDesensitizationFun(false)
          setIsModalVisible(false)
        }, DefaultDesensitizationTimer) // 5分钟后，页面中所有字段眼睛自动关闭，防止信息泄漏；
        setButtonState(!buttonState)
        // setTimeout(() => {
        //   window.sessionStorage.removeItem(cacheDesInfoObj.isDesensitization)
        //   window.sessionStorage.removeItem(cacheDesInfoObj.desensitizationTime)
        //   pageStore.setDesensitizationFun(false)
        // }, DefaultDesensitizationTimer) // 用户持续15分钟不操作系统，则页面锁定，需要再次输入登录密码
      } else {
        message.error(res.message)
      }
    })
  }

  return <AuthComponent actionName='queryDesensitizationInformation'>
    <div ref={modalRef}>
      <div onClick={(e) => { StateChangeHandle() }} className="query-desensitization-button">
          <IconFont type={buttonState ? 'icon-xianshi' : 'icon-yincang'} className="query-desensitization-icon"></IconFont>
          <span className="query-desensitization-text">{buttonState ? '查看脱敏信息' : '隐藏脱敏信息'}</span>
      </div>
      <Modal
        title="安全校验"
        visible={isModalVisible}
        onCancel={() => handleCancel()}
        getContainer={()=> modalRef && modalRef.current}
        width={280}
        footer={[
          <Button key="back" type="primary" onClick={() => ok(RSA)}>
            提交
          </Button>
        ]}
      >
        <>
          <div style={{ paddingBottom: '10px' }}>请输入用户密码</div>
          <Input type="password" value={userPassword} placeholder="请输入登录密码" onChange={(e) => setUserPassword(e.target.value)} />
        </>
      </Modal>
    </div>
  </AuthComponent>


})

// 无状态文字脱敏
export const desensitizationByState = (t) => {
  let isHideText = t
  let textState = cache.getCache(cacheDesInfoObj.isDesensitization, 'session')
  if (Number(t.replace(/\*/g, ''))) { // 证件号码，手机号脱敏
    const middleNum = t?.length >= 7 ? t?.length - 7 : 1
    const middleText = new Array(middleNum).toString().split(',').map(() => '*').join('')
    isHideText = t?.substring(0, 3) + middleText + t?.substring(t.length - 4)
  } else { // 姓名脱敏
    const middleNum = t?.length > 1 ? t?.length - 1 : 100
    isHideText = t.length === 1 ? t : t?.substring(0, 1) + (middleNum !== 100 ? new Array(middleNum).toString().split(',').map(() => '*').join('') : '')
  }
  return textState ? t : isHideText
}

export const getInfo = (name, val) => {
  return <DesensitizationInformation noName={true} name={name} val={val} key={name}></DesensitizationInformation>
};

export default {
  DesensitizationInformation,
  QueryDesensitizationButton,
  desensitizationByState,
  getInfo
}