import { View, Camera, Icon, Text, Image,Button } from "@tarojs/components";
import _ from "lodash"; 
import { useEffect, useMemo, useRef, useState } from "react";
import Taro, { useDidShow } from "@tarojs/taro";
import api from "@/services/core/api";
import { getAuth } from "@/utils/comm";
import photoBtn from "@/assets/images/event/photoBtn.png";
import region from "@/assets/images/event/region.png";
import "./index.less";
import useReportStore from "@/store/report";

interface ImgPathDto {
  type: 1 | 2 | 3;
  path: string;
}
//举手之劳
const liftFingerImgConfig = [
  {
    text: "处置前",
    type: 1.1,
  },
  {
    text: "处置后",
    type: 1.2,
  },
];

//拍照图片集
const commImgConfig = [
  {
    text: "近景",
    type: 2,
  },
  {
    text: "远景",
    type: 0.5,
  },
  {
    text: "其他",
    type: 1,
  },
];
function CameraComp() {
  const { discoverEntry } = useReportStore(); //事件上报入口
  const pathDefault: ImgPathDto[] = [
    {
      type: 1,
      path: "",
    },
    {
      type: 2,
      path: "",
    },
    {
      type: 3,
      path: "",
    },
  ];
  const ctx = Taro.createCameraContext();
  //设置选中图片的标识
  const [zoom, setZoom] = useState(() => {
    return discoverEntry === "liftFinger" ? 1.1 : 2;
  });
  const [imgPath, setImgPath] = useState<ImgPathDto[]>(pathDefault);

  //附件图片
  const attmentPreUrlList = useRef<ImgPathDto[]>(pathDefault);
  useDidShow(() => {
    getAuth("scope.camera", "请打开相机权限", () => {
      Taro.navigateBack();
    });
  });
  useEffect(() => {
    ctx.setZoom({
      zoom,
    });
  }, [zoom]);
  //拍照
  const takePhoto = () => {
    //焦距缩放配置
    const zoomConfig =
      discoverEntry === "liftFinger" ? [1.1, 1.2] : [2, 0.5, 1];
    ctx.takePhoto({
      quality: "high",
      success: (res) => {
        let pathList = _.cloneDeep(imgPath);
        const attmentImg = res.tempImagePath;
        let zoomIndex = zoomConfig.findIndex((it) => it === zoom); //当前zoom的索引
        pathList[zoomIndex].path = attmentImg;
        let nextZoom = zoomConfig[zoomIndex > 1 ? 2 : zoomIndex + 1]; //下个zoom
        setZoom(nextZoom);
        setImgPath(pathList);
        //上传图片
        Taro.uploadFile({
          url: api.uploadUrl,
          filePath: res.tempImagePath,
          header: {
            authorization: "Bearer " + Taro.getStorageSync("token"),
          },
          name: "file",
          success(imgRes) {
            let imgResultReq = JSON.parse(imgRes.data);
            const attmentImg = api.assetsUrl + imgResultReq.data;
            let zoomIndex = zoomConfig.findIndex((it) => it === zoom); //当前zoom的索引
            attmentPreUrlList.current[zoomIndex].path = attmentImg;
          },
        });
      },
    });
  };
  //设置缩放级别
  const setScaleZoom = (zoom: number) => {
    setZoom(zoom);
  };
  //删除图片
  const handleClearImg = (index: number) => {
    let pathList = _.cloneDeep(imgPath);
    pathList[index].path = "";
    setImgPath(pathList);
  };
  const showNextBtn = imgPath.filter((it) => it.path.length > 1);

  //下一步，拿第一张照片去获取类别
  const handleNextPage = () => {
    let fileimgList = attmentPreUrlList.current?.map((it) => it.path);
    // 存储照片信息
    if (discoverEntry === "liftFinger") {
      //举手之劳
      Taro.setStorageSync("beforeFilePath", fileimgList.slice(0, 1)); //处置前的照片
      Taro.setStorageSync("afterFilePath", fileimgList.slice(1, 2)); //处置后
    } else {
      let filehasimgList = fileimgList.filter((it) => it);
      Taro.setStorageSync("beforeFilePath", filehasimgList); //照片
    }

    Taro.redirectTo({ url: "/pages/Event/view/miniAiIdentify/index" });
  };

  //上传图片配置
  const cameraImgConfig = useMemo(() => {
    return discoverEntry === "liftFinger" ? liftFingerImgConfig : commImgConfig;
  }, []);
  return (
    <View className="camera-wrap">
      <Camera
        outputDimension="1080P"
        device-position="back"
        flash="off"
        style="width: 100%; height: 100%"
      ></Camera>
      <Image className="region-icon" src={region} />
      <View className="footer">
        <View className="img-wrap">
          {/* 举手之劳显示处置前和处置后的图片，其他拍照显示近/远/其他，逻辑不变 */}
          {cameraImgConfig?.map((it, index) => (
            <View
              key={it.type}
              className={
                zoom === it.type ? "img-box active" : "img-box imgpre-box"
              }
              onClick={() => setScaleZoom(it.type)}
            >
              <Text className="text"> {it.text}</Text>
              {imgPath[index]?.path && (
                <>
                  <Icon
                    type="clear"
                    className="clear-icon"
                    color="red"
                    onClick={() => handleClearImg(index)}
                  />
                  <View className="thumb-wrap">
                    <Image src={imgPath[index].path} className="img-thumb" />
                  </View>
                </>
              )}
            </View>
          ))}
        </View>

        <Image onClick={takePhoto} className="photo-icon" src={photoBtn} /> 
        <Button 
          className="next-btn"
          type="primary"
          size="mini"
          onClick={handleNextPage}
          style={{
            opacity: showNextBtn.length > 1 ? 1 : 0,
          }}
        >
          下一步
        </Button>
      </View>
    </View>
  );
}

export default CameraComp;
