import PageContainerBehavior from "../../../../core/behavior/page-container.behavior";
import { evaluateOrderGoodsMethod } from "../../request";
import { upload } from "../../../../lib/request/upload";
import { OfflineEvaluateModel } from "../../model/evaluate.model";
function withMediaType(url: string, type: "image" | "video") {
  if (!url) return url;
  const hasQuery = url.includes("?");
  const hasHash = url.includes("#");
  if (hasHash) {
    const [base, hash] = url.split("#");
    return `${base}${hasQuery ? "&" : "?"}type=${type}#${hash ?? ""}`;
  }
  return `${url}${hasQuery ? "&" : "?"}type=${type}`;
}
Page({
  behaviors: [PageContainerBehavior],
  data: {
    orderId: "",
    service: {} as OfflineEvaluateModel,
    scoreServiceQuality: 0,
    scoreAttitude: 0,
    scoreEnvironment: 0,
    rateColor: "#F7BA2A",
    content: "",
    mediaList: [] as { path: string; type: "image" | "video" }[],
    canPublish: false,
    videoFullscreen: false,
  },

  onLoad(options: Record<string, string>) {
    let service = {} as OfflineEvaluateModel;
    if (options.goodsInfo) {
      const goods = JSON.parse(decodeURIComponent(options.goodsInfo));
      service = {
        lineId: goods.id || 0,
        patientConditioningRecordId: goods.patientConditioningRecordId || 0,
        patientConditioningProgramId: goods.patientConditioningProgramId || 0,
        operateTime: goods.operateTime || "",
        operateBy: goods.operateBy || "",
        conditioningProgramSupplierName: goods.conditioningProgramSupplierName || "",
        image: goods.conditioningProgramPhoto || "",
        name: goods.conditioningProgramName || "",
      };
      console.log(service, "service===");
    }
    this.setData({
      service,
      canPublish: this._checkCanPublish(0, 0, 0),
    });
  },

  _checkCanPublish(
    quality: number,
    attitude: number,
    environment: number
  ): boolean {
    return quality > 0 && attitude > 0 && environment > 0;
  },
  _updateCanPublish() {
    const { scoreServiceQuality, scoreAttitude, scoreEnvironment } = this.data;
    this.setData({
      canPublish: this._checkCanPublish(
        scoreServiceQuality,
        scoreAttitude,
        scoreEnvironment
      ),
    });
  },
  onScoreServiceQuality(e: WechatMiniprogram.CustomEvent<{ value: number }>) {
    const scoreServiceQuality = e.detail?.value ?? 0;
    this.setData({ scoreServiceQuality }, () => this._updateCanPublish());
  },
  onScoreAttitude(e: WechatMiniprogram.CustomEvent<{ value: number }>) {
    const scoreAttitude = e.detail?.value ?? 0;
    this.setData({ scoreAttitude }, () => this._updateCanPublish());
  },
  onScoreEnvironment(e: WechatMiniprogram.CustomEvent<{ value: number }>) {
    const scoreEnvironment = e.detail?.value ?? 0;
    this.setData({ scoreEnvironment }, () => this._updateCanPublish());
  },
  onContentInput(e: WechatMiniprogram.Input) {
    const content = e.detail?.value ?? "";
    this.setData({ content });
  },
  onChooseMedia() {
    const current = this.data.mediaList.length;
    if (current >= 9) {
      wx.showToast({ title: "图片和视频总数不能超过9个", icon: "none" });
      return;
    }
    const remain = 9 - current;
    wx.chooseMedia({
      count: remain,
      mediaType: ["image", "video"],
      sourceType: ["album", "camera"],
      maxDuration: 30,
      camera: "back",
      success: (res) => {
        const list = res.tempFiles.map((f) => ({
          path: f.tempFilePath,
          type: (f.fileType === "video" ? "video" : "image") as "image" | "video",
        }));
        const oldLength = this.data.mediaList.length;
        const next = [...this.data.mediaList, ...list].slice(0, 9);
        this.setData({ mediaList: next });

        // 选取本地媒体后，调用上传接口上传到服务器
        list.forEach((item, idx) => {
          const index = oldLength + idx;
          upload<string, any>({
            params: { name: "file", file: item.path },
            transform({ data }: any): string {
              return (data as any)?.url || (data as any);
            },
          }).then(
            (url) => {
              const key = `mediaList[${index}].path`;
              this.setData({ [key]: url });
            },
            (error: any) => {
              wx.showToast({
                title: error?.errMsg || "上传失败",
                icon: "none",
              });
              const mediaList = this.data.mediaList.filter((_, i) => i !== index);
              this.setData({ mediaList });
            }
          );
        });
      },
    });
  },
  onRemoveMedia(e: WechatMiniprogram.TouchEvent) {
    const index = e.currentTarget.dataset.index as number;
    const mediaList = this.data.mediaList.filter((_, i) => i !== index);
    this.setData({ mediaList });
  },
  onPreviewImage(e: WechatMiniprogram.TouchEvent) {
    const url = e.currentTarget.dataset.url as string;
    const urls = this.data.mediaList.filter((m) => m.type === "image").map((m) => m.path);
    if (url && urls.length) {
      wx.previewImage({ current: url, urls });
    }
  },
  onPreviewVideo(e: WechatMiniprogram.TouchEvent) {
    const index = e.currentTarget.dataset.index as number;
    const videoContext = wx.createVideoContext("offline-video-" + index, this);
    videoContext.requestFullScreen({});
  },
  /** 点击图片/视频：原生全屏预览（类似 test 页） */
  onPreviewMedia(e: WechatMiniprogram.TouchEvent) {
    const index = e.currentTarget.dataset.index as number;
    const { mediaList } = this.data;
    if (index < 0 || index >= mediaList.length) return;

    const sources = mediaList.map((m) => ({
      url: m.path,
      type: m.type as "image" | "video",
    }));

    const previewMedia = (wx as any).previewMedia as
      | ((option: { sources: { url: string; type: "image" | "video" }[]; current: number }) => void)
      | undefined;

    if (typeof previewMedia === "function") {
      previewMedia({ sources, current: index });
      return;
    }

    // 低版本兜底：图片用 previewImage，视频用 requestFullScreen
    const current = mediaList[index];
    if (current.type === "image") {
      const urls = mediaList.filter((m) => m.type === "image").map((m) => m.path);
      wx.previewImage({ current: current.path, urls });
      return;
    }
    const ctx = wx.createVideoContext("offline-video-" + index, this);
    ctx.requestFullScreen({});
  },
  onVideoFullscreenChange(e: WechatMiniprogram.VideoFullScreenChange) {
    const fullScreen = !!(e.detail && e.detail.fullScreen);
    this.setData({ videoFullscreen: fullScreen });
  },
  onRemoveService() {
    this.setData({
      service: {} as OfflineEvaluateModel,
    });
  },
  async onPublish() {
    if (!this.data.canPublish) {
      wx.showToast({ title: "请完成三项评分", icon: "none" });
      return;
    }
    try {
      const data = {
        lineId: this.data.service?.lineId,
        patientConditioningRecordId: this.data.service?.patientConditioningRecordId,
        patientConditioningProgramId: this.data.service?.patientConditioningProgramId,
        complianceScore: this.data.scoreServiceQuality,
        qualityScore: this.data.scoreServiceQuality,
        attitudeScore: this.data.scoreAttitude,
        environmentScore: this.data.scoreEnvironment,
        depict: this.data.content,
        imageVideos: this.data.mediaList.map((m) => withMediaType(m.path, m.type)),
      };
      wx.showLoading({ title: "发布中..." });
      await evaluateOrderGoodsMethod(data);
      wx.hideLoading();
      wx.showToast({ title: "发布成功", icon: "success" });
      wx.redirectTo({
        url: `/module/care/pages/care/verifyRecord?id=${this.data.service?.patientConditioningProgramId}`,
      });
    } catch (error: any) {
      wx.hideLoading();
      wx.showToast({ title: error.errMsg || "发布失败", icon: "none" });
    }
  },
});
