import { composeImgUrl } from "@/utils";
import { Uploader } from "@taroify/core";
import { View, Image } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { useState } from "react";
import icon15 from "@/assets/icon/icon15.png";
import api from "@/services/core/api";

interface FormImgUploadProps {
  value?: string;
  onChange?: (value: string) => void;
  templateUrl?: string;
}

const FormImgUpload = (props: FormImgUploadProps) => {
  const [file, setFile] = useState<any>();
  const { value, onChange, templateUrl } = props;
  function onUpload() {
    Taro.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
    }).then(({ tempFiles }) => {
      setFile({
        url: tempFiles[0].path,
        type: tempFiles[0].type,
        name: tempFiles[0].originalFileObj?.name,
      });
      Taro.uploadFile({
        url: api.uploadUrl,

        name: "file",
        filePath: tempFiles[0].path,
        success: (res) => {
          const resData = JSON.parse(res.data);
          if (resData.code === 200) {
            onChange && onChange(resData.data);
          }
        },
      });
    });
  }
  /** 下载模版并查看 */
  const previewFile = (url) => {
    Taro.downloadFile({
      url: composeImgUrl(url),
      success: function (res) {
        var filePath = res.tempFilePath;
        Taro.openDocument({
          filePath: filePath,
          success: function (res) {
            console.log("打开文档成功");
          },
        });
      },
    });
  };

  return (
    <View className="fileUploadWrap">
      <Uploader
        value={file}
        onUpload={onUpload}
        onChange={(file) => setFile(file)}
      />

      {templateUrl && (
        <View
          className="downloadIconWrap"
          onClick={previewFile.bind(this, templateUrl)}
        >
          <Image src={icon15} className="downloadIcon"></Image>
          <View>下载模版文件</View>
        </View>
      )}
    </View>
  );
};

export default FormImgUpload;
