import MHeader from '@/components/m-header';
import MSticky from '@/components/m-sticky';
import { defineComponent, onMounted, reactive, onBeforeUnmount } from 'vue';
import styles from './index.module.less';
import { Button, Field, showToast } from 'vant';
import MUploader from '@/components/m-uploader';
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} = browser()
    const route = useRoute();
    const router = useRouter();
    const state = reactive({
      id: route.query.id,
      playType: '',
      musicDetail: {} as any,
      desc: '',
      videoImg: '', // 视频封面
      img: [] as any
    });

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

        router.back();
      } catch {
        //
      }
    };

    // 截图
    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 () => {
      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 ? [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}>
            <MUploader
              class={styles.muploader}
              // native
              cropper
              deletable={false}
              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}>
              <MUploader
                class={styles.btnImg}
                cropper
                deletable={false}
                onUploadChange={img => {
                  if (img.length > 0) {
                    state.videoImg = img[0];
                  }
                }}
                options={{
                  fixedNumber: [16, 9]
                }}
              />
              <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="linear-gradient(90deg, #44C9FF 0%, #259CFE 100%)"
            onClick={onSubmit}>
            {state.musicDetail.type === 'FORMAL' ? '保存' : '发布'}
          </Button>
        </div>
      </div>
    );
  }
});
