import { Button, Dialog, Grid, GridItem, Popup, Toast } from 'vant'
import { defineComponent, ref, toRefs } from 'vue'
import styles from './index.module.less'
import iconTitle from './icons/title.svg'
import iconCancel from './icons/cancel.png'
import iconConfirm from './icons/confirm.png'
import Content from './content'
import SettingState from '/src/pages/detail/setting-state'
import { IPostMessage, postMessage } from '/src/helpers/native-message'
import detailState from '/src/pages/detail/state'
import { browser } from '/src/helpers/utils'
export const evaluatingShow = ref<boolean>(false)
const open = ref(false)

export type ResultContent = {
  /* 节奏 */
  cadence: number
  /* 完整性 */
  integrity: number
  /* 音调 */
  intonation: number
  playTime: number
  recordId: number
  /** 评测记录ID */
  recordIdStr: string
  /* 分数 */
  score: number
}

/** 合成音频传伴奏弹窗 */
const api_openAdjustRecording = (content: any) => {
	postMessage({
		api: "openAdjustRecording",
		content,
	});
};

//效音组件
export default defineComponent({
  name: 'ColexiuEvaluating',
  props: {
    data: {
      type: Object as () => ResultContent | null,
      default: () => null,
    },
  },
  emits: ['restart'],
  setup(props) {
    const confirmShow = ref<boolean>(false)

    const sendUploadMessage = (res?: IPostMessage) => {
      postMessage({
        api: 'proxyServiceMessage',
        content: {
          header: {
            commond: 'videoUpload',
            status: 200,
            type: 'SOUND_COMPARE',
          },
          body: {
            filePath: res?.content?.filePath,
            recordId: props.data?.recordIdStr,
          },
        },
      })
    }
    const videoUpdate = () => {
      if (SettingState.sett.camera && SettingState.eva.save) {
        postMessage(
          {
            api: 'videoUpdate',
          },
          (res) => {
            console.log('保存视频', res)
            confirmShow.value = false
            if (res?.content) {
              if (res.content.type === 'error') {
                Toast(res.content.message)
                return
              }
              sendUploadMessage(res)
            }
          }
        )
      } else {
        confirmShow.value = false
        sendUploadMessage()
        Toast.success('上传成功')
      }
    }

    /** 评测结果按钮处理 */
    const handleEvaluatResult = () => {
      const browserInfo = browser()
      // 如果音频是midi格式，或者非学生端，走之前的逻辑
      if (detailState.isAppPlay || !browserInfo.isStudent) {
        confirmShow.value = true
      } else {
        if (props.data?.recordIdStr) {
          // 上传云端
          api_openAdjustRecording({
            recordId: String(props.data?.recordIdStr),
            title: detailState.activeDetail?.musicSheetName || "曲谱演奏",
            coverImg: detailState.activeDetail?.titleImg || '',
          });
        }
      }
    }

    return () => {
      return (
        <div>
          <Popup
            position="bottom"
            v-model:show={evaluatingShow.value}
            onOpen={() => (open.value = true)}
            onClosed={() => (open.value = false)}
            teleport="body"
            style={{ backgroundColor: 'transparent' }}
          >
            {open && (
              <Content
                data={props.data}
                onUpload={handleEvaluatResult}
                onRestart={() => (evaluatingShow.value = false)}
              />
            )}
          </Popup>
          <Dialog.Component
            teleport="body"
            class={styles.confirm}
            style={{
              overflow: 'initial',
            }}
            vSlots={{
              title: () => <img class={styles.iconTitle} src={iconTitle} />,
              footer: () => (
                <div class={styles.footer}>
                  <img src={iconCancel} onClick={() => (confirmShow.value = false)} />
                  <img src={iconConfirm} onClick={videoUpdate} />
                </div>
              ),
            }}
            v-model:show={confirmShow.value}
            message={`评测${SettingState.sett.camera && SettingState.eva.save ? '音视频' : '音频'}是否保存演奏？`}
          />
        </div>
      )
    }
  },
})
