<template>
  <div class="main">
    <div class="line">
      <div class="title">
        <label>示范视频</label>
        <div>
          <van-radio-group v-model="state.shifan_mode" direction="horizontal">
            <van-radio name="upload">上传文件</van-radio>
            <van-radio name="input">输入URL</van-radio>
          </van-radio-group>
        </div>
      </div>
      <textarea v-if="state.shifan_mode === 'input'" rows="3" v-model="state.shifan_input" placeholder="请输入视频URL地址"></textarea>
      <template v-else>
        <div class="task-id"  v-if="state.shifan_files[0]?.url">
          <span>Video URL: {{state.shifan_files[0]?.url}}</span>
          <van-button type="primary" size="mini" @click="copy_text(state.shifan_files[0].url)">Copy</van-button>
        </div>
        <div class="uploader">
          <upload-progress>
            <video-uploader v-model="state.shifan_files" />
          </upload-progress>
        </div>
      </template>
    </div>
    <div class="line">
      <div class="title">
        <label>练习视频</label>
        <div>
          <van-radio-group v-model="state.lianxi_mode" direction="horizontal">
            <van-radio name="upload">上传文件</van-radio>
            <van-radio name="input">输入URL</van-radio>
          </van-radio-group>
        </div>
      </div>
      <textarea v-if="state.lianxi_mode === 'input'" rows="3" v-model="state.lianxi_input" placeholder="请输入视频URL地址"></textarea>
      <template v-else>
        <div class="task-id"  v-if="state.lianxi_files[0]?.url">
          <span>Video URL: {{state.lianxi_files[0]?.url}}</span>
          <van-button type="primary" size="mini" @click="copy_text(state.lianxi_files[0].url)">Copy</van-button>
        </div>
        <div class="uploader">
          <upload-progress>
            <video-uploader v-model="state.lianxi_files" />
          </upload-progress>
        </div>
      </template>
    </div>
    <div class="line">
      <!-- <div>
        <van-button type="primary" :disabled="!can_score()" @click="score_by_matlab()">Matlab打分</van-button>
        <div>Task: {{scores.matlab_task}}</div>
        <template v-if="scores.matlab_task">
          <div>Status: {{scores.matlab_status}} <van-icon name="replay" @click="check_task(scores.matlab_task, 'matlab')" /></div>
          <template v-if="scores.matlab_status === 'DONE'">
            <div>Accuracy: {{scores.matlab_accuracy}}</div>
            <div>Recall: {{scores.matlab_recall}}</div>
          </template>
          <template v-if="scores.ml_status === 'FAILED'">
            <div>Error: {{scores.ml_error}}</div>
          </template>
        </template>
      </div> -->
      <div class="btns">
        <van-button type="primary" :disabled="!can_score()" @click="score_by_ml()">机器学习打分</van-button>
        <div>Task: {{scores.ml_task}}</div>
        <template v-if="scores.ml_task">
          <div>Status: {{scores.ml_status}} <van-icon name="replay" @click="check_task(scores.ml_task, 'ml')" /></div>
          <template v-if="scores.ml_status === 'DONE'">
            <div>Accuracy: {{scores.ml_accuracy}}</div>
            <div>Recall: {{scores.ml_recall}}</div>
          </template>
          <template v-if="scores.ml_status === 'FAILED'">
            <div>Error: {{scores.ml_error}}</div>
          </template>
        </template>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {defineComponent, reactive} from "vue";
import copy from 'copy-text-to-clipboard';
import {Button, Cell, Field, Icon, Radio, RadioGroup, Toast, Uploader, 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 {AiTaskHelper, isWxEnv} from "~/utils";
import request from "~/utils/request";
import {TaskStatuses, TaskTypes, UploadedFile} from "~/types";


export default defineComponent({
  name: "tester-ai",
  components: {
    [AudioRecord.name]: AudioRecord,
    [Cell.name]: Cell,
    [Uploader.name]: Uploader,
    [UploadProgress.name]: UploadProgress,
    [VideoUploader.name]: VideoUploader,
    [Button.name]: Button,
    [Field.name]: Field,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Icon.name]: Icon
  },
  computed: {
    isWx() {
      return isWxEnv();
    }
  },
  setup() {

    const state = reactive({
      shifan_files: [] as UploadedFile[],
      shifan_mode: 'upload',
      shifan_input: '',
      lianxi_files: [] as UploadedFile[],
      lianxi_mode: 'upload',
      lianxi_input: ''
    });

    const scores = reactive({
      matlab_task: '',
      matlab_status: '',
      matlab_accuracy: '',
      matlab_recall: '',
      matlab_error: '',
      ml_task: '',
      ml_status: '',
      ml_accuracy: '',
      ml_recall: '',
      ml_error: ''
    })


    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 get_shfian_url = () => {
      let { shifan_input, shifan_mode, shifan_files } = state;
      return {
        'upload': shifan_files[0]?.url,
        'input': shifan_input
      }[shifan_mode];
    }

    const get_lianxi_url = () => {
      let { lianxi_input, lianxi_mode, lianxi_files } = state;
      return {
        'upload': lianxi_files[0]?.url,
        'input': lianxi_input
      }[lianxi_mode];
    }

    const score_by_matlab = async () => {
      
      const res = await request({
        url: '/api/v1/ai/compare', 
        method: 'POST',
        headers: {Authorization: 'Basic aHVpd2luZzo5dm9EOVNSMVNMS3h3SnhNeVFNVQ=='},
        data: {
          reference_url: get_shfian_url(),
          compare_url: get_lianxi_url()
        }
      });
      update_result(res, 'matlab', new Date())
    }

    const score_by_ml = async () => {
      const res = await request({
        url: '/api/v1/ai/compare', 
        method: 'POST',
        headers: {Authorization: 'Basic aHVpd2luZzo5dm9EOVNSMVNMS3h3SnhNeVFNVQ=='},
        data: {
          reference_url: get_shfian_url(),
          compare_url: get_lianxi_url(),
          audio_type: "INSTRUMENT"
        }
      });
      update_result(res, 'ml', new Date())
    }

    const update_result = (data: any, key: 'matlab' | 'ml', start_time: Date) => {
      
      let { task_id, task_status, task_result, task_meta } = AiTaskHelper.parseRes(data, start_time, TaskTypes.AI_SCORE);
      scores[`${key}_task`] = task_id;
      scores[`${key}_status`] = task_status;
      if (task_status === TaskStatuses.DONE) {
        scores[`${key}_accuracy`] = task_result?.accuracy;
        scores[`${key}_recall`] = task_result?.recall;
      } else if (task_status === TaskStatuses.FAILED || task_status === TaskStatuses.UNKNOWN)  {
        scores[`${key}_error`] = task_meta?.data.error;
      }
    }

    const check_task = async (task_id: string, key: 'matlab' | 'ml') => {
      const res = await request({
        url: '/api/v1/ai/get_task_result',
        headers: {Authorization: 'Basic aHVpd2luZzo5dm9EOVNSMVNMS3h3SnhNeVFNVQ=='},
        data: { task_id }
      });
      update_result(res, key, new Date());
    }

    const can_score = () => get_lianxi_url() && get_shfian_url();

   return {
      state, copy_text, score_by_matlab, score_by_ml, scores, can_score, check_task
   }
  }
});
</script>

<style scoped lang="less">

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

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

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

    textarea {
      border: 1px solid #e5e5e5;
      width: calc(100% - 00.32rem);
      margin: 0.32rem 0.16rem;
      padding: 0.16rem;
    }

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

    .uploader {
      padding: 0.16rem;
    }

    &.flex {
      display: flex;
      align-items: center;
      justify-content: space-between;

      div {
        padding: 0.12rem 0;
      }
    }
  }
}

</style>
