LoginMobile.js 18 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 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 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
import React from 'react';
import { createForm } from 'rc-form';
import { InputItem, Button, WhiteSpace, Toast, Modal, Picker, List } from 'antd-mobile-v2';
import { history } from 'umi';
import 'antd-mobile-v2/dist/antd-mobile.css';
import styles from './LoginMobile.less';
import LoginIcon from '../../assets/mobile/LOGO.png';
import LoginUser from '../../assets/mobile/User.svg';
import loginCompanyPic from '../../assets/oee/loginCompany.png';
import LoginPassword from '../../assets/mobile/Password.svg';
import commonConfig from '../../utils/config';
import * as commonServices from '../../services/services';
import * as commonFunc from '../../components/Common/commonFunc';
import AppUtil from '../../utils/AppUtil';
import * as commonUtils from '../../utils/utils';
// import VConsole from 'vconsole';
// let vConsole;

// eslint-disable-next-line prefer-destructuring
const alert = Modal.alert;

class LoginMobile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      // eslint-disable-next-line react/no-unused-state
      companys: [],
      sParentId: '',
      sId: '',
      username: localStorage.getItem(`${commonConfig.prefix}username`) || '',
      userpwd: localStorage.getItem(`${commonConfig.prefix}userpwd`) || '',
      loginCompany: JSON.parse(localStorage.getItem(`${commonConfig.prefix}loginCompany`)) || [],
      cameraVisible: false,
      videoStream: null,
      cameraError: null,
      autoCaptureTimer: null,
      faceRecognizing: false,
    };
    this.videoRef = React.createRef();
  }
  async componentWillMount() {
    const configUrl = `${commonConfig.server_host}sysbrands/getSysbrands`;
    const configReturn = (await commonServices.getService(null, configUrl)).data;
    if (configReturn.code === 1) {
      const companys = configReturn.dataset.rows;
      const companysLabel = [];
      // const sParentId = commonUtils.isNotEmptyObject(this.state.sParentId) ? this.state.sParentId : companys[0].sParentId;
      // const sId = commonUtils.isNotEmptyObject(this.state.sId) ? this.state.sId : companys[0].sId;
      if (commonUtils.isNotEmptyArr(companys)) {
        // eslint-disable-next-line array-callback-return
        companys.forEach((item) => {
          const map = { ...item };
          map.label = item.sName;
          map.value = item.sId;
          map.sLanguage = item.sLanguage;
          companysLabel.push(map);
        });
      }
      // eslint-disable-next-line react/no-unused-state
      this.setState({ companys: companysLabel });
    } else {
      Toast.fail(configReturn.msg);
    }
  }
  componentDidMount() {
    if (localStorage.getItem(`${commonConfig.prefix}privacyPolicy`) !== 'agree') {
      const sLanguage = commonUtils.isNotEmptyArr(this.state.companys) ? this.state.companys[0].sLanguage : 'sChinese';
      if (sLanguage == "sEnglish") {
        alert(
          "User Agreement",
          <p>
            Thank you for choosing Xiaolingyang EBC! <br />
            We attach great importance to the protection of your personal information and privacy. To better safeguard your personal rights and
            interests, please carefully read all the terms in the
            <a href="serviceAgreement.html">Xiaolingyang EBC Service Agreement</a> and{" "}
            <a href="privacyPolicy.html">Xiaolingyang EBC Privacy Policy</a> before using our products, especially the following: Clauses regarding
            the rules for the collection, storage, use, external provision, and protection of your personal information, as well as clauses related to
            your user rights; Clauses stipulating our limited liability and exemption from liability; Other important clauses marked with colors or
            bold formatting. If you have any questions about the above agreements, you can contact us through customer service or by sending an email
            to yanghl@xlyerp.com. By clicking "Agree and Continue", you confirm that you have read and agreed to all the contents of the above
            agreements.
          </p>,
          [
            {
              text: "Disagree",
              onPress: () => {
                const { plus } = window;
                if (plus) {
                  plus.runtime.quit();
                }
              },
            },
            {
              text: "Agree and Continue",
              onPress: () => {
                localStorage.setItem(`${commonConfig.prefix}privacyPolicy`, "agree");
              },
            },
          ]
        );
      } else {


        alert(
          '用户协议与隐私政策',
          <p>感谢您选择小羚羊EBC<br />
            我们非常重视您的个人信息和隐私保护。为了更好地保障您的个人权益,在您使用我们的产品前,请务必审慎阅读
            <a href="serviceAgreement.html">《小羚羊EBC服务协议》</a>
            <a href="privacyPolicy.html">《小羚羊EBC隐私政策》</a>内的所有条款,尤其是:<br />
            1.我们对您的个人信息的收集/保存/使用/对外提供/保护等规则条款,以及您的用户权利等条款;<br />
            2.约定我们的限制责任、免责条款。<br />
            3.其他以颜色或加粗进行标识的重要条款。<br />
            如您对以上协议有任何疑问,可通过人工客服或发邮件至yanghl@xlyerp.com与我们联系。您点击“同意并继续”的行为即表示您已阅读完毕并同意以上协议的全部内容。
          </p>, [
          {
            text: '不同意',
            onPress: () => {
              const { plus } = window;
              if (plus) {
                plus.runtime.quit();
              }
            },
          },
          {
            text: '同意并继续',
            onPress: () => {
              localStorage.setItem(`${commonConfig.prefix}privacyPolicy`, 'agree');
            },
          },
        ],
        );
      }
    }
    // vConsole = new VConsole();
  }

  componentWillUnmount() {
    // vConsole.destroy();
    this.closeCamera();
    if (this.state.autoCaptureTimer) {
      clearTimeout(this.state.autoCaptureTimer);
    }
  }
  closeCamera = () => {
    if (this.state.videoStream) {
      this.state.videoStream.getTracks().forEach(track => track.stop());
      this.setState({ videoStream: null });
    }
    if (this.videoRef.current) {
      this.videoRef.current.srcObject = null;
    }
    if (this.state.autoCaptureTimer) {
      clearTimeout(this.state.autoCaptureTimer);
    }
  };

  startCamera = () => {
    navigator.mediaDevices.getUserMedia({
      video: {
        facingMode: 'user',
        width: { ideal: 640 },
        height: { ideal: 480 },
      },
    })
      .then(stream => {
        this.setState({
          cameraVisible: true,
          videoStream: stream,
          cameraError: null,
          autoCaptureTimer: setTimeout(() => {
            this.capturePhoto();
          }, 2000),
        }, () => {
          if (this.videoRef.current) {
            this.videoRef.current.srcObject = stream;
            this.videoRef.current.play();
          }
        });
      })
      .catch(error => {
        console.error('无法访问摄像头:', error);
        this.setState({
          cameraError: '无法访问摄像头,请检查权限设置',
          cameraVisible: false,
        });
        Toast.fail('无法访问摄像头,请检查权限');
      });
  };
  capturePhoto = () => {
    if (!this.videoRef.current || !this.state.cameraVisible) return;

    const video = this.videoRef.current;
    const canvas = document.createElement('canvas');
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

    const base64 = canvas.toDataURL('image/jpeg', 0.85).split(',')[1];
    //  不再立即 closeCamera(),而是进入识别状态
    this.setState({ faceRecognizing: true });
    this.processFaceRecognition(base64);
  };

  processFaceRecognition = (base64) => {
    const url = `${commonConfig.face_host}/face/faceSearch`;
    commonServices.postValueService(null, [{
      image: base64,
      image_type: "BASE64",
      face_field: "age",
      option: "COMMON"
    }], url)
      .then(({ data: dataReturn }) => {
        if (dataReturn?.code === 1 && dataReturn.dataset.rows.length > 0) {
          const value = {
            sEmployeeNo: dataReturn.dataset.rows[0].sEmployeeNo,
            sParentId: dataReturn.dataset.rows[0].sBrandsId,
            sId: dataReturn.dataset.rows[0].sSubsidiaryId
          };
          this.handleLogin(value);
        } else {
          Toast.fail(dataReturn?.msg || '人脸识别失败,请重试');
        }
      })
      .catch(err => {
        console.error('人脸识别失败:', err);
        Toast.fail('人脸识别失败');
      })
      .finally(() => {
        this.closeCamera();
        this.setState({
          cameraVisible: false,
          faceRecognizing: false
        });
      });
  };
  onChange = (name, newValue) => {
    if (name === 'username') {
      this.setState({ username: newValue });
    } if (name === 'userpwd') {
      this.setState({ userpwd: newValue });
    }
  }
  handleChoodeCompanyOk = (value) => {
    this.setState({
      loginCompany: value,
    });
  }

  takeTenPhotos = () => {
    if (!window.plus) {
      return Promise.reject(new Error('请在 HBuilder 打包的 App 中运行'));
    }

    return new Promise((resolve, reject) => {
      // 调用系统相机拍照(尽量指定前置)
      plus.camera.getCamera(1).captureImage(
        (imagePath) => {
          // 直接用 FileReader 读取逻辑路径(如 _doc/...),无需 resolve
          const reader = new plus.io.FileReader();
          reader.onload = (e) => {
            const img = new Image();
            img.onload = () => {
              const canvas = document.createElement('canvas');
              canvas.width = 268;
              canvas.height = 214;
              const ctx = canvas.getContext('2d');
              ctx.drawImage(img, 0, 0, 268, 214);
              // 转为 JPEG,质量 0.85,去掉前缀
              const base64 = canvas.toDataURL('image/jpeg', 0.85).split(',')[1];
              resolve(base64);
            };
            img.onerror = () => reject(new Error('图片解析失败'));

            img.src = e.target.result; // Data URL 安全加载
          };
          reader.onerror = (e) => reject(new Error('读取照片失败: ' + e.target.error.message));

          plus.io.resolveLocalFileSystemURL(imagePath, (entry) => {
            entry.file((file) => {
              reader.readAsDataURL(file.fullPath); // 关键:直接读逻辑路径

            })
          });
        },
        (error) => {
          reject(new Error('拍照失败: ' + error.message));
        },
        {
          filename: `_doc/camera/face_${Date.now()}.jpg`,
          format: 'jpg'
        }
      );
    });
  };

  handleFaceLogin = () => {
    this.takeTenPhotos()
      .then(base64List => {
        // 这里可以上传到你的 face/detectFaces 接口
        const url = `${commonConfig.face_host}/face/faceSearch`;
        commonServices.postValueService(null, [{
          image: base64List,
          image_type: "BASE64",
          face_field: "age",
          option: "COMMON"
        }], url).then(({ data: dataReturn }) => {
          // console.log('=====dataReturn', dataReturn);
          if (dataReturn.code === 1) {
            const value = {};
            value.sEmployeeNo = dataReturn.dataset.rows[0].sEmployeeNo;
            value.sParentId = dataReturn.dataset.rows[0].sBrandsId;
            value.sId = dataReturn.dataset.rows[0].sSubsidiaryId;
            this.handleLogin(value);
          } else {
            Toast.fail(dataReturn.msg);
          }
        })
      })
      .catch(err => {
        console.error('拍摄过程出错:', err);
      });
  }
  handleLogin = async (valueBase) => {
    const { dispatch, app } = this.props;
    const { loginCompany, companys } = this.state;
    let sParentId = '';
    if (commonUtils.isNotEmptyArr(companys) && commonUtils.isNotEmptyObject(loginCompany)) {
      // eslint-disable-next-line prefer-destructuring
      sParentId = companys.filter(item => item.sId === loginCompany[0])[0].sParentId;
    } else {
      Toast.fail(commonFunc.showMessage(app.commonConst, 'chooseBranchCompany'));
      return;
    }
    this.props.form.validateFields(async () => {
      let value = {};
      if (valueBase) {
        value = valueBase;
      } else {
        value.username = this.state.username;
        value.password = this.state.userpwd;
        value.sParentId = this.state.sParentId;
        // value.company = this.state.loginCompany;
        value.sId = this.state.sId;
      }
      const url = `${commonConfig.server_host}userlogin/${sParentId}/${loginCompany}?sLoginType=phoneLogin`;
      const dataReturn = (await commonServices.postValueService(null, value, url)).data;
      if (dataReturn.code === 1) {
        if (commonUtils.isNotEmptyObject(dataReturn.msg)) {
          Toast.info(dataReturn.msg, 3);
        }
        localStorage.setItem(`${commonConfig.prefix}username`, this.state.username);
        localStorage.setItem(`${commonConfig.prefix}userpwd`, this.state.userpwd);
        localStorage.setItem(`${commonConfig.prefix}loginCompany`, JSON.stringify(loginCompany));
        const param = {};
        const {
          token, gdslogininfo: userinfo, systemData, commonConst,
        } = dataReturn.dataset.rows[0];
        const decimals = {};
        if (systemData !== undefined) {
          const dNetPrice = systemData.filter(item => (item.sName === 'NetPrice'))[0];
          const dNetMoney = systemData.filter(item => (item.sName === 'NetMoney'))[0];
          decimals.dNetPrice = dNetPrice.sValue !== undefined ? (dNetPrice.sValue) * 1 : 6;
          decimals.dNetMoney = dNetMoney.sValue !== undefined ? (dNetMoney.sValue) * 1 : 6;
        }
        param.token = token;
        param.userinfo = userinfo;
        param.systemData = systemData;
        param.commonConst = commonConst;
        param.decimals = decimals;
        param.dateFormat = commonFunc.getDateFormat(systemData);
        dispatch({
          type: 'loginMobile/login',
          payload: { ...param, dispatch },
        });

      } else {
        Toast.fail(dataReturn.msg);
      }
    });
  }

  render() {
    const { loginCompany, companys, cameraVisible, cameraError } = this.state;
    console.log('2loginCompany22', loginCompany, companys);
    const { getFieldProps } = this.props.form;
    let sLanguage = commonUtils.isNotEmptyArr(companys) ? companys[0].sLanguage : 'sChinese';
    const settingTitle = sLanguage === 'sEnglish' ? 'server settings' : '服务器设置';
    const loginTitle = sLanguage === 'sEnglish' ? 'Login' : '登录';
    const loginFaceTitle = sLanguage === 'sEnglish' ? 'Face Login' : '人脸登录';
    const pleaseInputUser = sLanguage === 'sEnglish' ? 'please Input User' : '请输入用户';
    const pleaseInputPassword = sLanguage === 'sEnglish' ? 'please Input Password' : '请输入密码';

    return (
      <div className={styles.wraper}>
        {/* 摄像头预览层 - 仅在cameraVisible为true时显示 */}
        {cameraVisible && (
          <div className={styles.cameraOverlay}>
            <video
              ref={this.videoRef}
              autoPlay
              playsInline
              style={{ width: '100%', height: '100vh', objectFit: 'cover' }}
            />
            {cameraError && (
              <div className={styles.cameraError}>{cameraError}</div>
            )}
          </div>
        )}
        <div className={styles.logo}>
          <img src={LoginIcon} alt="login" />
        </div>
        <div className={styles.login}>
          <WhiteSpace size="xs" />
          <InputItem
            {...getFieldProps("username")}
            placeholder={pleaseInputUser}
            value={this.state.username}
            onChange={this.onChange.bind(this, "username")}
            style={{ backgroundColor: "#fff" }}
          >
            <div
              style={{
                backgroundImage: `url(${LoginUser})`,
                backgroundSize: "cover",
                height: "22px",
                width: "22px",
              }}
            />
          </InputItem>
          <WhiteSpace size="xs" />
          <InputItem
            {...getFieldProps("userpwd")}
            type="password"
            placeholder={pleaseInputPassword}
            value={this.state.userpwd}
            onChange={this.onChange.bind(this, "userpwd")}
          >
            <div
              style={{
                backgroundImage: `url(${LoginPassword})`,
                backgroundSize: "cover",
                height: "22px",
                width: "22px",
              }}
            />
          </InputItem>
          <div className="chooseCompany">
            <Picker data={this.state.companys} cols={1} value={loginCompany} onChange={this.handleCompanyChange} onOk={this.handleChoodeCompanyOk}>
              <List.Item arrow="horizontal">
                <div
                  style={{
                    backgroundImage: `url(${loginCompanyPic})`,
                    backgroundSize: "cover",
                    height: "22px",
                    width: "22px",
                  }}
                />
              </List.Item>
            </Picker>
          </div>
          <WhiteSpace size="lg" />
          <WhiteSpace size="lg" />
          <div className={styles.loginSubmit}>
            <Button type="primary" onClick={() => { this.handleLogin(); }} style={{ backgroundColor: "#5e81e5" }}>
              {loginTitle}
            </Button>
            <Button type="primary" onClick={this.startCamera} style={{ backgroundColor: "#5e81e5" }}>
              {loginFaceTitle}
            </Button>
          </div>
          {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
          <a
            className={styles.setting}
            onClick={() => {
              AppUtil.openSettingPage();
            }}
          >
            {settingTitle}
          </a>
        </div>
      </div>
    );
  }
}
const LoginMobileWrapper = createForm()(LoginMobile);
export default LoginMobileWrapper;