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); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
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 { useSetState } from 'ahooks';
import { Button, Checkbox, Form, message, Radio } from 'antd';
import dayjs from 'dayjs';
import { cloneDeep } from 'lodash';
import { useEffect, useState } from 'react';
import { VmExtraTab, VmWrapper } from '..';
import useSettings from "../../_hooks/useSettings";
import { getBackUrl, getPreviewUrl } from "../../_service";
import { ChannelOfflineIcon, Rect1Icon, Rect4Icon, Rect9Icon, ShrinkIcon } from "../../_util/iconSvgHtml";
import VmFilter, { VMDatePicker, VMInput } from "../vm-filter";
import { VmTabs } from "../vm-tabs";
import HistoryGrid from "./HistoryGrid";
import "./index.less";
import RealtimeGrid from "./RealtimeGrid";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
var VmVideo = function VmVideo(_ref) {
  var _ref$channels = _ref.channels,
    channels = _ref$channels === void 0 ? [] : _ref$channels;
  var _useSettings = useSettings(),
    isDark = _useSettings.isDark;
  var _Form$useForm = Form.useForm(),
    _Form$useForm2 = _slicedToArray(_Form$useForm, 1),
    form = _Form$useForm2[0];
  var _useState = useState('1'),
    _useState2 = _slicedToArray(_useState, 2),
    tabKey = _useState2[0],
    setTabKey = _useState2[1];
  var _useState3 = useState('4'),
    _useState4 = _slicedToArray(_useState3, 2),
    mode = _useState4[0],
    setMode = _useState4[1];
  var _useState5 = useState([]),
    _useState6 = _slicedToArray(_useState5, 2),
    checkedChannels = _useState6[0],
    setCheckedChannels = _useState6[1];
  var _useSetState = useSetState({
      dateType: 'custom',
      datePickerDisabled: true,
      startTime: dayjs().format('YYYY-MM-DD 00:00:00'),
      endTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      history: {}
    }),
    _useSetState2 = _slicedToArray(_useSetState, 2),
    state = _useSetState2[0],
    setState = _useSetState2[1];
  var dateType = state.dateType,
    datePickerDisabled = state.datePickerDisabled,
    startTime = state.startTime,
    endTime = state.endTime,
    history = state.history;
  useEffect(function () {
    if (dateType === 'custom') {
      setState({
        datePickerDisabled: false
      });
    } else {
      setState({
        datePickerDisabled: true
      });
      if (dateType === 'dayBeforeYesterday') {
        setState({
          startTime: dayjs().subtract(2, 'day').format('YYYY-MM-DD 00:00:00'),
          endTime: dayjs().subtract(2, 'day').format('YYYY-MM-DD 23:59:59')
        });
      } else if (dateType === 'yesterday') {
        setState({
          startTime: dayjs().subtract(1, 'day').format('YYYY-MM-DD 00:00:00'),
          endTime: dayjs().subtract(1, 'day').format('YYYY-MM-DD 23:59:59')
        });
      } else if (dateType === 'today') {
        setState({
          startTime: dayjs().format('YYYY-MM-DD 00:00:00'),
          endTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
        });
      }
    }
  }, [dateType]);
  useEffect(function () {
    if (channels !== null && channels !== void 0 && channels.length && tabKey === '1') {
      var _channels$filter;
      Promise.all(channels === null || channels === void 0 || (_channels$filter = channels.filter(function (ele, index) {
        return index < 4;
      })) === null || _channels$filter === void 0 ? void 0 : _channels$filter.map(function (ele) {
        return getPreviewUrl({
          channelNum: ele.channelNum,
          deviceId: ele.videoDeviceId
        });
      })).then(function (res) {
        setCheckedChannels(res.map(function (ele, index) {
          return _objectSpread(_objectSpread({}, ele.data), {}, {
            checked: index < 4
          });
        }));
      });
    } else {}
    if (tabKey === '2') {
      var _channels$;
      form.setFieldsValue({
        channelNum: (_channels$ = channels[0]) === null || _channels$ === void 0 ? void 0 : _channels$.channelNum
      });
    }
  }, [channels, tabKey]);
  var getActiveModeFill = function getActiveModeFill(key) {
    if (isDark) {
      return mode === key ? '#fff' : '#009DFF';
    }
    return mode === key ? '#1677FF' : '#8C8C8C';
  };
  var onHistorySubmit = function onHistorySubmit(values) {
    var channel = channels.find(function (ele) {
      return ele.channelNum === values.channelNum;
    });
    getBackUrl({
      beginTime: startTime,
      endTime: endTime,
      channelNum: values.channelNum,
      deviceId: channel.videoDeviceId
    }).then(function (res) {
      var _data$list;
      var data = (res === null || res === void 0 ? void 0 : res.data) || {};
      if (!(data !== null && data !== void 0 && data.totalTimeUrl) && !((_data$list = data.list) !== null && _data$list !== void 0 && (_data$list = _data$list[0]) !== null && _data$list !== void 0 && _data$list.playbackUrl)) {
        message.info('未查询到视频!');
        return;
      }
      setState({
        history: data
      });
    });
  };
  return /*#__PURE__*/_jsxs("div", {
    className: "vm-video ".concat(isDark ? 'dark' : ''),
    children: [/*#__PURE__*/_jsx(_Fragment, {
      children: /*#__PURE__*/_jsx("div", {
        className: "vm-video-left",
        children: /*#__PURE__*/_jsxs(VmWrapper, {
          title: "\u67E5\u8BE2\u89C6\u9891",
          children: [tabKey === '1' && /*#__PURE__*/_jsx("div", {
            className: "vm-video-left-channels",
            children: checkedChannels === null || checkedChannels === void 0 ? void 0 : checkedChannels.map(function (ele, index) {
              var color = ele.checked ? isDark ? '#009DFF' : '#1677FF' : isDark ? '#fff' : '#595959';
              return /*#__PURE__*/_jsx("div", {
                className: "channels--item",
                children: /*#__PURE__*/_jsxs(Checkbox, {
                  checked: ele.checked,
                  onChange: function onChange(e) {
                    var list = cloneDeep(checkedChannels);
                    if (e.target.checked) {
                      getPreviewUrl({
                        channelNum: ele.channelNum,
                        deviceId: ele.deviceId
                      }).then(function (res) {
                        list[index] = _objectSpread({
                          checked: true
                        }, res.data);
                        setCheckedChannels(list);
                      });
                    } else {
                      list[index].checked = false;
                      list[index].url = '';
                      list[index].player = '';
                      setCheckedChannels(list);
                    }
                  },
                  style: {
                    color: color
                  },
                  children: [/*#__PURE__*/_jsx(ChannelOfflineIcon, {
                    fill: color
                  }), ele.channelName]
                })
              }, index);
            })
          }), tabKey === '2' && /*#__PURE__*/_jsxs("div", {
            className: "vm-video-history",
            children: [/*#__PURE__*/_jsx("div", {
              className: "form",
              children: /*#__PURE__*/_jsxs(Form, {
                form: form,
                name: "history",
                labelCol: {
                  span: 6
                },
                wrapperCol: {
                  span: 18
                },
                onFinish: onHistorySubmit,
                requiredMark: false,
                colon: true,
                initialValues: {
                  beginTime: startTime ? dayjs(startTime) : dayjs().subtract(1, 'day').startOf('day'),
                  endTime: endTime ? dayjs(endTime) : dayjs().subtract(1, 'day').endOf('day')
                },
                autoComplete: "off",
                children: [/*#__PURE__*/_jsx(Form.Item, {
                  label: "",
                  wrapperCol: {
                    span: 24
                  },
                  children: /*#__PURE__*/_jsxs(Radio.Group, {
                    name: "radiogroup",
                    size: "small",
                    value: dateType,
                    onChange: function onChange(e) {
                      setState({
                        dateType: e.target.value
                      });
                    },
                    style: {
                      whiteSpace: 'nowrap'
                    },
                    children: [/*#__PURE__*/_jsx(Radio, {
                      value: "dayBeforeYesterday",
                      children: "\u524D\u65E5"
                    }), /*#__PURE__*/_jsx(Radio, {
                      value: "yesterday",
                      children: "\u6628\u65E5"
                    }), /*#__PURE__*/_jsx(Radio, {
                      value: "today",
                      children: "\u4ECA\u65E5"
                    }), /*#__PURE__*/_jsx(Radio, {
                      value: "custom",
                      children: "\u81EA\u5B9A\u4E49"
                    })]
                  })
                }), /*#__PURE__*/_jsx(Form.Item, {
                  label: "\u5F00\u59CB\u65F6\u95F4",
                  name: "beginTime",
                  rules: [{
                    required: true,
                    message: '请输入开始时间'
                  }],
                  children: /*#__PURE__*/_jsx(VMDatePicker, {
                    style: {
                      width: 180
                    },
                    showTime: true,
                    disabled: datePickerDisabled,
                    dropdownClassName: "date-dark",
                    classNames: {
                      popup: {
                        root: "date-dark"
                      }
                    }
                  })
                }), /*#__PURE__*/_jsx(Form.Item, {
                  label: "\u7ED3\u675F\u65F6\u95F4",
                  name: "endTime",
                  rules: [{
                    required: true,
                    message: '请输入结束时间'
                  }],
                  children: /*#__PURE__*/_jsx(VMDatePicker, {
                    style: {
                      width: 180
                    },
                    showTime: true,
                    disabled: datePickerDisabled
                  })
                }), /*#__PURE__*/_jsx(Form.Item, {
                  label: "\u89C6\u9891\u901A\u9053",
                  name: "channelNum",
                  rules: [{
                    required: true,
                    message: '请选择视频通道'
                  }],
                  children: /*#__PURE__*/_jsx(VmFilter.VMSelect, {
                    options: checkedChannels === null || checkedChannels === void 0 ? void 0 : checkedChannels.map(function (ele) {
                      return {
                        value: ele.channelNum,
                        label: ele.channelName
                      };
                    }),
                    style: {
                      width: 180
                    }
                  })
                }), /*#__PURE__*/_jsx(Form.Item, {
                  wrapperCol: {
                    span: 24
                  },
                  style: {
                    textAlign: 'center'
                  },
                  children: /*#__PURE__*/_jsx(Button, {
                    type: "primary",
                    htmlType: "submit",
                    className: "submit-button",
                    children: "\u67E5\u8BE2"
                  })
                })]
              })
            }), /*#__PURE__*/_jsx("div", {
              className: "vm-video-history-row"
            })]
          })]
        })
      })
    }), /*#__PURE__*/_jsxs("div", {
      className: "vm-video-right",
      children: [/*#__PURE__*/_jsx(VmTabs, {
        defaultActiveKey: "1",
        activeKey: tabKey,
        onChange: function onChange(key) {
          setTabKey(key);
          if (key === '2') {
            // extraTabRef.current?.setActiveKey(1)
            setMode('1');
          } else {
            setMode('4');
          }
        },
        items: [{
          label: "\u5B9E\u65F6\u89C6\u9891",
          key: '1'
        }, {
          label: "\u5386\u53F2\u89C6\u9891",
          key: '2'
        }],
        tabBarExtraContent: tabKey === '1' ? /*#__PURE__*/_jsx(VmExtraTab, {
          style: {
            width: '92px'
          },
          value: mode,
          data: [{
            title: /*#__PURE__*/_jsx(Rect1Icon, {
              fill: getActiveModeFill('1')
            }),
            name: '1分屏',
            key: '1'
          }, {
            title: /*#__PURE__*/_jsx(Rect4Icon, {
              fill: getActiveModeFill('4')
            }),
            name: '4分屏',
            key: '4'
          }, {
            title: /*#__PURE__*/_jsx(Rect9Icon, {
              fill: getActiveModeFill('9')
            }),
            name: '9分屏',
            key: '9'
          }],
          onChange: function onChange(key) {
            setMode(key);
          }
        }) : /*#__PURE__*/_jsx(_Fragment, {})
      }), /*#__PURE__*/_jsx("div", {
        className: "vm-video-content _".concat(mode),
        children: tabKey === '1' ? getGridItems(mode, checkedChannels === null || checkedChannels === void 0 ? void 0 : checkedChannels.filter(function (ele) {
          return ele.checked;
        }), setCheckedChannels) : /*#__PURE__*/_jsx(HistoryGrid, {
          channel: history
        })
      })]
    })]
  });
};
export default VmVideo;
var getGridItems = function getGridItems(latestGrid, channels, setCheckedChannels) {
  var items = [];
  var _loop = function _loop(i) {
    var element = /*#__PURE__*/_jsx(RealtimeGrid, {
      channel: channels[i] || {
        channelNum: '',
        channelId: ''
      },
      onClose: function onClose() {
        var list = cloneDeep(channels);
        list[i].checked = false;
        list[i].url = '';
        list[i].player = '';
        setCheckedChannels(list);
      },
      scale: 1
      // onScreenshot={onScreenshot}
    }, i);
    items.push(element);
  };
  for (var i = 0; i < Number(latestGrid); i++) {
    _loop(i);
  }
  return items;
};
export var Filter = function Filter(isDark, isShrink, setFilterVal) {
  return /*#__PURE__*/_jsxs("div", {
    className: "vm-video-left-filter",
    children: [/*#__PURE__*/_jsx("div", {
      className: "vm-video-left-filter-input",
      children: /*#__PURE__*/_jsx(VMInput, {
        onValChange: function onValChange(val) {
          setFilterVal(val);
        }
      })
    }), /*#__PURE__*/_jsx("div", {
      className: "vm-video-left-filter-btn",
      onClick: function onClick() {
        return setIsShrink(!isShrink);
      },
      children: /*#__PURE__*/_jsx(ShrinkIcon, {
        fill: isDark ? '#009DFF' : '#595959',
        style: {
          transform: isShrink ? 'rotate(180deg)' : ''
        }
      })
    })]
  });
};