import PageContainerBehavior from "../../../../core/behavior/page-container.behavior";
import { upload } from "../../../../lib/request/upload";

// module/chats/pages/analysis/analysis.ts

Component({
  behaviors: [PageContainerBehavior],
  options: {},
  properties: {},
  data: {
    uploadList: [
      { target: 'tongueImgUrl', required: true, label: '舌面图', src: '../../assets/tongue-1.png' },
      { target: 'tongueBackImgUrl', required: true, label: '舌下图', src: '../../assets/tongue-2.png' },
      { target: 'faceImgUrl', required: false, label: '面部图', src: '../../assets/face-1.png' },
    ],
    thumbnail: [] as string[],
    original: [] as string[],
    status: [false, false, false],
    _queue: {} as AnyObject,
  },
  methods: {
    handle(event: WechatMiniprogram.TouchEvent) {
      const { handle, index } = event.mark as AnyObject;
      console.log(handle, index, handle === 'upload:delete', event.mark);
      switch (handle) {
        case 'preview':
          break;
        case 'upload':
          this._chooseMedia(index).then(src => src && this._uploadMedia(index, src))
          break;
        case 'upload:delete':
          this._deleteMedia(index);
          break;
      }
    },
    _chooseMedia(index: number) {
      return wx.chooseMedia({ count: 1, mediaType: ['image'], sourceType: ['album', 'camera'], camera: 'front' })
        .then(res => {
          const src = res.tempFiles[0].tempFilePath;
          this.setData({ [`thumbnail.${index}`]: src });
          return src;
        })
        .catch(() => null);
    },
    _deleteMedia(index: number) {
      this.setData({
        [`thumbnail.${index}`]: '',
        [`original.${index}`]: '',
      })
    },
    _uploadMedia(index: number, src?: string) {
      this.setData({ [`_queue.${index}`]: true });
      src ??= this.data.thumbnail[index];
      upload({
        params: { name: 'file', file: src! },
        transform({ data }) { return (<any>data).url; }
      }).then(src => {
        this.setData({ [`original.${index}`]: src })
      }, (error) => {
        wx.showToast({ title: error?.errMsg ?? '上传失败', icon: 'error' })
        this.setData({
          [`thumbnail.${index}`]: '',
          [`original.${index}`]: '',
        })
      }).then(() => {
        this.setData({ [`_queue.${index}`]: false });
      })
    },
    onSubmit() {
      const data = [];
      for (let index = 0; index < this.data.uploadList.length; index++) {
        const item = this.data.uploadList[index];
        if (this.data._queue[index]) {
          wx.showToast({ title: `请等待图片上传完毕`, icon: 'none' });
          return;
        } else if (item.required && !this.data.original[index]) {
          wx.showToast({ title: `请上传${item.label}`, icon: 'none' });
          return;
        }
        if (this.data.original[index]) data.push({ target: item.target, src: this.data.thumbnail[index], })
      }
      this.getOpenerEventChannel().emit('update', data)
      wx.navigateBack()
    }
  }
})