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;
