AvatarDropdown.js 13.5 KB
Newer Older
dengxiaofeng's avatar
dengxiaofeng committed
1
import React from 'react';
2

邓晓峰's avatar
邓晓峰 committed
3 4 5 6 7 8 9 10 11 12
import {
  Avatar,
  Form,
  Input,
  message,
  Modal,
  Popover,
  Spin,
  Upload,
} from 'antd';
邓晓峰's avatar
邓晓峰 committed
13
import { withRouter } from 'react-router';
邓晓峰's avatar
邓晓峰 committed
14
import Cookies from 'js-cookie';
15 16 17 18 19 20 21
import {
  FormattedMessage,
  useIntl,
} from '@/locales/localeExports';
import { request } from '@wisdom-utils/utils';

import { appService } from '../../api';
邓晓峰's avatar
邓晓峰 committed
22 23
// eslint-disable-next-line import/named
import { API } from '../../api/service/base';
24
import globalHeader from '../../locales/zh-CN/globalHeader';
25 26 27 28
import styles from './index.less';

// import i18n from '../../utils/share';
// const app = i18n.getI18n('component');
邓晓峰's avatar
邓晓峰 committed
29 30 31 32
const formItemLayout = {
  labelCol: {
    xs: { span: 4 },
    sm: { span: 4 },
邓晓峰's avatar
邓晓峰 committed
33
  },
邓晓峰's avatar
邓晓峰 committed
34
};
邓晓峰's avatar
邓晓峰 committed
35

邓晓峰's avatar
邓晓峰 committed
36 37
/* eslint-disable */
const getIOT = () =>
38 39
  (window.globalConfig.loginTemplate === 'Dark - IOTMultiLogin.html' ||
    window.globalConfig.loginTemplate === '新春 - 智联.html')
dengxiaofeng's avatar
dengxiaofeng committed
40 41
class AvatarDropdown extends React.Component {
  /* eslint-disable no-unused-vars */
邓晓峰's avatar
邓晓峰 committed
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60

  constructor(props) {
    super(props);
    let {
      currentUser = {
        avatar: this.transformAvatarImage(),
        name:
          (props.global &&
            props.global.userInfo &&
            props.global.userInfo.fullName) ||
          'Serati Ma',
      },
    } = this.props;
    this.state = {
      currentUser: currentUser,
      visible: false,
      popVisible: false,
      path: null,
      version: null,
邓晓峰's avatar
邓晓峰 committed
61
      action: API.UPLOAD_FILE_URL
邓晓峰's avatar
邓晓峰 committed
62 63
    }
  }
邓晓峰's avatar
邓晓峰 committed
64
  loginout = event => {
邓晓峰's avatar
邓晓峰 committed
65
    // eslint-disable-next-line no-undef
66
    this.props.logout();
邓晓峰's avatar
邓晓峰 committed
67 68 69 70 71
    if (
      window.globalConfig.style === 'ios' &&
      window.globalConfig.loginTemplate === 'IOSCloud.html'
    ) {
      window.location.href = `${window.location.origin}/#login`;
邓晓峰's avatar
邓晓峰 committed
72 73
      return false;
    }
邓晓峰's avatar
邓晓峰 committed
74 75 76 77
    // console.log(this.props)
    // this.props.history.push('/login')
    // window.location.reload();
    //
dengxiaofeng's avatar
dengxiaofeng committed
78 79
  };

邓晓峰's avatar
邓晓峰 committed
80
  getRoles = () => {
邓晓峰's avatar
邓晓峰 committed
81 82
    const roles = this.props.global.userInfo.roles || [];
    const ret = [];
邓晓峰's avatar
邓晓峰 committed
83
    roles.forEach(item => {
邓晓峰's avatar
邓晓峰 committed
84 85 86 87 88
      ret.push(item.name);
    });
    return ret.join(',');
  };

邓晓峰's avatar
邓晓峰 committed
89

邓晓峰's avatar
邓晓峰 committed
90 91
  showModal = event => {
    event.stopPropagation();
邓晓峰's avatar
邓晓峰 committed
92
    this.setState({
邓晓峰's avatar
邓晓峰 committed
93
      visible: true,
邓晓峰's avatar
邓晓峰 committed
94 95 96 97
    });
  };

  handleOk = (event, form) => {
邓晓峰's avatar
邓晓峰 committed
98 99 100 101 102 103 104 105 106 107 108 109 110 111
    event.stopPropagation();
    form
      .validateFields()
      .then(res => {
        const params = getIOT()
          ? {
              newPassword: res.newPwd,
              phone: window.globalConfig.userInfo.Phone,
            }
          : {
              password: res.oldPwd,
              newpassword: res.newPwd,
              token: window.globalConfig.token,
            };
邓晓峰's avatar
邓晓峰 committed
112
        appService.changePassword(params)
邓晓峰's avatar
邓晓峰 committed
113 114
          .then(res => {
            if (res.success) {
115 116
              //message.success(useIntl().formatMessage({id: 'component.account.password.update.success'}));
              message.success(globalHeader['component.account.password.update.success']);
邓晓峰's avatar
邓晓峰 committed
117 118 119 120 121 122
              setTimeout(() => {
                this.setState({
                  visible: false,
                });
              }, 300);
            } else {
123
              message.error(useIntl().formatMessage({id: 'component.account.oldpassword.errorMessage'}));
邓晓峰's avatar
邓晓峰 committed
124 125 126
            }
          })
          .catch(error => {
127
            message.error(useIntl().formatMessage({id: 'component.account.password.update.fail'}));
邓晓峰's avatar
邓晓峰 committed
128
          });
邓晓峰's avatar
邓晓峰 committed
129
      })
邓晓峰's avatar
邓晓峰 committed
130 131 132
      .catch(error => {
        console.log(error);
      });
邓晓峰's avatar
邓晓峰 committed
133 134 135
  };

  handleCancel = (event, form) => {
邓晓峰's avatar
邓晓峰 committed
136
    event.stopPropagation();
邓晓峰's avatar
邓晓峰 committed
137 138 139 140 141
    form.resetFields();
    this.setState({
      visible: false,
    });
  };
邓晓峰's avatar
邓晓峰 committed
142

邓晓峰's avatar
邓晓峰 committed
143 144
  transformAvatarImage() {
    const { userInfo } = this.props.global;
邓晓峰's avatar
邓晓峰 committed
145 146 147 148 149 150 151 152 153
    const defaultImage = `${
      window.location.origin
    }/civweb4/assets/images/icon/熊猫新2.png`;
    let image = defaultImage;
    if (
      userInfo &&
      userInfo.UserImge &&
      userInfo.UserImge.indexOf('个人信息') > -1
    ) {
邓晓峰's avatar
邓晓峰 committed
154
      image = `/cityinterface/rest/services/filedownload.svc/download/${userInfo.UserImge}`;
邓晓峰's avatar
邓晓峰 committed
155 156 157 158 159
    } else if (
      userInfo.UserImge &&
      userInfo.UserImge !== '' &&
      userInfo.UserImge !== 'default_user.png'
    ) {
邓晓峰's avatar
邓晓峰 committed
160
      image = userInfo.UserImge;
邓晓峰's avatar
邓晓峰 committed
161
    } else if (userInfo.WxImage && userInfo.WxImage !== '') {
邓晓峰's avatar
邓晓峰 committed
162 163
      image = userInfo.WxImage;
    }
邓晓峰's avatar
邓晓峰 committed
164
    return image;
邓晓峰's avatar
邓晓峰 committed
165
  }
邓晓峰's avatar
邓晓峰 committed
166

邓晓峰's avatar
邓晓峰 committed
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
  beforeUpload(file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    const path = (new Date()).getTime();
    this.setState({
      path: path,
      action: this.state.action.replace('{path}', path).replace('{filename}', file.name)
    })
    return isJpgOrPng && isLt2M;
  }

  handleChange(data) {
    console.log(data)
  }

  componentDidMount() {
邓晓峰's avatar
邓晓峰 committed
189
    appService.getVersion({
邓晓峰's avatar
邓晓峰 committed
190 191
      ignoreSite: true
    }).then(res => {
邓晓峰's avatar
邓晓峰 committed
192 193 194 195 196 197
      if(res.success) {
        this.setState({
          version: res.message
        })
      }
    }).catch(error => {
198
      message.error(useIntl().formatMessage({id: 'component.getVersion.errorMessage'}))
邓晓峰's avatar
邓晓峰 committed
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    })
  }

  customRequest = ({
    action,
    data,
    file,
    filename,
    headers,
    onError,
    onProgress,
    onSuccess,
    withCredentials,}) => {
    const formData = new FormData();
    if(data) {
      Object.keys(data).forEach(key => {
        formData.append(key, data[key]);
      })
    }
    formData.append("filedata", file);
219
    request(action, {
邓晓峰's avatar
邓晓峰 committed
220 221 222 223 224 225
      withCredentials,
      headers: {
        ...headers,
        Accept: '*/*',
        'civ-site': ''
      },
226 227
      method: 'post',
      data: formData,
邓晓峰's avatar
邓晓峰 committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
      ignoreSite: true,
      onUploadProgress: ({ total, loaded }) => {
        onProgress({ percent: Math.round((loaded / total) * 100).toFixed(2) }, file);
      },
    })
      .then(res => {
        onSuccess(res, file);
      })
      .catch(onError);
    return {
      abort() {
        console.log('upload progress is aborted.');
      }
    }
  }

dengxiaofeng's avatar
dengxiaofeng committed
244
  render() {
邓晓峰's avatar
邓晓峰 committed
245
    const self = this;
邓晓峰's avatar
邓晓峰 committed
246
    const { props } = this;
邓晓峰's avatar
邓晓峰 committed
247
    const { userInfo } = props.global;
邓晓峰's avatar
邓晓峰 committed
248 249 250 251 252 253 254 255
    const site =
      props.global &&
      props.global.userInfo &&
      props.global.userInfo.site &&
      userInfo.site !== '' &&
      props.global.client !== 'oms'
        ? userInfo.site
        : '';
邓晓峰's avatar
邓晓峰 committed
256 257 258 259 260 261


    const uploadProps = {
      action: this.state.action,
      onStart(file) {
        console.log('onStart', file, file.name);
dengxiaofeng's avatar
dengxiaofeng committed
262
      },
邓晓峰's avatar
邓晓峰 committed
263 264 265 266 267 268 269 270 271 272 273 274 275 276
      onSuccess(res, file) {
        if(res.success) {
          const avatarPath =  "/个人信息/" + self.state.path + '/' + file.name;
          const params = {
            userID: props.global.get("userInfo.OID"),
            loginName: props.global.get("userInfo.loginName"),
            userName: props.global.get("userInfo.fullName"),
            _version: self.state.version,
            mark: props.global.get("userInfo.Mark"),
            phone: props.global.get("userInfo.Phone"),
            email: props.global.get("userInfo.Email"),
            userImage: decodeURIComponent(avatarPath),
            WXid: props.global.get("userInfo.WXid")
          }
叶飞's avatar
叶飞 committed
277

邓晓峰's avatar
邓晓峰 committed
278
          appService.updateAvatar(params).then(res => {
邓晓峰's avatar
邓晓峰 committed
279
            if(res.success) {
280 281
              // message.success(useIntl().formatMessage({id: 'component.avatar.update.success'}));
              message.success(globalHeader['component.avatar.update.success']);
邓晓峰's avatar
邓晓峰 committed
282 283 284
              self.setState({
                currentUser: {
                  name: self.state.currentUser.name,
邓晓峰's avatar
邓晓峰 committed
285 286
                  avatar: `${API.AVATAR_FILE_URL}${avatarPath}`,
                  action: API.UPLOAD_FILE_URL
邓晓峰's avatar
邓晓峰 committed
287 288 289 290
                }
              })
            }
          }).catch(e => {
291
            message.error(useIntl().formatMessage({id: 'component.avatar.update.fail'}))
邓晓峰's avatar
邓晓峰 committed
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
          })
        } else {
          message.error(res.message);
        }
      },
      onError(err) {
        console.log('onError', err);
      },
      onProgress({ percent }, file) {
        console.log('onProgress', `${percent}%`, file.name);
      },
      customRequest: this.customRequest.bind(this),
      beforeUpload: this.beforeUpload.bind(this),
      onChange: this.handleChange.bind(this)
    }
    const currentUser = this.state.currentUser;
dengxiaofeng's avatar
dengxiaofeng committed
308
    const menuHeaderDropdown = (
邓晓峰's avatar
邓晓峰 committed
309 310
      <div className={styles.userInfo}>
        <div className={styles.header}>
311
          <Upload className="avatar-uploader" {...uploadProps} maxCount={1} itemRender={()=>(<></>)}>
邓晓峰's avatar
邓晓峰 committed
312 313 314 315 316
            <div
              className={styles.avatar}
              style={{ backgroundImage: `url(${currentUser.avatar})` }}
            />
          </Upload>
邓晓峰's avatar
邓晓峰 committed
317
          <div className={styles.name}>{userInfo.fullName}</div>
邓晓峰's avatar
邓晓峰 committed
318 319 320 321 322
        </div>
        <div className={styles.body}>
          <div className={styles.item}>
            <ul>
              <li>
邓晓峰's avatar
邓晓峰 committed
323
                <span />
324
                <span className={styles.label}><FormattedMessage id="component.avatar.account"/></span>
邓晓峰's avatar
邓晓峰 committed
325
                <span className={styles.value}>{userInfo.loginName}</span>
邓晓峰's avatar
邓晓峰 committed
326 327
              </li>
              <li>
邓晓峰's avatar
邓晓峰 committed
328
                <span />
329
                <span className={styles.label}><FormattedMessage id="component.avatar.name"/></span>
邓晓峰's avatar
邓晓峰 committed
330
                <span className={styles.value}>{userInfo.fullName}</span>
邓晓峰's avatar
邓晓峰 committed
331 332
              </li>
              <li>
邓晓峰's avatar
邓晓峰 committed
333
                <span />
334
                <span className={styles.label}><FormattedMessage id="component.avatar.depart"/></span>
邓晓峰's avatar
邓晓峰 committed
335 336 337
                <span className={styles.value}>
                  {userInfo && userInfo.depart && userInfo.depart.name}
                </span>
邓晓峰's avatar
邓晓峰 committed
338 339
              </li>
              <li>
邓晓峰's avatar
邓晓峰 committed
340
                <span />
341
                <span className={styles.label}><FormattedMessage id="component.avatar.role"/></span>
邓晓峰's avatar
邓晓峰 committed
342 343
                <span className={styles.value}>{this.getRoles()}</span>
              </li>
邓晓峰's avatar
邓晓峰 committed
344 345 346
              {site ? (
                <li>
                  <span />
347
                  <span className={styles.label}><FormattedMessage id="component.siteCode"/></span>
邓晓峰's avatar
邓晓峰 committed
348 349 350
                  <span className={styles.value}>{userInfo.site}</span>
                </li>
              ) : null}
邓晓峰's avatar
邓晓峰 committed
351 352 353
            </ul>
          </div>
          <div className={styles.exit}>
邓晓峰's avatar
邓晓峰 committed
354
            {userInfo && userInfo.site === '' && (
355
              <a onClick={event => this.showModal(event)}><FormattedMessage id="component.password.update"/></a>
邓晓峰's avatar
邓晓峰 committed
356 357
            )}

358
            <a onClick={this.loginout}><FormattedMessage id="component.exit.login"/></a>
邓晓峰's avatar
邓晓峰 committed
359 360 361
          </div>
        </div>
      </div>
dengxiaofeng's avatar
dengxiaofeng committed
362
    );
邓晓峰's avatar
邓晓峰 committed
363

dengxiaofeng's avatar
dengxiaofeng committed
364
    return currentUser && currentUser.name ? (
邓晓峰's avatar
邓晓峰 committed
365
      <>
邓晓峰's avatar
邓晓峰 committed
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
        <Popover
          overlayClassName={styles.userWrapper}
          placement="bottom"
          trigger="click"
          content={
            props.global && props.global.userInfo ? menuHeaderDropdown : null
          }
        >
          <span
            className={`${styles.action} ${styles.account}`}
            ref={r => (this.avatarRef = r)}
          >
            <Avatar
              size="small"
              className={styles.avatar}
              src={currentUser.avatar}
              alt="avatar"
            />
            {/* <span className={`${styles.name} anticon`}>{currentUser.name}</span> */}
          </span>
        </Popover>
        <Modal
邓晓峰's avatar
邓晓峰 committed
388 389 390 391 392 393 394
          title="修改密码"
          centered
          width="480px"
          visible={this.state.visible}
          wrapClassName={styles.updatePassword}
          cancelText="取消"
          okText="确定"
邓晓峰's avatar
邓晓峰 committed
395 396 397 398 399 400 401 402 403 404
          onOk={event => this.handleOk(event, this.form)}
          onCancel={event => this.handleCancel(event, this.form)}
          zIndex={2000}
        >
          <Form
            labelAlign="right"
            {...formItemLayout}
            ref={f => (this.form = f)}
          >
            {!getIOT() && (
邓晓峰's avatar
邓晓峰 committed
405
              <Form.Item
邓晓峰's avatar
邓晓峰 committed
406 407
                name="oldPwd"
                label="原密码"
邓晓峰's avatar
邓晓峰 committed
408 409 410
                rules={[
                  {
                    required: true,
邓晓峰's avatar
邓晓峰 committed
411
                    message: '请输入原始密码',
邓晓峰's avatar
邓晓峰 committed
412 413
                  },
                ]}
邓晓峰's avatar
邓晓峰 committed
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
                hasFeedback
              >
                <Input.Password />
              </Form.Item>
            )}
            <Form.Item
              name="newPwd"
              label="新密码"
              rules={[
                {
                  required: true,
                  message: '请输入新密码',
                },
                {
                  pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9!@#$%^&*_]{8,16}$/,
                  message: '密码字符长度为8-16个字符',
                },
              ]}
              hasFeedback
            >
邓晓峰's avatar
邓晓峰 committed
434 435 436
              <Input.Password />
            </Form.Item>
            <Form.Item
邓晓峰's avatar
邓晓峰 committed
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
              name="confirmPwd"
              label="确认密码"
              dependencies={['newPwd']}
              hasFeedback
              rules={[
                {
                  required: true,
                  message: '请输入确认密码',
                },
                ({ getFieldValue }) => ({
                  validator(rule, value) {
                    if (!value || getFieldValue('newPwd') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject('确认密码与新密码输入不一致');
邓晓峰's avatar
邓晓峰 committed
452
                  },
邓晓峰's avatar
邓晓峰 committed
453 454 455
                }),
              ]}
            >
邓晓峰's avatar
邓晓峰 committed
456 457 458
              <Input.Password />
            </Form.Item>
          </Form>
邓晓峰's avatar
邓晓峰 committed
459 460
        </Modal>
      </>
dengxiaofeng's avatar
dengxiaofeng committed
461 462 463 464 465 466 467 468 469 470 471 472 473 474
    ) : (
      <span className={`${styles.action} ${styles.account}`}>
        <Spin
          size="small"
          style={{
            marginLeft: 8,
            marginRight: 8,
          }}
        />
      </span>
    );
  }
}

邓晓峰's avatar
邓晓峰 committed
475
export default withRouter(AvatarDropdown);