AvatarDropdown.jsx 6.5 KB
Newer Older
左玲玲's avatar
左玲玲 committed
1
import React, { useCallback, useState, useMemo, useEffect } from 'react';
wuhao's avatar
wuhao committed
2
import { LogoutOutlined, LockOutlined } from '@ant-design/icons';
TZW's avatar
TZW committed
3
import { Menu, Spin, Button, Form, Modal, message, Avatar, Select } from 'antd';
wuhao's avatar
wuhao committed
4 5 6 7 8 9 10 11 12 13 14 15 16
import { history, useModel } from '@umijs/max';
import { stringify } from 'querystring';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import { fakeAccountLoginOut, changePwd } from '@/services/login';
import InitForm from '@/components/InitForm';
import { doFetch } from '@/utils/doFetch';
import { useRequest } from 'ahooks';
import AES from 'crypto-js/aes';
import ECB from 'crypto-js/mode-ecb';
import Pkcs7 from 'crypto-js/pad-pkcs7';
import Utf8 from 'crypto-js/enc-utf8';
import moment from 'moment';
左玲玲's avatar
左玲玲 committed
17 18 19 20 21 22 23 24
import io from 'socket.io-client';
const { NODE_ENV } = process.env;
const websocketUrl = NODE_ENV == "development" ? "ws://192.168.40.110:9933" : `${window.location.protocol == "http:" ? "ws" : "wss"}://${window.location.host}`;
const socket = io(websocketUrl, {
  reconnectionDelay: 4000,
  transports: ['websocket'],
  autoConnect: true,
});
wuhao's avatar
wuhao committed
25 26 27 28
/**
 * 退出登录,并且将当前的 url 保存
 */
const loginOut = async () => {
TZW's avatar
TZW committed
29
  const { logoutRedirectUrl } = await fakeAccountLoginOut();
TZW's avatar
TZW committed
30
  if (window.location.pathname !== '/user/login') {
wuhao's avatar
wuhao committed
31
    localStorage.clear();
TZW's avatar
TZW committed
32
    window.location.replace(logoutRedirectUrl);
wuhao's avatar
wuhao committed
33 34 35 36
  }
};

const AvatarDropdown = ({ menu }) => {
TZW's avatar
TZW committed
37 38
  const getUserApp = useRequest(async () => {
    let res = await doFetch({ url: '/auth/sysUser/userApp/selection', params: {} });
TZW's avatar
TZW committed
39
    return res?.data || {};
TZW's avatar
TZW committed
40
  });
wuhao's avatar
wuhao committed
41
  const { initialState, setInitialState } = useModel('@@initialState');
左玲玲's avatar
左玲玲 committed
42
  const { allWebsocket, changeWebsocket } = useModel('useGlobal');
wuhao's avatar
wuhao committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
  const [visible, cv] = useState(false),
    [formRef] = Form.useForm(),
    { run, loading } = useRequest(doFetch, {
      manual: true,
      formatResult: (res) => res,
      onSuccess: (result, params) => {
        if (result.code == '0000') {
          cv(false);
          message.success('密码修改成功,请重新登录', 2, () => {
            setInitialState((s) => ({
              ...s,
              currentUser: undefined,
              newMenu: undefined,
            }));
            loginOut();
          });
        }
      },
    });
左玲玲's avatar
左玲玲 committed
62 63 64 65 66 67 68 69


  useEffect(() => {
    changeWebsocket((s) => ({ ...s, commonWebsocket: socket }));
    socket.on('iotData', (data) => {
      changeWebsocket((s) => ({ ...s, commonWebmsg: data }));
    });
  }, []);
wuhao's avatar
wuhao committed
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
  const fields = useMemo(() => {
    return {
      password: {
        value: null,
        type: 'password',
        title: '密码',
        name: ['password'],
        required: true,
      },
      newPassword: {
        value: null,
        type: 'password',
        title: '新密码',
        name: ['newPassword'],
        required: true,
      },
      confirmPassword: {
        value: null,
        type: 'password',
        title: '确认密码',
        name: ['confirmPassword'],
        required: true,
        checkConfirm: (rule, value) => {
          if (value && value !== formRef.getFieldValue('newPassword')) {
            return Promise.reject('2次密码不一致!');
          } else {
            return Promise.resolve();
          }
        },
      },
    };
  }, []);
TZW's avatar
TZW committed
102 103 104 105 106 107 108 109 110 111 112 113

  const onMenuClick = (event) => {
    const { key } = event;
    if (key === 'logout') {
      loginOut();
      return;
    } else if (key == 'changepwd') {
      cv(true);
      return;
    }
  };

wuhao's avatar
wuhao committed
114
  const loadings = (
TZW's avatar
TZW committed
115
    <HeaderDropdown overlay={menuHeaderDropdown}>
TZW's avatar
TZW committed
116 117 118 119 120 121 122 123 124 125 126 127
      <React.Fragment>
        <Button onClick={onMenuClick}>
          <Spin
            size="small"
            style={{
              marginLeft: 8,
              marginRight: 8,
            }}
          />
          退出
        </Button>
      </React.Fragment>
TZW's avatar
TZW committed
128
    </HeaderDropdown>
wuhao's avatar
wuhao committed
129 130 131 132 133 134 135
  );

  if (!initialState) {
    return loadings;
  }

  const { currentUser } = initialState;
TZW's avatar
TZW committed
136
  if (!currentUser || !currentUser.username) {
wuhao's avatar
wuhao committed
137 138
    return loadings;
  }
TZW's avatar
TZW committed
139 140 141
  // console.log(
  //   getUserApp?.data?.dataList?.filter((it) => it?.appId == getUserApp?.data?.appId)[0]?.value,
  // );
wuhao's avatar
wuhao committed
142 143 144 145 146 147 148 149 150 151 152

  let saveData = (values) => {
    let newfields = JSON.parse(JSON.stringify(values));
    delete newfields.confirmPassword;

    let timestamp = moment().valueOf().toString() + 'acb';
    let newtimestamp = AES.encrypt(timestamp, Utf8.parse('NANGAODEAESKEY--'), {
      mode: ECB,
      padding: Pkcs7,
    }).toString();
    let newPassword = AES.encrypt(values.newPassword, Utf8.parse(timestamp), {
左玲玲's avatar
左玲玲 committed
153 154 155
      mode: ECB,
      padding: Pkcs7,
    }).toString(),
wuhao's avatar
wuhao committed
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
      password = AES.encrypt(values.password, Utf8.parse(timestamp), {
        mode: ECB,
        padding: Pkcs7,
      }).toString();

    let postData = {
      password,
      newPassword,
      encryptKey: newtimestamp,
    };
    run({ url: '/ngic-auth/sysUser/changePassword', params: { ...postData } });
  };
  const menuHeaderDropdown = (
    <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
      <Menu.Item key="logout">
        <LogoutOutlined />
        退出登录
      </Menu.Item>
    </Menu>
  );
TZW's avatar
TZW committed
176 177

  const handleChange = (value) => {
TZW's avatar
TZW committed
178 179 180
    if (value) {
      window.location.href = value;
    }
TZW's avatar
TZW committed
181
  };
wuhao's avatar
wuhao committed
182
  return (
TZW's avatar
TZW committed
183 184 185 186 187 188 189
    <div
      style={{
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center',
      }}
    >
wuhao's avatar
wuhao committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203
      <Modal
        title="修改密码"
        open={visible}
        onCancel={() => {
          cv(false);
        }}
        destroyOnClose={true}
        maskClosable={false}
        footer={false}
      >
        <InitForm
          formRef={formRef}
          fields={fields}
          col={{ span: 24 }}
左玲玲's avatar
左玲玲 committed
204
          onChange={(changedValues, allValues) => { }}
wuhao's avatar
wuhao committed
205 206 207 208 209 210
          submitData={(values, fn) => {
            saveData(values, fn);
          }}
          submitting={loading || !visible}
        />
      </Modal>
TZW's avatar
TZW committed
211 212
      <Select
        style={{ width: 150, marginRight: 8 }}
TZW's avatar
TZW committed
213 214 215 216
        value={
          getUserApp?.data?.dataList?.filter((it) => it?.appId == getUserApp?.data?.appId)[0]?.value
        }
        options={getUserApp?.data?.dataList}
TZW's avatar
TZW committed
217 218
        onChange={handleChange}
      />
wuhao's avatar
wuhao committed
219 220 221
      <HeaderDropdown overlay={menuHeaderDropdown}>
        <span className={`${styles.action} ${styles.account}`}>
          <Avatar style={{ backgroundColor: '#1890ff' }}>
TZW's avatar
TZW committed
222
            {currentUser.fullName.substr(0, 1)}
wuhao's avatar
wuhao committed
223 224
          </Avatar>
          <span className={`${styles.name} anticon`} style={{ margin: '0 12px' }}>
TZW's avatar
TZW committed
225
            {currentUser.fullName}
wuhao's avatar
wuhao committed
226 227 228 229 230 231 232 233
          </span>
        </span>
      </HeaderDropdown>
    </div>
  );
};

export default AvatarDropdown;