import MHeader from '@/components/col-header'
import MSticky from '@/components/col-sticky'
import { defineComponent, onMounted, reactive, onBeforeUnmount } from 'vue'
import styles from './index.module.less'
import { Button, Field } from 'vant'
import MUploader from '@/components/col-upload'
import { api_userMusicDetail, api_userMusicSave } from '../api'
import { useRoute, useRouter } from 'vue-router'
import videoBg from '../images/videoBg.png'
import { postMessage } from '@/helpers/native-message'
import { browser } from '@/helpers/utils'

export default defineComponent({
  name: 'creation-edit',
  setup() {
    const { isTablet, ios, iPhone } = browser()
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      id: route.query.id,
      musicDetail: {} as any,
      playType: '',
      desc: '',
      videoImg: '', // 视频封面
      img: '',
      needCheckDevice: (ios || iPhone) ? true : false,
      hasDeviceAuth: false, // 有设备相机权限
    })

    const onSubmit = async () => {
      console.log({
        id: state.id,
        img: state.img,
        videoImg: state.videoImg,
        desc: state.desc || '我发布了一首演奏作品，快来听听吧～',
        musicPracticeRecordId: state.musicDetail.musicPracticeRecordId,
        type: 'FORMAL'
      })
      try {
        await api_userMusicSave({
          id: state.id,
          img: state.img,
          videoImg: state.videoImg,
          desc: state.desc || '我发布了一首演奏作品，快来听听吧～',
          musicPracticeRecordId: state.musicDetail.musicPracticeRecordId,
          type: 'FORMAL'
        })

        router.back()
      } catch {
        //
      }
    }
    // 初始化获取是否已经授权
    const initDeviceAuth = () => {
      postMessage(
        {
          api: 'checkDeviceCamera',
          content: {
            hideAlert: true
          }
        },
        res => {
          if (res?.content.status) {
            state.hasDeviceAuth = true
          }
        }
      )
    }
    // 校验是否已经授权
    const checkDeviceAuth = () => {
      console.log('校验app',state.needCheckDevice)
      if (state.needCheckDevice) {
        postMessage({ api: 'checkDeviceCamera' }, res => {
          const { content } = res as any
          if (content?.status) {
            state.hasDeviceAuth = true
          } else {
            // 没有权限不能获取图片
            state.hasDeviceAuth = false
          }
        })
      } else {
        state.hasDeviceAuth = true
      }
    }
    // 截图
    const onCropper = () => {
      postMessage(
        {
          api: 'videoCrop',
          content: {
            url: state.musicDetail.videoUrl
          }
        },
        res => {
          if (res?.content.videoCover) {
            state.videoImg = res.content.videoCover
          }
        }
      )
    }
    // 设置导航栏颜色
    function setStatusBarTextColor(isWhite: boolean) {
      postMessage({
        api: 'setStatusBarTextColor',
        content: { statusBarTextColor: isWhite }
      });
    }
    onMounted(async () => {
      initDeviceAuth();
      setStatusBarTextColor(false);
      try {
        const { data } = await api_userMusicDetail(state.id)
        state.musicDetail = data
        state.desc = data.desc
        state.videoImg = data.videoImg
        state.img = data.img

        if (data?.videoUrl.lastIndexOf('mp4') !== -1) {
          state.playType = 'Video'
        } else {
          state.playType = 'Audio'
        }
      } catch {
        //
      }
    })
    onBeforeUnmount(() => {
      setStatusBarTextColor(true);
    });
    return () => (
      <div class={isTablet ? styles.creationTablet : ''}>
        <MSticky position="top">
          <MHeader background={'#F1F1F1'} border={false} />
        </MSticky>
        <div class={[styles.section, styles.sectionFile]}>
          <div class={styles.uploadImg} onClick={checkDeviceAuth}>
            <MUploader
              class={styles.muploader}
              // native
              cropper
              tips={''}
              deletable={false}
              hasDeviceAuth={state.hasDeviceAuth}
              v-model:modelValue={state.img}
            />
            {/* <div class={styles.tip}>选封面</div> */}
          </div>
          <div class={styles.musicDetail}>
            <p class={styles.musicName}>{state.musicDetail.musicSheetName}</p>
            <p class={styles.username}>{state.musicDetail.username}</p>
          </div>
        </div>        
        {state.playType === 'Video' && (
          <div class={[styles.section, styles.sectionVideo]}>
            <img src={state.videoImg || videoBg} class={styles.videoBg} />
            <div class={styles.btnGroup}>
              <div onClick={checkDeviceAuth}>
                <MUploader
                  class={styles.btnImg}
                  cropper
                  tips=""
                  deletable={false}
                  hasDeviceAuth={state.hasDeviceAuth}
                  onUploadChange={img => {
                    console.log(img, 'img')
                    state.videoImg = img
                  }}
                  options={{
                    fixedNumber: [16, 9]
                  }}
                />
              </div>
              <div class={styles.btnCropper} onClick={onCropper}>
                视频截取封面
              </div>
            </div>
          </div>
        )}

        <div class={styles.section}>
          <Field
            rows={4}
            autosize
            type="textarea"
            maxlength={150}
            placeholder="我发布了一首演奏作品，快来听听吧～"
            showWordLimit
            v-model={state.desc}
          />
        </div>

        <div class={styles.btnGroup}>
          <Button type="primary" round block color="#2DC7AA" onClick={onSubmit}>
            {state.musicDetail.type === 'FORMAL' ? '保存' : '发布'}
          </Button>
        </div>
      </div>
    )
  }
})
