import { Button, message, Radio, Spin } from 'antd';
import React, { useCallback, useEffect, useLayoutEffect, useState } from 'react';
import { getCode, getDingKey, ddlogin, phoneLogin, selectCompanyApi, getNoteCode, getEmailNoteCodeApi, emailLoginApi } from './API';
import styles from './index.less';
import { CopyrightOutlined, SwapRightOutlined } from '@ant-design/icons';
import Bg from './components/bg';
import loginStore from './store/loginStore';
import { observer, useLocalObservable } from 'mobx-react';
import { useSearchParams } from 'react-router-dom'
import globaStore from '@/store/index'
import { toJS } from 'mobx';
import { useAjax } from '@/Hook/useAjax';
import { getMenu } from '@/API';


/**
 * 退出登录，并且将当前的 url 保存
 */


const Login: React.FC<{}> = () => {
  const store = useLocalObservable(() => { return { loginStore, globaStore } })
  const [values, setValues] = useState<{ phone: string, code: string }>({ phone: '', code: '' })
  const [emailData, setEmailData] = useState<{ email: string, code: string }>({ email: '', code: '' })
  const [isLogin, setIsLogin] = useState<boolean>(false)
  const [videoMenu, setVideoMenu] = useState<{ visible: boolean, left?: number, top?: number }>({ visible: false, left: 0, top: 0 })
  const [show, setShow] = useState<boolean>(false)
  const [tab, setTab] = useState<1 | 2 | 3>(1)
  const [APPID,] = useState<string>(process.env.CONFIG.DDAPPID)//测试 dingdsfuoevmawlyyrjx  线上dingwfmhucedfluenpuj
  const [REDIRECT_URI,] = useState<string>(encodeURIComponent(window.location.href?.split('?')[0]))
  const [companyList, setCompanyList] = useState<any[]>([])
  const [loading, setLoading] = useState<boolean>(false)
  const [isMobile, setIsMobile] = useState<boolean>(false)
  const [m, setM] = useState<any>(0)//倒计时，0可以点击
  const [urlParams] = useSearchParams(window.location.search)//query获取
  const get_Menu = useAjax(() => getMenu())
  const [feasible, setFeasible] = useState(true)//是否浏览器内核大于87
  const [codeType, setCodeType] = useState(1)//1钉钉验证码 2短信验证码
  const getEmailNoteCode = useAjax((phone) => getEmailNoteCodeApi(phone))//短信验证码
  const emailLogin = useAjax((params: any) => emailLoginApi(params))//用邮箱登录

  // token登录
  useEffect(() => {
    let hash = window.location.hash || window.location.search
    console.log('hash', hash)
    if (hash?.includes('token')) {
      let str = hash.split('?')[1]
      let arr = str.split('&')
      let obj: any = {
        token: '',
        olderp: '',
        path: ''
      }
      arr.forEach(s => {
        obj[s.split('=')[0]] = s.split('=')[1]
      })
      if (obj.token) {
        localStorage.setItem('Admin-Token', obj.token)
        if (obj.path) {
          location.href = decodeURIComponent(obj.path)
        } else {
          location.href = location.origin
        }
      }
    }
  }, [])
  // 同步添加头部跨域问题
  useLayoutEffect(() => {
    if (!document.getElementById('referrer')) {
      let meta = document.createElement('meta')
      meta.name = 'referrer'
      meta.content = "no-referrer"
      meta.id = 'referrer'
      document.head.appendChild(meta)
    }
  }, [])
  //添加钉钉事件
  useLayoutEffect(() => {
    let DD = document.getElementById('DDlogin')
    if (!DD) {
      let script = document.createElement('script')
      script.src = 'https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js'
      script.id = 'DDlogin'
      document.head.appendChild(script)
    }
  }, [])
  // 获取运行环境
  useEffect(() => {
    let u = navigator.userAgent
    let isPhone = !!u.match(/AppleWebKit.*Mobile.*/) || u.indexOf('iPad') > -1
    if (isPhone) {
      setTab(1)
      setIsMobile(isPhone)  // 判断是否在移动端
      sessionStorage.setItem('isPhone', 'true')
    }
  }, [])
  // 查看是否已登录
  useEffect(() => {
    let AdminToken = localStorage.getItem('Admin-Token')
    if (AdminToken) {
      if (JSON.stringify(toJS(store.globaStore.data.menus)) !== '{}') {
        console.log(toJS(store.globaStore.data.menus))
        let menus: any = Object.values(toJS(store.globaStore.data.menus)).sort((a: any, b: any) => { return a[0]?.orderNum - b[0]?.orderNum })
        menus = menus?.filter((item: string | any[]) => item?.length > 0)
        window.location.href = window.location.origin + menus[0][0].path
      } else {
        store.globaStore.userInit()
      }
    }
  }, [store.globaStore.data.menus])
  // 获取公司列表
  useEffect(() => {
    let data = store.globaStore.data.companyList
    if (data && Object.keys(data).length > 0) {
      setCompanyList(() => data as any)
    }
  }, [store.globaStore.data.companyList])

  //显示隐藏登录
  let handleShow = useCallback((props?: boolean) => {
    if (props && !show) {
      console.log('显示1')
      setShow(true)
    }
    if (!props && show) {
      console.log('关闭1')
      setShow(false)
    }
  }, [show])
  // 钉钉登录
  useEffect(() => {
    if (!localStorage.getItem('Admin-Token')) {
      let code: any = urlParams.get('code')
      let state: any = urlParams.get('state')
      if (code) {
        ddlogin({ code, state, stateKey: sessionStorage.getItem('DDK') }).then((msg: any) => {
          if (msg.code === 200) {
            localStorage.setItem('Admin-Token', msg?.data?.token)
            let companyInfo = msg?.data?.companyRelationInfo?.filter((item: { companyId: number }) => item.companyId !== 4 && item.companyId !== 3)
            setIsLogin(false)
            if (companyInfo?.length === 0) {
              localStorage.removeItem('Admin-Token')
              sessionStorage.removeItem('userId')
              message.error('登录失败，请用趣程运营平台账号登录')
              return
            } else if (companyInfo?.length === 1) {
              setCompanyHandle(msg?.data?.companyRelationInfo[0].companyId)
            } else {
              setCompanyList(companyInfo)
            }
            message.success('登录成功！');
            return;
          } else {
            setIsLogin(false)
            message.success('2秒后刷新页面,请重新扫码登录')
            setTimeout(() => {
              window.open(location?.origin, '_parent')
            }, 2000)
          }
        })
      } else {
        if (tab === 2) {
          let state = ''
          getDingKey().then((res) => {
            console.log('钉钉---->', res);

            let strArr = res?.data?.split('_')
            sessionStorage.setItem('DDK', strArr[0])
            state = strArr[1]
          });
          (window as any)?.DDLogin && (window as any).DDLogin({
            id: "login_container",
            goto: encodeURIComponent(`https://oapi.dingtalk.com/connect/qrconnect?appid=${APPID}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${REDIRECT_URI}`),
            style: "border:none;padding:0 0 20px 0;background-color:rgba(255,255,255,0.7);",
            width: "100%",
            height: "400"
          });
          const handleMessage = (event: { data: any; origin: any; }) => {
            // 获取loginTempCode
            const loginTempCode = event.data;
            // 获取消息来源
            const origin = event.origin;
            // 拼接 url
            const url = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${APPID}&response_type=code&scope=snsapi_login&state=${encodeURIComponent(state)}&redirect_uri=${REDIRECT_URI}&loginTmpCode=${loginTempCode}`
            // 如果来源为https://login.dingtalk.com，则在当前窗口打开回调链接
            if (origin === 'https://login.dingtalk.com') {
              window.open(encodeURI(url), '_parent')
            }
          }
          // 监听iframe的消息
          if (typeof window.addEventListener != 'undefined') {
            window.addEventListener('message', handleMessage, false);
          } else if (typeof (window as any).attachEvent != 'undefined') {
            (window as any).attachEvent('onmessage', handleMessage);
          }
        }
      }
    }

  }, [tab, (window as any)?.DDLogin])
  // 选择公司
  const setCompanyHandle = (companyId: number) => {
    setLoading(() => true)
    selectCompanyApi(companyId).then((res: any) => {
      setLoading(() => false)
      if (res?.code === 200) {
        localStorage.setItem('Admin-Token', res?.data?.token)
        get_Menu.run().then(res => {//跳转默认第一个权限路径
          let arr = Object.keys(res?.data)?.filter(key => res?.data[key]?.length > 0)
          let obj: any = {}
          arr.forEach(a => {
            obj[a] = res?.data[a]
          })
          let menus: any = Object.values(obj).sort((a: any, b: any) => { return a[0]?.orderNum - b[0]?.orderNum })
          let path = menus[0][0].path
          window.location.href = window.location.origin + path
        })
      }
    }).catch(() => setLoading(() => false))
  }
  // 更换账户
  const logOut = () => {
    store.globaStore.data.companyList = []
    store.globaStore.loginOut()
  }
  // 获取手机验证码
  const getPhoneCode = () => {
    let reg = new RegExp(/^(13\d|14[579]|15[^4\D]|17[^49\D]|18\d)\d{8}$/g)
    if (values?.phone) {
      // if (values?.phone.match(reg)) {
      setM(30)
      getCode(values?.phone).then(res => {
        message.success('获取成功，请查看你的钉钉消息！验证码将发送到钉钉')
        timeOut(30)
      }).catch(() => timeOut(0))
    } else {
      message.error('请输入正确的手机号！！！')
    }
  }
  // 获取手机短信验证码
  const getPhoneNoteCode = () => {
    let reg = new RegExp(/^(13\d|14[579]|15[^4\D]|17[^49\D]|18\d)\d{8}$/g)
    if (values) {
      setM(30)
      getNoteCode(values?.phone).then(res => {
        message.success('获取成功，请查看你的短信消息！验证码将以短信的形式发送到您的手机！')
        timeOut(30)
      }).catch(() => timeOut(0))
    } else {
      message.error('请输入正确的手机号！！！')
    }
  }
  // 倒计时
  const timeOut = useCallback((num: number) => {
    let timer: any = null
    if (num > 0) {
      timer = setTimeout(() => {
        setM(num - 1)
        timeOut(num - 1)
        clearTimeout(timer)
        timer = null
      }, 1000)
    } else {
      setM(0)
    }
  }, [])
  // 手机登录
  const phoneSubmit = () => {
    if (values?.code) {
      phoneLogin(values).then(res => {
        console.log('res', res)
        try {
          setIsLogin(false)
          localStorage.setItem('Admin-Token', res?.data?.token)
          let companyInfo = res?.data?.companyRelationInfo//?.filter((item: { companyId: number }) => item.companyId === 1)
          if (companyInfo?.length === 0) {
            localStorage.removeItem('Admin-Token')
            sessionStorage.removeItem('userId')
            message.error('登录失败，请用趣程运营平台账号登录')
            return
          } else if (companyInfo?.length === 1) {
            setCompanyHandle(res?.data?.companyRelationInfo[0].companyId)
          } else {
            setCompanyList(companyInfo)
          }
          // console.log("companyInfo===>",companyInfo)
          message.success('登录成功！');
          // 如果失败去设置用户错误信息
        } catch (error) {
          setIsLogin(false)
          message.error('登录失败，请重试！');
        }
      })
    }
  }

  // 获取游戏验证码
  const getEmailCode = () => {
    const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (emailData?.email && !regex.test(emailData.email)) {
      message.error('请输入正确的邮箱！！！')
      return
    }
    if (emailData) {
      setM(30)
      getEmailNoteCode.run(emailData?.email).then(res => {
        if (res.code === 200) {
          message.success('获取成功，请查看你的邮箱！验证码将以邮件的形式发送到您的邮箱！')
          timeOut(30)
        } else {
          timeOut(0)
        }
      }).catch(() => timeOut(0))
    } else {
      message.error('请输入邮箱地址！！！')
    }
  }

  // 邮箱登录
  const emailSubmit = () => {
    if (emailData?.code) {
      emailLogin.run(emailData).then(res => {
        try {
          if (res.code === 200) {
            setIsLogin(false)
            localStorage.setItem('Admin-Token', res?.data?.token)
            let companyInfo = res?.data?.companyRelationInfo?.filter((item: { companyId: number }) => item.companyId !== 4 && item.companyId !== 3)
            if (companyInfo?.length === 0) {
              localStorage.removeItem('Admin-Token')
              message.error('登录失败，请用趣程运营平台账号登录')
              return
            } else if (companyInfo?.length === 1) {
              setCompanyHandle(res?.data?.companyRelationInfo[0].companyId)
            } else {
              setCompanyList(companyInfo)
            }
            return;
          } else {
            setIsLogin(false)
          }
        } catch (error) {
          setIsLogin(false)
          message.error('登录失败，请重试！');
        }
      })
    }
  }

  // 判断浏览器内核
  useEffect(() => {
    let v = navigator.userAgent
    if (v.includes('Chrome')) {
      let cm = navigator.userAgent.match(/Chrome\/\d{2,3}/)
      if (cm && cm?.length > 0) {
        let n = cm[0].split('/')[1]
        if (Number(n) < 87) {
          setFeasible(false)
        }
      }
    }
  }, [])
  return (
    <>
      {
        feasible ? <>
          {/* {isOk?} */}
          <div className={styles.container} id='login'>
            <div className={styles.content}>

              {localStorage.getItem('Admin-Token') && companyList?.length > 0 ? <div className={`${styles.company}  ${isMobile ? '' : show ? '' : styles.login_hide}`}>
                <h1>趣程企微管理后台</h1>

                <div className={styles.companyAccount}>
                  <h3 className={styles.title}>请选择公司账户登录</h3>
                  <div className={styles.chooseTableBlock}>
                    <Spin spinning={loading}>
                      {
                        companyList?.map((item: any) => <div className={styles.acTableLine} key={item?.companyId} onClick={() => { setCompanyHandle(item.companyId) }}>
                          <div className={styles.actname}>{item?.companyInfo?.companyName}</div>
                          <div className={styles.right}> <div className={styles.actcha}>{item?.powerLevel === 999 ? '超级管理员' : item?.powerLevel === 100 ? '系统管理员' : item?.powerLevel === 99 ? '管理员' : '普通用户'}</div> <SwapRightOutlined className={styles.iconRight} /></div>
                        </div>)
                      }
                    </Spin>
                  </div>
                  <div className={styles.button}>
                    <Button type="link" onClick={logOut}>更换账号</Button>
                  </div>
                </div>

              </div> : <div className={`${styles.main}  ${isMobile ? '' : show ? '' : styles.login_hide}`} id='login_main'>
                <h1>趣程企微管理后台</h1>
                {<div className={styles.tabs}>
                  <span onClick={() => { setTab(1) }} style={tab === 1 ? { color: localStorage.getItem('color') || '#24DB95' } : {}}>手机</span>
                  <span onClick={() => { setTab(3) }} style={tab === 3 ? { color: localStorage.getItem('color') || '#24DB95' } : {}}>邮箱</span>
                  {/* <span onClick={() => { setTab(2) }} style={tab === 2 ? { color: localStorage.getItem('color') || '#24DB95' } : {}}>钉钉</span> */}
                </div>}

                {
                  tab === 1 ? <>
                    <div>
                      <input
                        className={styles.input}
                        name='phone'
                        placeholder='Phone'
                        value={values?.phone}
                        type='text'
                        autoComplete='on'
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                          let value = e.target.value
                          if (value === '背景') {
                            setVideoMenu({ visible: true })
                          }
                          setValues({ ...values, phone: value })
                        }}
                      />
                    </div>
                    <div>
                      <input
                        className={styles.input}
                        autoComplete='no'
                        placeholder='Code'
                        style={{ width: '60%' }}
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                          let value = e.target.value
                          setValues({ ...values, code: value })
                        }}
                        onKeyUp={(event: React.KeyboardEvent<HTMLInputElement>) => {
                          if (event.key === 'Enter') {
                            phoneSubmit()
                          }
                        }}
                      />
                      <button
                        className={styles.btn}
                        style={!m ? { background: localStorage.getItem('color') || '#24DB95' } : { background: '#999' }}
                        onClick={codeType === 1 ? getPhoneCode : getPhoneNoteCode}
                        disabled={!!m}
                      >
                        {!m ? '获取验证码' : m + '秒再次获取'}
                      </button>
                    </div>
                    <div>
                      <Radio.Group value={codeType} style={{ fontSize: 14 }} onChange={(e) => {
                        let v = e.target.value
                        setCodeType(v)
                      }}>
                        <Radio value={1} style={{ color: '#fff' }}>钉钉验证码</Radio>
                        <Radio value={2} style={{ color: '#fff' }}>手机验证码</Radio>
                      </Radio.Group>
                    </div>
                    <button
                      onClick={phoneSubmit}
                      disabled={isLogin}
                      style={{ background: localStorage.getItem('color') || '#24DB95' }}
                    >登录</button>
                  </> : tab === 3 ? <>
                    <div>
                      <input
                        className={styles.input}
                        placeholder='Email'
                        value={emailData?.email}
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                          let value = e.target.value
                          if (value === '背景') {
                            setVideoMenu({ visible: true })
                          }
                          setEmailData({ ...values, email: value })
                        }}
                      />
                    </div>
                    <div>
                      <input
                        className={styles.input}
                        placeholder='Code'
                        style={{ width: '60%' }}
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                          let value = e.target.value
                          setEmailData({ ...emailData, code: value })
                        }}
                        onKeyUp={(event: React.KeyboardEvent<HTMLInputElement>) => {
                          if (event.key === 'Enter') {
                            phoneSubmit()
                          }
                        }}
                      />
                      <button
                        className={styles.btn}
                        style={!m ? { background: localStorage.getItem('color') || '#24DB95' } : { background: '#999' }}
                        onClick={getEmailCode}
                        disabled={!!m}
                      >
                        {!m ? '获取验证码' : m + '秒再次获取'}
                      </button>
                    </div>
                    <button
                      onClick={emailSubmit}
                      disabled={isLogin}
                      style={{ background: localStorage.getItem('color') || '#24DB95' }}
                    >登录</button>
                  </> : <div id='login_container' />
                }
              </div>}
            </div>
            {/**背景 */}
            {!isMobile && <Bg data={videoMenu} open={setVideoMenu} show={handleShow} isShow={show} />}
            <footer className={`${styles.footer} ${show ? '' : styles.footer_hide}`} onClick={() => { setVideoMenu({ visible: !videoMenu.visible }) }}>
              <a >
                趣程
              </a>
              <span>Copyright<span><CopyrightOutlined /></span>趣程 </span>
            </footer>
          </div>
        </> : <>
          <div className={styles.container} id='login' >
            <div className={styles.content} style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }} >
              <div style={{ width: '50vw' }}>
                您的浏览器内核版本过低,不支持当前系统，请更新至最新版本！<br />
                360等杂牌浏览器技术内核无法支持最新CSS特性，推荐使用谷歌,火狐,Edge浏览器！
                <div style={{ display: 'flex', justifyContent: 'space-evenly', marginTop: 20 }}>
                  <Button style={{ cursor: 'pointer' }} onClick={() => window.open('https://www.google.cn/intl/zh-CN/chrome/')}>谷歌浏览器下载</Button>
                  <Button style={{ cursor: 'pointer' }} onClick={() => window.open('http://www.firefox.com.cn/')}>火狐浏览器下载</Button>
                  <Button type='link' onClick={() => window.open('https://www.microsoft.com/zh-cn/edge?form=MA13FJ')} style={{ cursor: 'pointer' }}>Edge浏览器下载</Button>
                </div>
              </div>
            </div>
          </div>
        </>
      }
    </>
  );
};

export default observer(Login);