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

Page({
  data: {
    pageStep: 1 as number,
    targetAvatar: '',
    targetName: '',
    targetContext: '',
    reasons: [
      { id: 1, label: '欺诈' },
      { id: 2, label: '色情低俗' },
      { id: 3, label: '诱导' },
      { id: 4, label: '传播不实信息' },
      { id: 5, label: '违法犯罪' },
      { id: 6, label: '骚扰' },
      { id: 7, label: '侵权（诽谤、抄袭）' },
      { id: 8, label: '混淆他人投诉' },
      { id: 9, label: '恶意营销' },
      { id: 10, label: '与服务类目不符' },
      { id: 11, label: '隐私信息收集' },
      { id: 12, label: '广告体验' },
      { id: 13, label: '其他' },
    ],
    selectedReason: '',
    description: '',
    descriptionLen: 0 as number,
    imageList: [] as string[],
    isAgreed: true as boolean,
    canSubmit: false as boolean,
  },

  onLoad(options: any) {
    if (options?.targetName) {
      this.setData({
        targetName: decodeURIComponent(options.targetName),
        targetContext: options.targetContext || '',
        targetAvatar: options.targetAvatar || '',
      });
    }
  },

  onReasonTap(e: any) {
    const { id } = e.currentTarget.dataset;
    const reason = this.data.reasons.find((r: any) => r.id === Number(id));
    if (reason) {
      this.setData({
        selectedReason: reason.label,
        pageStep: 2,
        isAgreed: true,
      });
      this.updateCanSubmit();
    }
  },

  updateCanSubmit() {
    const d = this.data;
    this.setData({ canSubmit: !!d.selectedReason && !!d.description && d.isAgreed && d.imageList.length > 0 });
  },

  onDescriptionInput(e: any) {
    this.setData({
      description: e.detail.value,
      descriptionLen: e.detail.value.length,
    });
    this.updateCanSubmit();
  },

  onChooseImage() {
    wx.chooseMedia({
      count: 9 - this.data.imageList.length,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res: any) => {
        const tempFiles = res.tempFiles || [];
        const newImages = tempFiles.map((f: any) => f.tempFilePath || f.path);
        this.setData({
          imageList: [...this.data.imageList, ...newImages],
        }, () => {
          this.updateCanSubmit();
        });
      },
    });
  },

  onRemoveImage(e: any) {
    const { index } = e.currentTarget.dataset;
    const list = [...this.data.imageList];
    list.splice(index, 1);
    this.setData({ imageList: list }, () => {
      this.updateCanSubmit();
    });
  },

  toggleAgree() {
    this.setData({ isAgreed: !this.data.isAgreed });
    this.updateCanSubmit();
  },

  async handleSubmit() {
    if (!this.data.canSubmit) {
      return;
    }

    if (!this.data.selectedReason) {
      wx.showToast({ title: '请选择投诉原因', icon: 'none' });
      return;
    }

    wx.showLoading({ title: '提交中...' });

    try {
      await request({
        options: {
          url: '/app/video-watch/feedback',
          method: 'POST',
          data: {
            seeId: wx.getStorageSync("seeId") || '',
            code: wx.getStorageSync("code") || '',
            openId: wx.getStorageSync("openId") || '',
            appId,
            type: this.data.selectedReason,
            description: this.data.description,
          },
        },
      });

      wx.hideLoading();
      this.setData({ pageStep: 3 });
    } catch (err) {
      wx.hideLoading();
      wx.showToast({ title: '提交失败，请重试', icon: 'none' });
    }
  },

  handleClose() {
    wx.navigateBack();
  },
});