"use strict";

function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = DraftingPrint;
var _react = _interopRequireWildcard(require("react"));
var _antd = require("antd");
var _Modal = _interopRequireDefault(require("../../components/Modal"));
var _html2canvas = _interopRequireDefault(require("html2canvas"));
var _interaction = require("ol/interaction");
var _Draw = require("ol/interaction/Draw");
var _printJs = _interopRequireDefault(require("print-js"));
var _control = require("ol/control");
var _Tile = _interopRequireDefault(require("ol/layer/Tile"));
var _OSM = _interopRequireDefault(require("ol/source/OSM"));
var _ol = require("ol");
var _lodash = require("lodash");
var _useProps2 = _interopRequireDefault(require("../../../use-props"));
var _Draw2 = require("../../Utils/Draw");
var _legend = _interopRequireDefault(require("../../../legend"));
require("./index.less");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _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(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
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(r) { if (Array.isArray(r)) return r; } // 假设 Legend 组件位于同级目录
/**
 * 制图打印组件（含图例、鹰眼、比例尺）
 */
function DraftingPrint(props) {
  var _props$download = props.download,
    download = _props$download === void 0 ? false : _props$download,
    onClose = props.onClose,
    showEagleEye = props.showEagleEye,
    showScale = props.showScale,
    showLegend = props.showLegend;
  // console.log(44444, props);
  var _useProps = (0, _useProps2["default"])(),
    mainMap = _useProps.map,
    TextEnum = _useProps.TextEnum;
  var _useState = (0, _react.useState)(false),
    _useState2 = _slicedToArray(_useState, 2),
    visible = _useState2[0],
    setVisible = _useState2[1];
  var _useState3 = (0, _react.useState)(null),
    _useState4 = _slicedToArray(_useState3, 2),
    img = _useState4[0],
    setImg = _useState4[1];
  var _useState5 = (0, _react.useState)({}),
    _useState6 = _slicedToArray(_useState5, 2),
    formVal = _useState6[0],
    setFormVal = _useState6[1];
  var _useState7 = (0, _react.useState)('1'),
    _useState8 = _slicedToArray(_useState7, 2),
    rangeType = _useState8[0],
    setRangeType = _useState8[1]; // '1': 当前视图, '2': 手动框选

  var drawTool = (0, _react.useRef)();
  var printMapRef = (0, _react.useRef)(null); // 用于挂载临时地图的 DOM
  var legendContainerRef = (0, _react.useRef)(null);
  var imgRef = (0, _react.useRef)(null);
  var _useState9 = (0, _react.useState)('auto'),
    _useState0 = _slicedToArray(_useState9, 2),
    imgHeight = _useState0[0],
    setImgHeight = _useState0[1];
  (0, _react.useEffect)(function () {
    if (img && visible) {
      var imgEl = new Image();
      imgEl.src = img;
      imgEl.onload = function () {
        var aspectRatio = imgEl.width / imgEl.height;
        var maxWidth = 1200; // Modal 的 width
        var maxHeight = window.innerHeight * 0.8; // 最大高度为屏幕 70%

        var finalWidth = maxWidth;
        var finalHeight = finalWidth / aspectRatio;
        if (finalHeight > maxHeight) {
          finalHeight = maxHeight;
          finalWidth = finalHeight * aspectRatio;
        }
        setImgHeight(finalHeight);
      };
    }
  }, [img, visible]);

  // 初始化绘制工具（用于手动框选）
  (0, _react.useEffect)(function () {
    var tool = new _interaction.Draw({
      type: 'Circle',
      style: _Draw2.drawStyle,
      geometryFunction: (0, _Draw.createBox)()
    });
    tool.setActive(false);
    tool.on('drawstart', function () {
      mainMap.showTip('再次点击确定结束点');
    });
    tool.on('drawend', function (event) {
      mainMap.showTip('鼠标左键确定起始点');
      mainMap.getView().fit(event.feature.getGeometry().getExtent(), {
        maxZoom: 20,
        duration: 500
      });
    });
    drawTool.current = tool;
    mainMap.addInteraction(tool);
    return function () {
      mainMap.removeInteraction(tool);
      mainMap.hideTip();
    };
  }, []);

  // 处理范围选择变化
  var onRangeChange = function onRangeChange(val) {
    setRangeType(val);
    if (val === '1') {
      mainMap.hideTip();
      drawTool.current.setActive(false);
    } else {
      mainMap.showTip('鼠标左键确定起始点');
      drawTool.current.setActive(true);
    }
  };

  // 渲染预览图
  var onFinish = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(values) {
      var view, center, zoom, baseLayers, visibleLayers, businessLayers, tempMap, container, canvas, url;
      return _regenerator().w(function (_context) {
        while (1) switch (_context.n) {
          case 0:
            setFormVal(values);

            // 获取当前主地图的视图状态
            view = mainMap.getView();
            center = view.getCenter();
            zoom = view.getZoom(); // 克隆底图
            baseLayers = (0, _lodash.cloneDeep)(mainMap.baseLayer || []); // 获取所有可见业务图层（排除底图、Highlight 等）
            visibleLayers = mainMap.getVisibleLayersByKeys(); // 返回带 key 的可见图层
            businessLayers = visibleLayers.filter(function (layer) {
              return !baseLayers.some(function (bl) {
                return bl.key === layer.key;
              });
            }).map(function (layer) {
              return (0, _lodash.cloneDeep)(layer);
            }); // 创建临时地图
            tempMap = new _ol.Map({
              target: printMapRef.current,
              controls: (0, _control.defaults)({
                zoom: false,
                attribution: false
              }).extend([].concat(_toConsumableArray(showEagleEye ? [new _control.OverviewMap({
                layers: (0, _lodash.cloneDeep)(baseLayers),
                collapsed: false
                // className: 'custom-overviewmap-extra',
              })] : []), _toConsumableArray(showScale ? [new _control.ScaleLine({
                units: 'metric',
                bar: true,
                text: true,
                minWidth: 125,
                className: 'ol-map-custom-scaleLine-right'
              })] : []))),
              layers: [].concat(_toConsumableArray(baseLayers), _toConsumableArray(businessLayers)),
              // layers: [osmLayer1],
              view: new _ol.View({
                center: center,
                zoom: zoom,
                projection: 'EPSG:4326',
                constrainResolution: true
              }),
              pixelRatio: 2 // 提高截图清晰度
            }); // setTimeout(() => {
            //     // ✅ 使用原始参数重新生成底图图层
            //     // const overviewBaseLayers = cloneDeep(mainMap.getBaseLayers(mainMap.baseLayerParams));
            //     // console.log(11111, overviewBaseLayers);
            //     const overviewMapControl = new OverviewMap({
            //         layers: [osmLayer2],
            //         collapsed: false,
            //         className: 'custom-overviewmap',
            //     });
            //     tempMap.addControl(overviewMapControl);
            //     tempMap.updateSize();
            // }, 100);
            // 强制重绘

            setTimeout(function () {
              tempMap.updateSize();
            }, 200);

            // 等待图层加载完成（简单延迟，可优化为监听 loadend）
            _context.n = 1;
            return new Promise(function (resolve) {
              return setTimeout(resolve, 800);
            });
          case 1:
            // return;
            // return;
            // 截图整个制图区域（包含地图 + 图例）
            container = printMapRef.current.closest('.mapr-print-container');
            _context.n = 2;
            return (0, _html2canvas["default"])(container, {
              useCORS: true,
              allowTaint: false,
              scale: 2,
              backgroundColor: null
            });
          case 2:
            canvas = _context.v;
            url = canvas.toDataURL('image/png');
            setImg(url);
            setVisible(true);

            // 销毁临时地图
            tempMap.setTarget(null);
          case 3:
            return _context.a(2);
        }
      }, _callee);
    }));
    return function onFinish(_x) {
      return _ref.apply(this, arguments);
    };
  }();
  var onOk = function onOk() {
    if (download) {
      var a = document.createElement('a');
      a.href = img;
      a.download = decodeURIComponent("".concat(formVal.title, ".png"));
      a.style.display = 'none';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    } else {
      (0, _printJs["default"])({
        printable: img,
        // 注意：printJS 接受 data URL
        type: 'image',
        documentTitle: formVal.title || '地图打印',
        imageStyle: 'width:100%;' // 可选样式
      });
      //         const printWindow = window.open('', '_blank');
      //         printWindow.document.write(`
      //     <html>
      //       <head><title>打印预览</title></head>
      //       <body style="margin:0;">
      //         <img src="${img}" style="width:100%;"/>
      //       </body>
      //     </html>
      //   `);
      //         printWindow.document.close();
      //         printWindow.focus();
      //         printWindow.print();
    }
  };
  return /*#__PURE__*/_react["default"].createElement(_Modal["default"], {
    title: TextEnum.toolDraftingPrint,
    onClose: onClose
  }, /*#__PURE__*/_react["default"].createElement(_antd.Form, {
    name: "mapR",
    labelCol: {
      span: 8
    },
    wrapperCol: {
      span: 16
    },
    initialValues: {
      range: '1'
    },
    onFinish: onFinish
  }, /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, {
    label: TextEnum.mapTitle,
    name: "title",
    rules: [{
      required: true,
      message: TextEnum.pleaseInputTitle
    }]
  }, /*#__PURE__*/_react["default"].createElement(_antd.Input, {
    placeholder: TextEnum.pleaseInput
  })), /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, {
    label: TextEnum.downloadRange,
    name: "range"
  }, /*#__PURE__*/_react["default"].createElement(_antd.Select, {
    placeholder: TextEnum.pleaseSelect,
    allowClear: true,
    onChange: onRangeChange
  }, /*#__PURE__*/_react["default"].createElement(_antd.Select.Option, {
    value: "1"
  }, TextEnum.currentView), /*#__PURE__*/_react["default"].createElement(_antd.Select.Option, {
    value: "2"
  }, TextEnum.manualBoxSelect))), /*#__PURE__*/_react["default"].createElement(_antd.Form.Item, {
    wrapperCol: {
      offset: 8,
      span: 16
    }
  }, /*#__PURE__*/_react["default"].createElement(_antd.Button, {
    type: "primary",
    htmlType: "submit"
  }, TextEnum.preview))), visible && /*#__PURE__*/_react["default"].createElement(_antd.Modal, {
    visible: visible,
    title: TextEnum.preview,
    onCancel: function onCancel() {
      return setVisible(false);
    },
    width: 1400,
    centered: true,
    onOk: onOk,
    okText: download ? TextEnum.download : TextEnum.print,
    cancelText: TextEnum.cancel
  }, /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      minHeight: '200px',
      maxHeight: '80vh',
      overflow: 'auto'
    }
  }, /*#__PURE__*/_react["default"].createElement("img", {
    ref: imgRef,
    src: img,
    alt: "\u5236\u56FE\u9884\u89C8",
    style: {
      width: 'auto',
      height: 'auto',
      maxWidth: '100%',
      objectFit: 'contain',
      display: 'block'
    }
  }))), /*#__PURE__*/_react["default"].createElement("div", {
    ref: printMapRef,
    className: "mapr-print-container",
    style: {
      position: 'absolute',
      left: '-9999px',
      width: 1400,
      height: 600,
      background: '#fff',
      padding: '20px',
      boxSizing: 'border-box'
    }
  }, showLegend && /*#__PURE__*/_react["default"].createElement("div", {
    ref: legendContainerRef,
    style: {
      position: 'absolute',
      bottom: '20px',
      left: '20px',
      maxWidth: '300px',
      zIndex: 1000
    }
  }, /*#__PURE__*/_react["default"].createElement(_legend["default"], {
    className: "extra-legend"
  }))));
}
//# sourceMappingURL=index.js.map
