import { Post } from "../../../../lib/request/method";

interface Gallery {
  label?: string;
  src: string;
}

type Result = {
  thumbnail: Gallery[];
  source: (Gallery & { target: string; })[];
}

// module/chats/components/message-analysis/message-analysis.ts

const defaultGallery = {
  'tongueImgUrl': '',
  'tongueBackImgUrl': '',
  'faceImgUrl': '',
}

Component({
  properties: {
    payload: { type: Object, value: { title: '', description: '' } },
    active: { type: Boolean, value: false },
    messageType: { type: Number, value: 0 },
  },
  data: {
    isAnalysis: 0,
    start: false,
    examples: [
      { label: '舌面举例', src: '../../assets/tongue-1.png' },
      { label: '舌下举例', src: '../../assets/tongue-2.png' },
      { label: '面部举例', src: '../../assets/face-1.png' },
    ] as Gallery[],
    source: [] as Gallery[],
  },
  attached() {
    this.setData({
      isAnalysis: wx.getStorageSync("isAnalysis"),
    });
  },
  /**
   * 组件的方法列表
   */
  methods: {
    onConfirm() {
      if (this.data.source.length) return;
      this.setData({ start: true });
      // wx.navigateTo({
      //   url: '/module/chats/pages/analysis/analysis?messageType=' + this.data.messageType,
      //   events: { update: (data: Result) => this._update(data) }
      // });
    },
    onCancel() {
      this.triggerEvent('next', defaultGallery);
    },
    async onUpdate(event) {
      this.setData({ start: false });
      if (event.detail) {
        await this._followUp(event.detail);
        this._update(event.detail);
      }
    },
    // 提交随访提醒
    async _followUp({ source, thumbnail }: Result) {
      const data = {} as AnyObject;
      for (const item of source) { data[item.target] = item.src; }
      if (this.data.messageType === 2 && this.data.isAnalysis === 2) {
        wx.showLoading({ title: '提交中', mask: true });
        try {
          const workId = wx.getStorageSync("workId") || 0;
          const followObj = wx.getStorageSync("followObj");
          const res = await Post(
            `/followupTaskManage/updateFollowupTaskFillin/${workId}`,
            { ...followObj, upImg: data.tongueImgUrl, downImg: data.tongueBackImgUrl, faceImg: data.faceImgUrl },
            { transform({ data }: any) { return data; }, }
          );
          // 存储舌面象分析报告id，用于跳转页面时最后产生结果查看
          wx.setStorageSync("tonguefaceAnalysisReportId", res.tonguefaceAnalysisReportId);
          wx.hideLoading();
        } catch (error) {
          wx.hideLoading();
          wx.showToast({ title: error?.errMsg ?? '提交失败', icon: 'none', duration: 3000 });
          this.setData({ start: true });
          throw error;
        }
      }
    },
    _update({ source, thumbnail }: Result) {
      this.setData({ source: thumbnail });
      const data = {} as AnyObject;
      for (const item of source) { data[item.target] = item.src; }
      this.triggerEvent('next', {
        ...defaultGallery,
        ...data,
      });
    }
  }
})