import React, { useCallback, useEffect, useMemo, useRef } from 'react'
import styles from './index.module.scss'
import { Button, Form, FormInstance, Input, Modal } from 'antd'
import { MessageFu } from '@/utils/message'
import { Base64 } from 'js-base64'
import encodeStr from '@/utils/pass'
import { passWordEditAPI, passWordEditAPI2 } from '@/store/action/layout'
import store from '@/store'
import { loginExit } from '../data'
import { setTokenInfo } from '@/utils/storage'
import history from '@/utils/history'
import { defaultPassWord } from '@/utils/http'

type Props = {
  userTokenInfo?: any
}

function PassEdit({ userTokenInfo }: Props) {
  // 设置表单ref
  const FormBoxRef = useRef<FormInstance>(null)

  // 是否是从登录页面进来的，需求强制修改默认密码
  const flag = useMemo(() => {
    let flag = false
    if (userTokenInfo && userTokenInfo.token) flag = true
    return flag
  }, [userTokenInfo])

  useEffect(() => {
    if (flag) {
      FormBoxRef.current?.setFieldsValue({
        oldPassword: defaultPassWord
      })
    }
  }, [flag])

  // 拿到新密码的输入框的值
  const oldPasswordValue = useRef('')

  const checkPassWord = (rule: any, value: any = '') => {
    if (value !== oldPasswordValue.current) return Promise.reject('新密码不一致!')
    else return Promise.resolve(value)
  }

  const onFinish = useCallback(
    async (values: any) => {
      // 通过校验之后发送请求
      if (values.oldPassword === values.newPassword) return MessageFu.warning('新旧密码不能相同!')
      const obj = {
        oldPassword: encodeStr(Base64.encode(values.oldPassword)),
        newPassword: encodeStr(Base64.encode(values.newPassword))
      }
      const token = flag ? userTokenInfo.token : undefined
      const res: any = flag ? await passWordEditAPI(obj, token) : await passWordEditAPI2(obj)
      if (res.code === 0) {
        store.dispatch({ type: 'layout/passEditShow', payload: false })
        if (flag) {
          MessageFu.success('登录成功')
          // 用户信息存到本地
          setTokenInfo(userTokenInfo)
          history.replace('/')
        } else {
          MessageFu.success('修改成功')
          loginExit()
        }
      }
    },
    [flag, userTokenInfo]
  )

  return (
    <Modal
      wrapClassName={styles.PassEdit}
      destroyOnClose
      open={true}
      title={flag ? '为保障账号安全，请修改默认密码' : '修改密码'}
      // onCancel={() => store.dispatch({ type: 'layout/passEditShow', payload: false })}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <Form
        ref={FormBoxRef}
        scrollToFirstError={true}
        name='basic'
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 16 }}
        onFinish={onFinish}
        autoComplete='off'
      >
        <Form.Item
          label='旧密码'
          name='oldPassword'
          rules={[{ required: true, message: '不能为空!' }]}
          getValueFromEvent={e => e.target.value.replace(/\s+/g, '')}
        >
          <Input.Password maxLength={20} disabled={flag} />
        </Form.Item>

        <Form.Item
          label='新密码'
          name='newPassword'
          rules={[
            { required: true, message: '不能为空!' },
            { min: 6, max: 15, message: '密码长度为6-15个字符!' }
          ]}
          getValueFromEvent={e => e.target.value.replace(/\s+/g, '')}
        >
          <Input.Password
            maxLength={15}
            onChange={e => (oldPasswordValue.current = e.target.value)}
          />
        </Form.Item>

        <Form.Item
          label='确定新密码'
          name='checkPass'
          rules={[{ validator: checkPassWord }]}
          getValueFromEvent={e => e.target.value.replace(/\s+/g, '')}
        >
          <Input.Password maxLength={15} />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 5, span: 16 }}>
          <Button onClick={() => store.dispatch({ type: 'layout/passEditShow', payload: false })}>
            {flag ? '取消登录' : '取消'}
          </Button>
          &emsp;
          <Button type='primary' htmlType='submit'>
            {flag ? '确定修改并进入系统' : '确定'}
          </Button>
        </Form.Item>
      </Form>
    </Modal>
  )
}

const MemoPassEdit = React.memo(PassEdit)

export default MemoPassEdit
