import { uploadFile } from "@/utils/http";
import { Image, View } from "@tarojs/components";
import Taro, { useReady } from "@tarojs/taro";
import { useEffect, useState } from "react";
import popupStyle from "./index.module.less";
import {
  cloneVoice
  
} from "@/service/voice";
import { EUploadFileScene } from "@/consts/enum";
import { useVoiceStore } from "@/store/voiceStore";
import { isSuccess } from "@/utils";

export enum ECloneStatus {
  STOP = 0,
  RECORDING = 1,
  RECORDED = 2,
}

interface Props {
  voiceName?: string;
  setCloneStatus: (status: ECloneStatus) => void;
  setShow: (show: boolean) => void;
  show: boolean;
  entId: number | string; // 企业ID
  onRecordEnd: (r: string, voiceName?: string) => void;
}

const texts = [
  '新的一天又开始了。昨晚休息的怎么样？今天的天气看起来不错，适合外出走走，可以带上相机，捕捉一些美好的瞬间。工作之余，别忘了给自己一点放松的时间。',

  '今天别忘了我们的约会哦。晚上7点，老地方见。我已经迫不及待想见到你了。需要的话，我可以提前去接你，吃完饭去湖边散散步。',

  '探索这座充满活力的城市，从现代摩天大楼到古老的街巷，每个角落都有惊喜。我们的城市以其美食、艺术和文化活动而闻名。',

  '健康是最重要的财富。记得每天至少喝八杯水，保持身体的水分。多吃蔬菜水果，保持均衡的饮食。适量的运动也很重要，找到你喜欢的运动方式，让健康成为你生活的一部分。',

  '不要错过我们一年一度的文化节庆，这是一个展示我们传统艺术和手工艺的盛会。您可以观看精彩的舞蹈表演，也是一个了解我们文化的绝佳机会。',
]

// 随机一段文本给用户阅读
const text = texts[Math.round(Math.random() * (texts.length - 1))]

export default ({
  voiceName,
  onRecordEnd,
  setCloneStatus,
  setShow,
  show,
  entId
}: Props) => {
  const [recording, setRecording] = useState(false);
  
  const recorderManager = Taro.getRecorderManager();
  const readText = text;
  
  recorderManager.onStart(() => {
    console.log("recorder start");
  });
  recorderManager.onPause(() => {
    console.log("recorder pause");
  });
  recorderManager.onStop(async (res: any) => {
    console.log("recorder stop", res);
    setCloneStatus(ECloneStatus.STOP);
    setRecording(false);

    // 如果录制取消则不上传
    if (pressEvent.canceled) {
      setPressEvent({
        ...pressEvent,
        isLongPress: false,
        moveY: 0,
        canceled: false,
      });

      return;
    }

    // const acb = await cloneVoice({sourceUrl:"https://51saas.oss-cn-hangzhou.aliyuncs.com/u260727532/20250701/tmp_6479f0_5615350594ec420a8f1cd8c8102980ad.mp3",
    //   voiceText:"健康是最重要的财富。记得每天至少喝八杯水，保持身体的水分。多吃蔬菜水果，保持均衡的饮食。适量的运动也很重要，找到你喜欢的运动方式，让健康成为你生活的一部分。"});
    // // const res = await cloneVoice({sourceUrl: response.publicUrl, voiceText: readText});
    // console.log(acb);

    
    const { tempFilePath, duration } = res;
    if (duration.length < 10000) {
      Taro.showToast({
        title: "录音不能小于10秒",
        icon: "none",
      });
      return;
    }

    // 此处需要判断文件大小
    const response = await uploadFile(
      tempFilePath,
      EUploadFileScene.VOICE_CLONE,
    );
    // 发送录音
    // Taro.showToast({
    //   title: '发送成功',
    //   icon: 'success'
    // })
    console.log(response?.publicUrl, 'publicUrl');
    if (response && response.publicUrl) {
      Taro.showLoading();
      console.log({sourceUrl: response.publicUrl, entId}, 'clone started');
      const res = await cloneVoice({sourceUrl: response.publicUrl, voiceText: readText, entId});
      Taro.hideLoading();
      if(isSuccess(res.status)){
        onRecordEnd(res.data.taskId, voiceName);
      }else{
        onRecordEnd('', voiceName);
      }
    }
  });

  recorderManager.onError(() => {
    setCloneStatus(ECloneStatus.STOP);
    setRecording(false);
  });
  const [pressEvent, setPressEvent] = useState({
    isLongPress: false,
    startY: 0,
    moveY: 0,
    canceled: false,
  });
  const exit = () => {
    setShow(false);
    setCloneStatus(ECloneStatus.STOP);
    setRecording(false);
  };
  
  const onLongPress = (event: any) => {
    recorderManager.start({
      duration: 1000 * 60 * 20,
      sampleRate: 16000,
      encodeBitRate: 96000, //编码码率
      numberOfChannels: 1,
      format: "mp3",
      frameSize: 1,
    });
    setCloneStatus(ECloneStatus.RECORDING);
    setRecording(true);
    setPressEvent({
      ...pressEvent,
      isLongPress: true,
      startY: event.touches[0].clientY,
    });
  };
  const onTouchMove = (event: any) => {
    if (pressEvent.isLongPress) {
      const moveY = event.touches[0].clientY - pressEvent.startY;
      let canceled = pressEvent.canceled;
      // 上移大于 50 就说明用户想取消
      if (moveY < -50) {
        canceled = true;
      } else {
        canceled = false;
      }
      setPressEvent({
        ...pressEvent,
        moveY,
        canceled,
      });
    }
  };
  const onTouchEnd = () => {
    if (pressEvent.isLongPress) {
      recorderManager.stop();
      if (!pressEvent.canceled) {
        exit();
        setPressEvent({
          ...pressEvent,
          isLongPress: false,
          moveY: 0,
          canceled: false,
        });
      }
    }
    setRecording(false);
  };

  
  useEffect(() => {
    if (!show) {
      return recorderManager.stop();
    }
  }, [show]);

  useReady(() => {});

  return (
    <View className={popupStyle.container}>
      <View className={popupStyle.content}>
        <View className={popupStyle.title}>
          <View>请朗读</View>
        </View>
        <View className="flex-1 flex items-center">
          <View className={popupStyle.demoText}>
            {readText}
          </View>
        </View>

        <View className={popupStyle.actionButtonContainer}>
          <View
            className={recording ? popupStyle.tipsActived : popupStyle.tips}
          >
            松手发送，上移取消
          </View>
          <View
            className={recording ? popupStyle.actionButtonActived : popupStyle.actionButton}
            onLongPress={onLongPress}
            onTouchEnd={onTouchEnd}
            onTouchMove={onTouchMove}
          >
            <View className={`${recording ? 'hidden':''}`}>按住录制</View>
          </View>
        </View>
      </View>
    </View>
  );
};
