<template>
  <div class="main">
    <div class="line">
      <div class="title">
        <label>Audio Record</label>
        <van-button type="primary" size="small" v-if="state.audio.media_id" @click="upload_audio">Upload</van-button>
      </div>
      <div class="task-id" v-if="tasks.audio.task_id">
        <span>TaskID: {{tasks.audio.task_id}}, media_id: {{tasks.audio.media_id}}</span>
        <van-button type="primary" size="mini" @click="copy_text(tasks.audio.task_id + ', ' + tasks.audio.media_id)">Copy</van-button>
      </div>
      <audio-record v-model="state.audio"></audio-record>
    </div>
    <div class="line">
      <div class="title">
        <label>Image directly upload to combine</label>
        <van-button type="primary" size="small" v-if="images.multi_form[0]" @click="upload_multi_images_by_form">Upload</van-button>
      </div>
      <div class="task-id"  v-if="tasks.form_photo.task_id">
        <span>Task ID: {{tasks.form_photo.task_id}}</span>
        <van-button type="primary" size="mini" @click="copy_text(tasks.form_photo.task_id)">Copy</van-button>
      </div>
      <div class="uploader">
        <photo-uploader native v-model="images.multi_form" multiple :max-count="5" :do-upload="false" />
      </div>
    </div>
    <div class="line">
      <div class="title">
        <label>Image directly upload</label>
      </div>
      <div class="task-id"  v-if="tasks.form_photo.task_id">
        <span>url: {{images.single_form[0]?.url}}</span>
        <van-button type="primary" size="mini" @click="copy_text(images.single_form[0]?.url)">Copy</van-button>
      </div>
      <div class="uploader">
        <photo-uploader native v-model="images.single_form" multiple :max-count="5" />
      </div>
    </div>
    <div class="line" v-if="isWx">
      <div class="title">
        <label>Image upload by wx</label>
      </div>
      <div class="task-id">
        <span>url: {{images.single_wx[0]?.url}}</span>
        <van-button type="primary" size="mini" @click="copy_text(images.single_wx[0]?.url)">Copy</van-button>
      </div>
      <div class="uploader">
        <photo-uploader v-model="images.single_wx" :show-button="true"/>
      </div>
    </div>
    <div class="line" v-if="isWx">
      <div class="title">
        <label>Image upload by wx to combine</label>
        <van-button type="primary" size="small" v-if="images.multi_wx[0]" @click="upload_multi_images_by_wx">Upload</van-button>
      </div>
      <div class="task-id"  v-if="tasks.wx_photo.task_id">
        <span>Task ID: {{tasks.wx_photo.task_id}}</span>
        <van-button type="primary" size="mini" @click="copy_text(tasks.wx_photo.task_id)">Copy</van-button>
      </div>
      <div class="uploader">
        <photo-uploader multiple :max-count="5" v-model="images.multi_wx" :do-upload="false" />
      </div>
    </div>
    <div class="line">
      <div class="title">
        <label>Upyun resource remove</label>
      </div>
      <div>
        <van-field type="textarea" autosize rows="3" required v-model="resource_url" colon label="URL" />
      </div>
      <div>
        <van-button type="primary" size="mini" @click="remove_resource()" :disabled="!resource_url">Remove</van-button>
      </div>
    </div>
    <div class="line">
      <div class="title">
        <label>Video Upload</label>
      </div>
      <div class="task-id"  v-if="state.videos[0]?.url">
        <span>Video URL: {{state.videos[0]?.url}}</span>
        <van-button type="primary" size="mini" @click="copy_text(state.videos[0].url)">Copy</van-button>
      </div>
      <div class="uploader">
        <upload-progress>
          <video-uploader v-model="state.videos" />
        </upload-progress>
      </div>
    </div>
    <div class="line">
      <div class="title">
        <label>Remote cache</label>
      </div>
      <div>
        <van-button type="primary" size="mini" @click="setCache()">Set remote cache</van-button>
        <van-button type="primary" size="mini" @click="getCache()">Get remote cache</van-button>
      </div>
    </div>
    <div class="line">
      <div class="title">
        <label>Play media_id</label>
      </div>
      <div>
        <van-field required v-model="playing.media_id" colon label="Media ID" />
        <van-field required v-model="playing.local_id" colon label="Local ID" />
      </div>
      <div>
        <van-button type="primary" size="mini" @click="playMediaID()">Play Media ID</van-button>
        <van-button type="primary" size="mini" @click="playLocalID()">Play Local ID</van-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from "vue";
import copy from 'copy-text-to-clipboard';
import {Cell, Uploader, Button, Field, showFailToast, showSuccessToast} from 'vant'
import AudioRecord from '~/components/audio-record.vue';
import UploadProgress from "~/components/upload-progress.vue";
import VideoUploader from "~/components/video-uploader.vue";
import PhotoUploader from '~/components/photo-uploader.vue';
import { ImageHelper, isWxEnv } from "~/utils";
import { AudioConvertTask, TaskTypes, UploadPictureTask, UploadedFile, WxUploadingPhoto, UploadPhoto } from "~/types";
import useTask from "~/store/task";
import usePool from "~/store/pool";
import {wxUtil} from "~/utils/wx";
import {wx} from "~/utils/wx";
import request from "~/utils/request";

export default defineComponent({
  name: "tester-function",
  components: {
    [AudioRecord.name]: AudioRecord,
    [Cell.name]: Cell,
    [Uploader.name]: Uploader,
    [UploadProgress.name]: UploadProgress,
    [VideoUploader.name]: VideoUploader,
    [Button.name]: Button,
    [PhotoUploader.name]: PhotoUploader,
    [Field.name]: Field
  },
  computed: {
    isWx() {
      return isWxEnv();
    }
  },
  setup() {
    wxUtil.init(['playVoice', 'downloadVoice']);
    const {createTask} = useTask()
    const {setRemoteCache, getRemoteCache} = usePool()
    const state = reactive({
      audio: {media_id: '', audio_url: ''},
      videos: [] as UploadedFile[],
    })
    const playing = reactive({
      media_id: "", local_id: ""
    })

    const resource_url = ref("")

    const images = reactive({
        single_form: [] as Partial<UploadPhoto>[],
        multi_form: [] as Partial<UploadPhoto>[],
        multi_wx: [] as Partial<UploadPhoto>[],
        single_wx: [] as Partial<UploadPhoto>[]
    })

    const tasks = reactive({
      audio: {} as AudioConvertTask,
      form_photo: {} as UploadPictureTask,
      wx_photo: {} as UploadPictureTask,
    })

    const show_video_url = ref(false)

    const upload_audio = async () => {
      let task = {media_id: state.audio.media_id, task_type: TaskTypes.CONVERT_AUDIO_FILE} as AudioConvertTask;
      let task_id = await createTask({task_type: TaskTypes.CONVERT_AUDIO_FILE, payload: {media_id: state.audio.media_id}});
      if (task_id) {
        tasks.audio = {...task, task_id};
      } else {
        showFailToast("create task failed...")
      }

    }

    const upload_multi_images_by_form = async () => {
      let task_id = await ImageHelper.combine_by_form(images.multi_form);
      if (!task_id) return Promise.reject();
      tasks.form_photo = { task_id, task_type: TaskTypes.UPLOAD_PICTURE } as UploadPictureTask;
    }
    const upload_multi_images_by_wx = async () => {
      console.log(images.multi_wx.values)
      let photo =  await ImageHelper.combine_by_wx(images.multi_wx.map(x => (x as WxUploadingPhoto).serverId))
    }

    const copy_text = (text?: string) => {
      if (!text) {
        showFailToast("text is empty!")
        return;
      }
      try {
        if (copy(text)) {
          showSuccessToast('text copied!')
        } else {
          showFailToast('text copy failed!')
        }
      } catch (err) {
        console.log('copy err,...', err);
        showFailToast('text copy error!')
      }

    }

    const setCache = async () => {
      await setRemoteCache("abc", {def: 1, hij: "2"})
    }

    const getCache = async () => {
      let data = await getRemoteCache("abc")
      console.log(data)
    }

    const playMediaID = () => {
      wx.downloadVoice({
        serverId: playing.media_id, isShowProgressTips: 0,
        success: ({localId}: any) => {
          wx.playVoice({localId})
          wx.onVoicePlayEnd({
            complete: () => {
              console.log("play done")
            }, fail: () => {
              showFailToast('音频播放失败！')
            }
          })
        },
        fail: (err: any) => {
          console.error('wx download voice failed...', err)
        }
      });
    }

    const playLocalID = () => {
      console.log(playing.local_id)
      wx.playVoice({localId: playing.local_id})
      wx.onVoicePlayEnd({
        complete: () => {
          console.log("play done")
        }, fail: () => {
          showFailToast('音频播放失败！')
        }
      })
    }

    const remove_resource = async () => {
      const {r, d, e} = await request({
        url: "/api/ngx/image/upyun_remove",
        method: "POST",
        data: {request_url: resource_url.value}
      });
      if (r) {
        showSuccessToast("删除成功！")
      } else {
        showFailToast("删除失败！")
      }
    }

   return {
      state, images, copy_text, upload_audio, resource_url, remove_resource,
      upload_multi_images_by_form, upload_multi_images_by_wx, 
      show_video_url, tasks, setCache, getCache, playing, playMediaID, playLocalID
   }
  }
});
</script>

<style scoped lang="less">

.main {
  padding: 0.24rem 0;
  overflow: auto;

  .line {
    background: #FFFFFF;
    margin-bottom: 0.2rem;
    padding: 0.32rem;

    .title {
      padding: 0 0.16rem;
      display: flex;
      align-items: center;
      justify-content: space-between;

      label {
        font-size: 0.28rem;
      }
    }

    .task-id {
      font-size: 0.24rem;
      padding: 0.1rem 0.16rem;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .uploader {
      padding: 0.16rem;
    }
  }
}

</style>
