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

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

const FormFileUpload = (props: FormFileUploadProps) => {
  const [file, setFile] = useState<any>();
  const { onChange, templateUrl } = props;

  function onUpload() {
    Taro.chooseMessageFile({
      count: 1,
      type: "file",
    }).then(({ tempFiles }) => {
      setFile({
        url: tempFiles[0].path,
        type: tempFiles[0].type,
        name: tempFiles[0]?.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>
      <View className="fileUploadWrap">
        <View>
          <View className="fileUpload" onClick={onUpload}>
            <BackTop />
            <View>上传文件</View>
          </View>
        </View>
        {templateUrl && (
          <View
            className="downloadIconWrap"
            onClick={previewFile.bind(this, templateUrl)}
          >
            <Image src={icon15} className="downloadIcon"></Image>
            <View>下载模版文件</View>
          </View>
        )}
      </View>
      <View>{file?.name}</View>
    </View>
  );
};

export default FormFileUpload;
