//极简巡查
import { View, Text, Image, Canvas } from "@tarojs/components";
import "./index.less";
import { useRef, useState } from "react";
import Taro, { NodesRef, requirePlugin, useDidShow } from "@tarojs/taro";
import services from "@/services";
import useReportStore from "@/store/report";
import ai from "@/assets/images/event/ai.png";
import edit from "@/assets/images/event/edit.png";
import audio from "@/assets/images/event/audio.png";
import { Button, Dialog, Flex, Textarea } from "@taroify/core";
function MiniAiIdentify() {
  const { updateReportEvent, updateContent } = useReportStore(); //上报事件
  const [visible, setVisible] = useState<boolean>(false);
  const [aiData, setAiData] = useState<API.DetectedInfoItem>(); //AI识别数据,只取第一个
  const [content, setContent] = useState<string>(""); //事件内容
  const fileEventImg = Taro.getStorageSync("beforeFilePath")[0]; //事件照片信息
  let plugin = requirePlugin("QCloudAIVoice");
  const speechRecognizerManager = useRef<any>(plugin.speechRecognizerManager());
  const params = {
    // 用户参数
    secretkey: "jBMGtGMBizziAMHuGL9fvuc3D6i49xUk",
    secretid: "AKIDAIAm7ByVkiPqzrSnreAQP7YhaCXaNt85",
    appid: 1308579967,
    // 实时识别接口参数
    engine_model_type: "16k_zh",
    filter_punc: 1,
    filter_modal: 2,
    word_info: 2,
  };

  // 开始识别
  speechRecognizerManager.current.OnRecognitionStart = (res) => {
    console.log("开始识别", res);
  };
  // 一句话开始
  speechRecognizerManager.current.OnSentenceBegin = (res) => {
    console.log("一句话开始", res);
  };
  // 识别变化时
  speechRecognizerManager.current.OnRecognitionResultChange = (res) => {
    console.log("识别变化", res);
    if (res.code === 0) {
      let text = res.result.voice_text_str;
      setContent(text.slice(0, 30));
    }
  };
  // 一句话结束
  speechRecognizerManager.current.OnSentenceEnd = (res) => {
    console.log("一句话结束", res.result.voice_text_str);
  };
  // 识别结束
  speechRecognizerManager.current.OnRecognitionComplete = (res) => {
    console.log("识别结束", res);
  };
  // 识别错误
  speechRecognizerManager.current.OnError = (res) => {
    // code为6001时，国内站用户请检查是否使用境外代理，如果使用请关闭。境外调用需开通国际站服务
    console.log("识别失败", res);
  };
  // 录音结束（最长10分钟）时回调
  speechRecognizerManager.current.OnRecorderStop = (res) => {
    console.log("录音结束", res);
  };
  useDidShow(() => {
    init();
  });
  const init = async () => {
    let imgBase64: string = (await imageToBase64(fileEventImg)) as string;
    services.event
      .postPhotoAcquisitionCategory({ img: imgBase64 })
      .then((res) => {
        if (res.code === 200) {
          //接口成功
          let aidataRes = res.data; //AI数据
          if (aidataRes.code === 200) {
            //识别成功
            setAiData(aidataRes.data[0]?.detectedInfo[0]);
            drawCanvas(aidataRes.data[0]?.detectedInfo[0]);
          } else {
            //未识别
            setVisible(true);
          }
        }
      });
  };
  const drawCanvas = (aiData) => {
    Taro.nextTick(() => {
      const query = Taro.createSelectorQuery();
      query
        .select("#canvas")
        .fields({ node: true, size: true })
        // 执行所有的请求。请求结果按请求次序构成数组，在callback的第一个参数中返回
        .exec((res: NodesRef) => {
          // Canvas 实例
          const canvas = res[0].node;
          const ctx = canvas.getContext("2d");
          Taro.getImageInfo({
            src: fileEventImg,
            success: (resImg1) => {
              canvas.width = resImg1.width;
              canvas.height = resImg1.height;
              // 创建一个图片对象
              const img1 = canvas.createImage();
              img1.src = resImg1.path;
              img1.onload = () => {
                ctx.clearRect(0, 0, canvas.width, canvas.height); // 可选：清除画布
                ctx.drawImage(img1, 0, 0, resImg1.width, resImg1.height);
                ctx.strokeStyle = "#ff0000";
                ctx.lineWidth = 2;
                ctx.strokeRect(
                  aiData?.x_left,
                  aiData?.y_left,
                  Number(aiData?.x_right) - Number(aiData?.x_left),
                  Number(aiData?.y_right) - Number(aiData?.y_left)
                ); // 在图片上添加红色框
              };
            },
          });
        });
    });
  };
  //调用微信自带的base64转化
  const imageToBase64 = (img) => {
    if (!img) {
      return;
    }
    return new Promise((resolve, reject) => {
      Taro.downloadFile({
        url: img,
        success(res) {
          Taro.getFileSystemManager().readFile({
            filePath: res.tempFilePath, //选择图片返回的相对路径
            encoding: "base64", //编码格式
            success: (res) => {
              //成功的回调
              resolve(res.data);
            },
          });
        },
      });
    });
  };
  //录入事件内容
  const handleContentDone = () => {
    if (!aiData) {
      //未识别，去确认位置
      handleConfirm();
      return;
    }
    setVisible(false);
  };
  //确认位置
  const handleConfirm = () => {
    //事件信息，上报提交
    let eventCategory = aiData?.eventCategoryInfo;
    //AI识别
    if (eventCategory?.classifyRegisterConds) {
      updateReportEvent({
        newInstCondCode:
          eventCategory?.classifyRegisterConds[0]?.registeredCondCode, //立案条件code
        newInstCondName:
          eventCategory?.classifyRegisterConds[0]?.registeredCondName, //立案条件name
      });
    }
    //描述
    updateContent(content);
    Taro.navigateTo({
      url: "/pages/Event/view/confirmLocation/index",
    });
  };
  const handleAudioToText = () => {
    speechRecognizerManager.current.start(params);
  };
  const handleCloseAudio = () => {
    console.log("停止");
    speechRecognizerManager.current.stop();
  };
  //立案条件
  let classifyRegisterConds = aiData?.eventCategoryInfo?.classifyRegisterConds;
  return (
    <>
      {aiData && (
        <View className="ai-wrap">
          <View className="header">
            <img className="ai-icon" src={ai} />
            <Text className="title">AI智能识别</Text>
          </View>
          <View className="picture-wrap">
            <Canvas
              id="canvas"
              canvasId="canvas"
              type="2d"
              className="canvas-wrap"
            ></Canvas>
          </View>
          <View className="footer-btn">
            <View className="tag textellipsis">
              {aiData?.eventCategoryInfo?.thirdTypeName}-
              {(classifyRegisterConds &&
                classifyRegisterConds[0]?.registeredCondName) ||
                "无"}
            </View>
            <View className="tip" onClick={() => setVisible(true)}>
              <img className="edit-icon" src={edit} />
              识别错误了，点这里重新描述
            </View>
            <Button
              shape="round"
              color="primary"
              className="btn"
              onClick={handleConfirm}
            >
              去确认位置
            </Button>
          </View>
        </View>
      )}
      {!aiData && (
        <View className="full-wrap">
          <Image
            src={fileEventImg}
            mode="aspectFill"
            className="full-picture"
          />
        </View>
      )}
      <Dialog open={visible} onClose={() => setVisible(false)}>
        <Dialog.Header>
          <Text className="title">简要说明问题</Text>
        </Dialog.Header>
        <Dialog.Content>
          <Textarea
            autoHeight
            style={{ width: "100%" }}
            limit={30}
            className="text-area"
            value={content}
            onInput={(e) => setContent(e.detail.value)}
            placeholder="请按照一事一报原则上报问题，将问题情况描述准确，更有利于解决"
          />
        </Dialog.Content>
        <Dialog.Actions>
          <Flex className="footer">
            <Flex.Item span={12}>
              <Button
                shape="round"
                block
                color="primary"
                className="audio"
                onTouchStart={handleAudioToText}
                onTouchEnd={handleCloseAudio}
                icon={<Image className="audio-icon" src={audio} />}
              >
                按住说话
              </Button>
            </Flex.Item>
            <Flex.Item span={12}>
              <Button
                shape="round"
                block
                color="primary"
                className="btn"
                onClick={handleContentDone}
              >
                完成
              </Button>
            </Flex.Item>
          </Flex>
        </Dialog.Actions>
      </Dialog>
    </>
  );
}

export default MiniAiIdentify;
