import { request } from "../../utils/request";

// components/banner/banner.ts
interface BannerData {
  avatarUrl: string;
  nickName: string;
  userId: string;
  showPopup: boolean;
  reportOptions: Array<{
    id: number;
    text: string;
    checked: boolean;
  }>;
  showOtherInput: boolean;
  otherReason: string;
  uploadedImages: string[];
  description: string;
  state: number;
  isSubmitEnabled: boolean;
}

interface BannerProperties {
  roomInfo: {
    iconUrl?: string;
    name?: string;
    mumId?: string;
    state: number;
  };
}

interface BannerComponent extends WechatMiniprogram.Component.TrivialInstance {
  data: BannerData;
  properties: BannerProperties;
}

const state: Record<number, string> = {
  1: "直播中",
  2: "直播结束",
};
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    roomInfo: {
      type: Object,
      value: {
        iconUrl: "",
        nickname: "",
        mumId: "",
        state: null
      },
      observer: function (
        this: BannerComponent,
        newVal: BannerProperties["roomInfo"]
      ) {
        this.updateRoomInfo(newVal);
      },
    },
    watchNum:{
        type:Number,
        data:0
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    avatarUrl: "",
    nickName: "",
    userId: "",
    state: "",
    showPopup: false,
    reportOptions: [
      { id: 1, text: "价格虚假", checked: false },
      { id: 2, text: "品牌虚假", checked: false },
      { id: 3, text: "色情低俗", checked: false },
      { id: 4, text: "虚假活动", checked: false },
      { id: 5, text: "不良行为", checked: false },
      { id: 6, text: "商品信息虚假", checked: false },
      { id: 7, text: "出售违禁品", checked: false },
      { id: 8, text: "其他", checked: false },
    ],
    showOtherInput: false,
    otherReason: "",
    uploadedImages: [],
    description: "",
    isSubmitEnabled: false,
  },
  lifetimes: {
    attached(this: BannerComponent) {
      this.updateRoomInfo(this.properties.roomInfo);
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    updateRoomInfo(
      this: BannerComponent,
      roomInfo?: BannerProperties["roomInfo"]
    ) {
      const info = roomInfo || this.properties.roomInfo;
      this.setData({
        avatarUrl: info?.iconUrl || "",
        nickName: info?.name || "",
        userId: info?.mumId || "",
        state: state[info?.state ?? 2],
      });
    },
    handOpen(this: WechatMiniprogram.Component.TrivialInstance) {
      this.setData({
        showPopup: true,
        isSubmitEnabled: false,
      });
    },
    closePopup(this: WechatMiniprogram.Component.TrivialInstance) {
      this.setData({
        showPopup: false,
      });
    },

    onOptionChange(this: WechatMiniprogram.Component.TrivialInstance, e: any) {
      const { value } = e.detail;
      const reportOptions = this.data.reportOptions.map((item: any) => ({
        ...item,
        checked: value.includes(item.id.toString()),
      }));

      const showOtherInput =
        reportOptions.find((item: any) => item.id === 8)?.checked || false;

      this.setData({
        reportOptions,
        showOtherInput,
      }, () => {
        this.updateSubmitEnabled();
      });
    },

    onOtherInput(this: WechatMiniprogram.Component.TrivialInstance, e: any) {
      this.setData({
        otherReason: e.detail.value,
      }, () => {
        this.updateSubmitEnabled();
      });
    },
    deleteImage(
      this: WechatMiniprogram.Component.TrivialInstance,
      e: WechatMiniprogram.TouchEvent
    ) {
      const { index } = e.currentTarget.dataset;
      wx.showModal({
        title: "提示",
        content: "确定要删除这张图片吗？",
        success: (res) => {
          if (res.confirm) {
            const uploadedImages = [...this.data.uploadedImages];
            uploadedImages.splice(index, 1);
            this.setData({ uploadedImages });
          }
        },
      });
    },
    chooseImage(this: WechatMiniprogram.Component.TrivialInstance) {
      wx.chooseImage({
        count: 3 - this.data.uploadedImages.length,
        success: (res) => {
          this.setData({
            uploadedImages: [...this.data.uploadedImages, ...res.tempFilePaths],
          });
        },
      });
    },

    previewImage(this: WechatMiniprogram.Component.TrivialInstance, e: any) {
      const { src } = e.currentTarget.dataset;
      wx.previewImage({
        current: src,
        urls: this.data.uploadedImages,
      });
    },

    onDescriptionInput(
      this: WechatMiniprogram.Component.TrivialInstance,
      e: any
    ) {
      this.setData({
        description: e.detail.value,
      }, () => {
        this.updateSubmitEnabled();
      });
    },

    updateSubmitEnabled(this: BannerComponent) {
      const selectedOptions = this.data.reportOptions.filter(
        (item: any) => item.checked
      );
      const hasSelectedOptions = selectedOptions.length > 0;

      const isOtherSelected = selectedOptions.some((item: any) => item.id === 8);
      const otherReasonValid = !isOtherSelected || (this.data.otherReason && this.data.otherReason.trim().length > 0);

      const hasDescription = this.data.description && this.data.description.trim().length > 0;

      this.setData({
        isSubmitEnabled: hasSelectedOptions && otherReasonValid && hasDescription,
      });
    },

    async submitReport(this: BannerComponent) {
      if (!this.data.isSubmitEnabled) {
        return;
      }

      const selectedOptions = this.data.reportOptions.filter(
        (item: any) => item.checked
      );
      if (selectedOptions.length === 0) {
        wx.showToast({
          title: "请选择举报原因",
          icon: "none",
        });
        return;
      }

      if (
        selectedOptions.some((item: any) => item.id === 8) &&
        !this.data.otherReason
      ) {
        wx.showToast({
          title: "请填写其他举报原因",
          icon: "none",
        });
        return;
      }

      // 提交举报信息
      const reportData = {
        reasons: selectedOptions,
        otherReason: this.data.otherReason,
        images: this.data.uploadedImages,
        description: this.data.description,
        userId: this.data.userId,
        roomId: wx.getStorageSync("joinedGroupId"),
      };
      console.log("举报信息：", reportData);

      try {
        await request({
          options: {
            url: `/app/video-live/feedback`,
            data: reportData,
          },
        });

        wx.showToast({
          title: "举报成功",
          icon: "success",
        });

        // 提交成功后关闭弹窗
        this.setData({
          showPopup: false,
          reportOptions: this.data.reportOptions.map((item: any) => ({
            ...item,
            checked: false,
          })),
          showOtherInput: false,
          otherReason: "",
          uploadedImages: [],
          description: "",
          isSubmitEnabled: false,
        });
      } catch (error) {
        this.handleError(error);
      }
    },
  },
});