function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { Camera } from 'react-camera-pro';
import Iconfont from "../iconfont";
import { getText } from "../../locales";
import PisellModal from "../../components/pisellModal";
import "./index.less";
var PisellCamera = /*#__PURE__*/forwardRef(function (props, ref) {
  var cameraRef = useRef(null);
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    open = _useState2[0],
    setOpen = _useState2[1];
  var _useState3 = useState(''),
    _useState4 = _slicedToArray(_useState3, 2),
    photo = _useState4[0],
    setPhoto = _useState4[1];
  var _useState5 = useState(null),
    _useState6 = _slicedToArray(_useState5, 2),
    cameraAvailable = _useState6[0],
    setCameraAvailable = _useState6[1]; // null: 检测中, true: 可用, false: 不可用
  var uploadFileRef = useRef(null);

  // Base64转File对象
  var base64ToFile = function base64ToFile(base64String, filename) {
    var _arr$0$match;
    var arr = base64String.split(',');
    var mime = ((_arr$0$match = arr[0].match(/:(.*?);/)) === null || _arr$0$match === void 0 ? void 0 : _arr$0$match[1]) || '';
    var bstr = atob(arr[1]);
    var n = bstr.length;
    var u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {
      type: mime
    });
  };

  // 拍照并添加到fileList
  var takePhoto = function takePhoto() {
    if (!cameraRef.current || !cameraRef.current.takePhoto) {
      return;
    }
    try {
      var _cameraRef$current, _cameraRef$current$ta;
      var _photo = (_cameraRef$current = cameraRef.current) === null || _cameraRef$current === void 0 || (_cameraRef$current$ta = _cameraRef$current.takePhoto) === null || _cameraRef$current$ta === void 0 ? void 0 : _cameraRef$current$ta.call(_cameraRef$current);
      var timestamp = Date.now();
      var filename = "photo-".concat(timestamp, ".jpg");
      setPhoto(_photo);

      // 转换为File对象
      var file = base64ToFile(_photo, filename);

      // 创建符合Antd Upload格式的文件对象
      var uploadFile = {
        uid: timestamp.toString(),
        name: filename,
        status: 'uploading',
        url: _photo,
        // 用于预览
        originFileObj: file,
        // 原始文件对象，用于上传
        thumbUrl: _photo,
        lastModified: Date.now(),
        lastModifiedDate: new Date(),
        type: 'image/jpeg',
        size: file.size
      };
      console.log('takePhoto_uploadFile', uploadFile);
      uploadFileRef.current = uploadFile;
      return uploadFile;
    } catch (error) {
      console.error('takePhoto_error', error);
      uploadFileRef.current = null;
      setPhoto('');
      return null;
    }
  };
  var onOpen = function onOpen() {
    setCameraAvailable(null);
    setPhoto('');
    uploadFileRef.current = null;
    setOpen(true);
  };

  // 关闭相机弹窗，重置状态
  var onClose = function onClose() {
    cameraRef.current = null;
    uploadFileRef.current = null;
    setOpen(false);
    setPhoto('');
    setCameraAvailable(null);
  };

  // 重拍照片
  var onRetakePhoto = function onRetakePhoto() {
    setPhoto('');
  };

  // 使用照片
  var onUsePhoto = function onUsePhoto() {
    var _props$onChange;
    props === null || props === void 0 || (_props$onChange = props.onChange) === null || _props$onChange === void 0 || _props$onChange.call(props, uploadFileRef.current);
    onClose();
  };
  useImperativeHandle(ref, function () {
    return {
      open: onOpen,
      takePhoto: takePhoto,
      isCameraAvailable: function isCameraAvailable() {
        return cameraAvailable;
      }
    };
  });
  console.log('cameraAvailable', cameraAvailable);
  return /*#__PURE__*/React.createElement(PisellModal, {
    open: open,
    onCancel: function onCancel(e) {
      e.stopPropagation();
      e.preventDefault();
      onClose();
    },
    header: false,
    footer: null,
    destroyOnClose: true,
    bodyStyle: {
      padding: 0
    },
    width: '90vw',
    className: "pisell-camera-modal"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-camera-container",
    onClick: function onClick(e) {
      e.stopPropagation();
      e.preventDefault();
    }
  }, cameraAvailable === null ?
  /*#__PURE__*/
  // 检测中
  React.createElement("div", {
    className: "pisell-camera-loading"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-camera-loading-text"
  }, getText('pisell-camera-checking'))) : cameraAvailable === false ?
  /*#__PURE__*/
  // 无摄像头
  React.createElement("div", {
    className: "pisell-camera-no-camera"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-camera-no-camera-icon"
  }, "\uD83D\uDCF7"), /*#__PURE__*/React.createElement("div", {
    className: "pisell-camera-no-camera-text"
  }, getText('pisell-camera-no-camera-accessible')), /*#__PURE__*/React.createElement("div", {
    className: "pisell-camera-no-camera-desc"
  }, getText('pisell-camera-no-camera-desc'))) : null, /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Camera, {
    ref: cameraRef,
    facingMode: "environment",
    errorMessages: {
      // noCameraAccessible: getText('pisell-camera-no-camera-accessible'),
      // permissionDenied: getText('pisell-camera-permission-denied'),
      // switchCamera: getText('pisell-camera-switch-camera'),
      // canvas: getText('pisell-camera-canvas'),
    },
    numberOfCamerasCallback: function numberOfCamerasCallback(numberOfCameras) {
      console.log('numberOfCameras', numberOfCameras);
      if (!cameraRef.current) {
        return;
      }
      if (numberOfCameras <= 0) {
        setTimeout(function () {
          setCameraAvailable(function (pre) {
            if (pre === true) {
              return true;
            }
            return false;
          });
        }, 5000);
      } else {
        setCameraAvailable(true);
      }
    }
  }), cameraAvailable === true && /*#__PURE__*/React.createElement("div", {
    className: "pisell-camera-action"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-camera-action-item-wrap",
    onClick: function onClick(e) {
      e.stopPropagation();
      e.preventDefault();
      takePhoto();
    }
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-camera-action-item"
  }, /*#__PURE__*/React.createElement(Iconfont, {
    type: "pisell2-camera-01",
    style: {
      fontSize: 32
    }
  })))), photo && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    className: "pisell-camera-photo-container"
  }, /*#__PURE__*/React.createElement("img", {
    src: photo,
    alt: "photo",
    className: "pisell-camera-photo"
  })), /*#__PURE__*/React.createElement("div", {
    className: "pisell-camera-photo-img-action"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-camera-photo-img-action-item",
    onClick: function onClick(e) {
      e.stopPropagation();
      e.preventDefault();
      onRetakePhoto();
    }
  }, getText('pisell-upload-camera-retake')), /*#__PURE__*/React.createElement("div", {
    className: "pisell-camera-photo-img-action-item",
    onClick: function onClick(e) {
      e.stopPropagation();
      e.preventDefault();
      onUsePhoto();
    }
  }, getText('pisell-upload-camera-use')))))));
});
export default PisellCamera;