import { j as createComponent, x as scrollTargetProp, k as getCurrentInstance, F as ref, p as computed, y as watch, B as onBeforeUnmount, T as cleanEvt, U as addEvt, z as getScrollTarget, q as h, V as Transition, s as hSlot, W as stopAndPrevent, _ as _export_sfc, a as defineComponent, r as resolveComponent, c as createBlock, o as openBlock, w as withCtx, b as createVNode, g as createBaseVNode, h as createElementBlock, M as createCommentVNode, e as QBtn, X as QSpinner, Q as QIcon, P as Fragment, R as renderList, S as normalizeClass, O as toDisplayString, f as withModifiers, i as createTextVNode } from "./index-BRudWVF6.js";
import { Q as QSeparator } from "./QSeparator-2SNNJjxi.js";
import { u as useTransitionProps, a as useModelToggleEmits, v as validateOffset, b as validatePosition, c as useModelToggleProps, d as useAnchorStaticProps, p as parsePosition, e as useTick, f as useTransition, g as useScrollTarget, h as useAnchor, i as useModelToggle, j as usePortal, k as addClickOutside, r as removeClickOutside, s as setPosition, l as clearSelection, A as AppHeader } from "./AppHeader-DugPHj8B.js";
import { b as useTimeout } from "./use-id-Bga_UBPy.js";
import { Q as QCardSection } from "./QCardSection-BEf1jKxd.js";
import { Q as QCard } from "./QCard-S3y3u9tH.js";
import { Q as QPage } from "./QPage-y4zftl3-.js";
import { u as utils } from "./utils-DT9w33jF.js";
const QTooltip = createComponent({
  name: "QTooltip",
  inheritAttrs: false,
  props: {
    ...useAnchorStaticProps,
    ...useModelToggleProps,
    ...useTransitionProps,
    maxHeight: {
      type: String,
      default: null
    },
    maxWidth: {
      type: String,
      default: null
    },
    transitionShow: {
      ...useTransitionProps.transitionShow,
      default: "jump-down"
    },
    transitionHide: {
      ...useTransitionProps.transitionHide,
      default: "jump-up"
    },
    anchor: {
      type: String,
      default: "bottom middle",
      validator: validatePosition
    },
    self: {
      type: String,
      default: "top middle",
      validator: validatePosition
    },
    offset: {
      type: Array,
      default: () => [14, 14],
      validator: validateOffset
    },
    scrollTarget: scrollTargetProp,
    delay: {
      type: Number,
      default: 0
    },
    hideDelay: {
      type: Number,
      default: 0
    },
    persistent: Boolean
  },
  emits: [
    ...useModelToggleEmits
  ],
  setup(props, { slots, emit, attrs }) {
    let unwatchPosition, observer;
    const vm = getCurrentInstance();
    const { proxy: { $q } } = vm;
    const innerRef = ref(null);
    const showing = ref(false);
    const anchorOrigin = computed(() => parsePosition(props.anchor, $q.lang.rtl));
    const selfOrigin = computed(() => parsePosition(props.self, $q.lang.rtl));
    const hideOnRouteChange = computed(() => props.persistent !== true);
    const { registerTick, removeTick } = useTick();
    const { registerTimeout } = useTimeout();
    const { transitionProps, transitionStyle } = useTransition(props);
    const { localScrollTarget, changeScrollEvent, unconfigureScrollTarget } = useScrollTarget(props, configureScrollTarget);
    const { anchorEl, canShow, anchorEvents } = useAnchor({ showing, configureAnchorEl });
    const { show, hide } = useModelToggle({
      showing,
      canShow,
      handleShow,
      handleHide,
      hideOnRouteChange,
      processOnMount: true
    });
    Object.assign(anchorEvents, { delayShow, delayHide });
    const { showPortal, hidePortal, renderPortal } = usePortal(vm, innerRef, renderPortalContent, "tooltip");
    if ($q.platform.is.mobile === true) {
      const clickOutsideProps = {
        anchorEl,
        innerRef,
        onClickOutside(e) {
          hide(e);
          if (e.target.classList.contains("q-dialog__backdrop")) {
            stopAndPrevent(e);
          }
          return true;
        }
      };
      const hasClickOutside = computed(
        () => (
          // it doesn't has external model
          // (null is the default value)
          props.modelValue === null && props.persistent !== true && showing.value === true
        )
      );
      watch(hasClickOutside, (val) => {
        const fn = val === true ? addClickOutside : removeClickOutside;
        fn(clickOutsideProps);
      });
      onBeforeUnmount(() => {
        removeClickOutside(clickOutsideProps);
      });
    }
    function handleShow(evt) {
      showPortal();
      registerTick(() => {
        observer = new MutationObserver(() => updatePosition());
        observer.observe(innerRef.value, { attributes: false, childList: true, characterData: true, subtree: true });
        updatePosition();
        configureScrollTarget();
      });
      if (unwatchPosition === void 0) {
        unwatchPosition = watch(
          () => $q.screen.width + "|" + $q.screen.height + "|" + props.self + "|" + props.anchor + "|" + $q.lang.rtl,
          updatePosition
        );
      }
      registerTimeout(() => {
        showPortal(true);
        emit("show", evt);
      }, props.transitionDuration);
    }
    function handleHide(evt) {
      removeTick();
      hidePortal();
      anchorCleanup();
      registerTimeout(() => {
        hidePortal(true);
        emit("hide", evt);
      }, props.transitionDuration);
    }
    function anchorCleanup() {
      if (observer !== void 0) {
        observer.disconnect();
        observer = void 0;
      }
      if (unwatchPosition !== void 0) {
        unwatchPosition();
        unwatchPosition = void 0;
      }
      unconfigureScrollTarget();
      cleanEvt(anchorEvents, "tooltipTemp");
    }
    function updatePosition() {
      setPosition({
        targetEl: innerRef.value,
        offset: props.offset,
        anchorEl: anchorEl.value,
        anchorOrigin: anchorOrigin.value,
        selfOrigin: selfOrigin.value,
        maxHeight: props.maxHeight,
        maxWidth: props.maxWidth
      });
    }
    function delayShow(evt) {
      if ($q.platform.is.mobile === true) {
        clearSelection();
        document.body.classList.add("non-selectable");
        const target = anchorEl.value;
        const evts = ["touchmove", "touchcancel", "touchend", "click"].map((e) => [target, e, "delayHide", "passiveCapture"]);
        addEvt(anchorEvents, "tooltipTemp", evts);
      }
      registerTimeout(() => {
        show(evt);
      }, props.delay);
    }
    function delayHide(evt) {
      if ($q.platform.is.mobile === true) {
        cleanEvt(anchorEvents, "tooltipTemp");
        clearSelection();
        setTimeout(() => {
          document.body.classList.remove("non-selectable");
        }, 10);
      }
      registerTimeout(() => {
        hide(evt);
      }, props.hideDelay);
    }
    function configureAnchorEl() {
      if (props.noParentEvent === true || anchorEl.value === null) return;
      const evts = $q.platform.is.mobile === true ? [
        [anchorEl.value, "touchstart", "delayShow", "passive"]
      ] : [
        [anchorEl.value, "mouseenter", "delayShow", "passive"],
        [anchorEl.value, "mouseleave", "delayHide", "passive"]
      ];
      addEvt(anchorEvents, "anchor", evts);
    }
    function configureScrollTarget() {
      if (anchorEl.value !== null || props.scrollTarget !== void 0) {
        localScrollTarget.value = getScrollTarget(anchorEl.value, props.scrollTarget);
        const fn = props.noParentEvent === true ? updatePosition : hide;
        changeScrollEvent(localScrollTarget.value, fn);
      }
    }
    function getTooltipContent() {
      return showing.value === true ? h("div", {
        ...attrs,
        ref: innerRef,
        class: [
          "q-tooltip q-tooltip--style q-position-engine no-pointer-events",
          attrs.class
        ],
        style: [
          attrs.style,
          transitionStyle.value
        ],
        role: "tooltip"
      }, hSlot(slots.default)) : null;
    }
    function renderPortalContent() {
      return h(Transition, transitionProps.value, getTooltipContent);
    }
    onBeforeUnmount(anchorCleanup);
    Object.assign(vm.proxy, { updatePosition });
    return renderPortal;
  }
});
const _sfc_main = defineComponent({
  name: "ReelsListPage",
  components: {
    AppHeader
  },
  data() {
    return {
      list: [],
      selectedId: null,
      loading: false,
      publishing: false,
      logText: "",
      // 没有 vip 权限
      noVipPermission: true
    };
  },
  mounted() {
    this.logText = this.getCachedLogText() || "";
    this.fetchList();
    this.getUserInfo();
  },
  methods: {
    async getUserInfo() {
      try {
        let res = await this.$api.get("/api/main/user/info");
        if (res) {
          this.noVipPermission = res.status !== 1;
        }
      } catch (err) {
        this.url = url;
      }
    },
    storageKey() {
      return "fbhelper.reels.selectedId";
    },
    logStorageKey() {
      return "fbhelper.reels.lastPublishLog";
    },
    getCachedSelectedId() {
      if (typeof localStorage === "undefined") return null;
      return localStorage.getItem(this.storageKey()) || null;
    },
    setCachedSelectedId(id) {
      if (typeof localStorage === "undefined") return;
      if (!id) localStorage.removeItem(this.storageKey());
      else localStorage.setItem(this.storageKey(), String(id));
    },
    getCachedLogText() {
      if (typeof localStorage === "undefined") return "";
      return localStorage.getItem(this.logStorageKey()) || "";
    },
    setLogText(text) {
      this.logText = text || "";
      if (typeof localStorage === "undefined") return;
      if (!text) localStorage.removeItem(this.logStorageKey());
      else localStorage.setItem(this.logStorageKey(), String(text));
    },
    nowText() {
      const d = /* @__PURE__ */ new Date();
      const y = d.getFullYear();
      const mo = String(d.getMonth() + 1).padStart(2, "0");
      const da = String(d.getDate()).padStart(2, "0");
      const h2 = String(d.getHours()).padStart(2, "0");
      const mi = String(d.getMinutes()).padStart(2, "0");
      const s = String(d.getSeconds()).padStart(2, "0");
      return `${y}-${mo}-${da} ${h2}:${mi}:${s}`;
    },
    selectItem(id) {
      this.selectedId = id;
      this.setCachedSelectedId(id);
    },
    pickLatestId(items) {
      if (!items || items.length === 0) return null;
      const parseTime = (it) => {
        const d = it && it.publishDate ? String(it.publishDate) : "";
        const t = it && it.publishTime ? String(it.publishTime) : "";
        const dt = new Date(`${d} ${t}`.replace(/\./g, "-"));
        const ms = dt.getTime();
        if (!Number.isNaN(ms)) return ms;
        const maybeNum = Number(it && it.id);
        return Number.isNaN(maybeNum) ? 0 : maybeNum;
      };
      return items.reduce((best, cur) => {
        if (!best) return cur;
        return parseTime(cur) > parseTime(best) ? cur : best;
      }, null).id;
    },
    async fetchList() {
      this.loading = true;
      try {
        const res = await this.$api.post("/api/main/reels/list");
        this.list = res || [];
        if (this.list.length === 0) {
          this.selectedId = null;
          this.setCachedSelectedId(null);
          return;
        }
        const cachedId = this.getCachedSelectedId();
        const cachedItem = cachedId ? this.list.find((i) => String(i.id) === String(cachedId)) : null;
        if (cachedItem) {
          this.selectedId = cachedItem.id;
          return;
        }
        const querySelectedId = this.$route && this.$route.query ? this.$route.query.selectedId : null;
        const queryItem = querySelectedId ? this.list.find((i) => String(i.id) === String(querySelectedId)) : null;
        if (queryItem) {
          this.selectItem(queryItem.id);
          this.$router.replace({ path: "/reels/list" });
          return;
        }
        const latestId = this.pickLatestId(this.list);
        this.selectItem(latestId);
      } catch (err) {
      } finally {
        this.loading = false;
      }
    },
    formatInterval(minutes) {
      if (!minutes) return "0分钟";
      const num = Number(minutes);
      if (num % 60 === 0) {
        return num / 60 + " 小时";
      }
      return num + " 分钟";
    },
    onEdit(item) {
      this.$router.push({ path: "/reels/add", query: { id: item.id } });
    },
    async onDelete(item) {
      try {
        await this.$api.post("/api/main/reels/delete", { ids: [item.id] });
        utils.notifySuccess("删除成功");
        this.list = this.list.filter((i) => i.id !== item.id);
        if (String(this.selectedId) === String(item.id)) {
          const nextId = this.pickLatestId(this.list);
          this.selectItem(nextId);
        }
      } catch (err) {
        utils.notifyError("删除功能暂未对接");
      }
    },
    getChrome() {
      if (typeof window === "undefined") return null;
      return window.chrome || null;
    },
    async getActiveTab() {
      const chrome = this.getChrome();
      if (!chrome || !chrome.tabs || !chrome.tabs.query) return null;
      const tabs = await new Promise((resolve) => {
        chrome.tabs.query({ active: true, currentWindow: true }, resolve);
      });
      return tabs && tabs[0] ? tabs[0] : null;
    },
    async onPublish() {
      if (!this.selectedId) return;
      const item = this.list.find((i) => i.id === this.selectedId);
      if (!item) return;
      this.publishing = true;
      this.setLogText("正在检查环境...");
      try {
        const tab = await this.getActiveTab();
        if (!tab) {
          throw new Error("无法获取当前标签页信息");
        }
        if (!tab.url || !tab.url.includes("business.facebook.com/latest/bulk_upload_compose")) {
          utils.notifyError("请先打开 Facebook 批量上传页面");
          this.setLogText("当前不是 Facebook 批量上传页面");
          return;
        }
        this.setLogText("环境检查通过，正在启动脚本...");
        const chrome = this.getChrome();
        if (!chrome || !chrome.scripting) {
          throw new Error("缺少 scripting 权限或不在扩展环境");
        }
        let total = document.querySelectorAll('input[type="checkbox"][aria-label="添加"]').length - 1;
        const formData = {
          startDay: item.publishDate,
          startHour: Number(item.publishTime.split(":")[0]),
          startMinute: Number(item.publishTime.split(":")[1]),
          interval: Number(item.intervalMinutes),
          total,
          description: item.description
        };
        await chrome.scripting.executeScript({
          target: { tabId: tab.id },
          world: "MAIN",
          args: [formData],
          func: (data) => {
            window.__FB_HELPER_DATA__ = data;
          }
        });
        await chrome.scripting.executeScript({
          target: { tabId: tab.id },
          world: "MAIN",
          files: ["assets/task.min.js"]
        });
        this.setLogText(`${this.nowText()} 脚本已启动`);
        this.publishing = false;
        setTimeout(() => {
          window.close();
        }, 50);
        return;
      } catch (err) {
        this.setLogText(`执行出错: ${err.message}`);
        console.error(err);
      } finally {
        this.publishing = false;
      }
    }
  }
});
const _hoisted_1 = { class: "col column q-pa-md scroll" };
const _hoisted_2 = { class: "row items-center justify-between q-mb-md" };
const _hoisted_3 = { class: "col scroll" };
const _hoisted_4 = {
  key: 0,
  class: "row justify-center q-pa-md"
};
const _hoisted_5 = {
  key: 1,
  class: "column flex-center text-grey q-pa-lg q-mt-lg",
  style: { "height": "200px" }
};
const _hoisted_6 = {
  key: 0,
  class: "column flex-center"
};
const _hoisted_7 = { key: 1 };
const _hoisted_8 = {
  key: 2,
  class: "q-gutter-y-sm"
};
const _hoisted_9 = { class: "q-mr-md q-pt-xs" };
const _hoisted_10 = { class: "col" };
const _hoisted_11 = { class: "row justify-between items-center q-mb-sm" };
const _hoisted_12 = { class: "text-caption text-grey-8 row items-center" };
const _hoisted_13 = { class: "text-weight-medium" };
const _hoisted_14 = { class: "row q-gutter-x-sm" };
const _hoisted_15 = {
  class: "text-body2 text-grey-9 ellipsis-2-lines",
  style: { "word-break": "break-all" }
};
const _hoisted_16 = {
  key: 0,
  class: "bg-white q-px-md q-pb-md q-pt-0"
};
const _hoisted_17 = { class: "q-mb-sm text-caption text-grey-8 row items-center" };
function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
  const _component_app_header = resolveComponent("app-header");
  return openBlock(), createBlock(QPage, { class: "popup-page bg-white column" }, {
    default: withCtx(() => [
      createVNode(_component_app_header),
      createBaseVNode("div", _hoisted_1, [
        createBaseVNode("div", _hoisted_2, [
          _cache[2] || (_cache[2] = createBaseVNode("div", { class: "text-subtitle1 text-weight-bold text-grey-9" }, "批量发布任务", -1)),
          !_ctx.noVipPermission ? (openBlock(), createBlock(QBtn, {
            key: 0,
            label: "+ 添加内容",
            color: "negative",
            rounded: "",
            outline: "",
            onClick: _cache[0] || (_cache[0] = ($event) => _ctx.$router.push("/reels/add"))
          })) : createCommentVNode("", true)
        ]),
        createBaseVNode("div", _hoisted_3, [
          _ctx.loading ? (openBlock(), createElementBlock("div", _hoisted_4, [
            createVNode(QSpinner, {
              color: "primary",
              size: "2em"
            })
          ])) : _ctx.list.length === 0 ? (openBlock(), createElementBlock("div", _hoisted_5, [
            createVNode(QIcon, {
              name: _ctx.noVipPermission ? "block" : "assignment_turned_in",
              size: "48px",
              class: "q-mb-sm text-grey-4"
            }, null, 8, ["name"]),
            _ctx.noVipPermission ? (openBlock(), createElementBlock("div", _hoisted_6, [
              _cache[3] || (_cache[3] = createBaseVNode("div", null, "权限不足，请升级为VIP用户", -1)),
              createVNode(QBtn, {
                label: "开通VIP会员",
                color: "primary",
                class: "q-mt-md",
                unelevated: "",
                rounded: "",
                onClick: _cache[1] || (_cache[1] = ($event) => _ctx.$router.push("/activation"))
              })
            ])) : (openBlock(), createElementBlock("div", _hoisted_7, "暂无任务，请点击右上角添加"))
          ])) : (openBlock(), createElementBlock("div", _hoisted_8, [
            (openBlock(true), createElementBlock(Fragment, null, renderList(_ctx.list, (item) => {
              return openBlock(), createBlock(QCard, {
                key: item.id,
                flat: "",
                class: normalizeClass(["cursor-pointer transition-generic", _ctx.selectedId === item.id ? "bg-green-1 border-green" : "bg-grey-2"]),
                style: { "border-radius": "10px" },
                onClick: ($event) => _ctx.selectItem(item.id)
              }, {
                default: withCtx(() => [
                  createVNode(QCardSection, { class: "row no-wrap items-start q-pa-md" }, {
                    default: withCtx(() => [
                      createBaseVNode("div", _hoisted_9, [
                        createVNode(QIcon, {
                          name: _ctx.selectedId === item.id ? "check_circle" : "radio_button_unchecked",
                          color: _ctx.selectedId === item.id ? "positive" : "grey-5",
                          size: "24px"
                        }, null, 8, ["name", "color"])
                      ]),
                      createBaseVNode("div", _hoisted_10, [
                        createBaseVNode("div", _hoisted_11, [
                          createBaseVNode("div", _hoisted_12, [
                            createVNode(QIcon, {
                              name: "event",
                              size: "14px",
                              class: "q-mr-xs text-grey-6"
                            }),
                            createBaseVNode("span", _hoisted_13, toDisplayString(item.publishDate) + " " + toDisplayString(item.publishTime), 1),
                            createVNode(QSeparator, {
                              vertical: "",
                              class: "q-mx-sm"
                            }),
                            createVNode(QIcon, {
                              name: "timer",
                              size: "14px",
                              class: "q-mr-xs text-grey-6"
                            }),
                            createBaseVNode("span", null, toDisplayString(_ctx.formatInterval(item.intervalMinutes)), 1)
                          ]),
                          createBaseVNode("div", _hoisted_14, [
                            createVNode(QBtn, {
                              flat: "",
                              dense: "",
                              round: "",
                              icon: "edit",
                              color: "primary",
                              size: "sm",
                              onClick: withModifiers(($event) => _ctx.onEdit(item), ["stop"])
                            }, {
                              default: withCtx(() => [
                                createVNode(QTooltip, null, {
                                  default: withCtx(() => [..._cache[4] || (_cache[4] = [
                                    createTextVNode("编辑", -1)
                                  ])]),
                                  _: 1
                                })
                              ]),
                              _: 1
                            }, 8, ["onClick"]),
                            createVNode(QBtn, {
                              flat: "",
                              dense: "",
                              round: "",
                              icon: "delete",
                              color: "grey-6",
                              size: "sm",
                              onClick: withModifiers(($event) => _ctx.onDelete(item), ["stop"])
                            }, {
                              default: withCtx(() => [
                                createVNode(QTooltip, null, {
                                  default: withCtx(() => [..._cache[5] || (_cache[5] = [
                                    createTextVNode("删除", -1)
                                  ])]),
                                  _: 1
                                })
                              ]),
                              _: 1
                            }, 8, ["onClick"])
                          ])
                        ]),
                        createBaseVNode("div", _hoisted_15, toDisplayString(item.description), 1)
                      ])
                    ]),
                    _: 2
                  }, 1024)
                ]),
                _: 2
              }, 1032, ["class", "onClick"]);
            }), 128))
          ]))
        ])
      ]),
      !_ctx.noVipPermission ? (openBlock(), createElementBlock("div", _hoisted_16, [
        createBaseVNode("div", _hoisted_17, [
          createVNode(QIcon, {
            name: "terminal",
            size: "16px",
            class: "q-mr-xs"
          }),
          createTextVNode(" 执行日志：" + toDisplayString(_ctx.logText || "暂未运行"), 1)
        ]),
        createVNode(QBtn, {
          label: "立即发布",
          color: "positive",
          class: "full-width",
          rounded: "",
          unelevated: "",
          icon: "rocket_launch",
          disable: !_ctx.selectedId,
          loading: _ctx.publishing,
          onClick: _ctx.onPublish
        }, null, 8, ["disable", "loading", "onClick"])
      ])) : createCommentVNode("", true)
    ]),
    _: 1
  });
}
const list = /* @__PURE__ */ _export_sfc(_sfc_main, [["render", _sfc_render], ["__scopeId", "data-v-dfbe9a64"]]);
export {
  list as default
};
