import { FileOutlined, PlusOutlined } from "@ant-design/icons-vue";
import { css } from "@linaria/core";
import { defineComponent } from "vue";
import { string } from "vue-types";
import { uploader } from "../objects";

import { message } from "ant-design-vue";

export default defineComponent({
  props: {
    text: string(),
    data: string(),
  },
  emits: ["change"],
  setup(props, { emit }) {
    const uploadFile = async () => {
      const [file] = await uploader.selectFile({ accept: "*" });
      if (file.size > 50 * 1024 * 1024) {
        message.warn("文件不能超过50M!");
        return false;
      }
      const fileRes = await uploader.uploadFile(file);
      if (fileRes.error) {
        message.error(fileRes.error);
        return;
      }
      emit("change", fileRes.url);
    };
    const getFileName = (url: string) => {
      const lastIndex = url.lastIndexOf("/");
      if (lastIndex == -1) {
        return "";
      }
      const file = url.substring(lastIndex + 1);
      return file.split(".")[0];
    };

    return () => (
      <div class={ImageStyle} onClick={uploadFile}>
        <div class={"wapper"}>
          {props.data ? (
            <div class={"file"}>
              <FileOutlined />
              <div class={"up_txt"}>{getFileName(props.data)}</div>
            </div>
          ) : (
            <div class={"no_value"}>
              <PlusOutlined />
              <div class={"up_txt"}>{props.text}</div>
            </div>
          )}
        </div>
      </div>
    );
  },
});
const ImageStyle = css`
  width: 100%;
  height: 100%;
  color: #343434;
  background-color: #f2f2f2;
  font-size: 24px;
  border-radius: 2px;
  cursor: pointer;
  .wapper {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .file {
    padding: 24px 0;
    display: inline-flex;
    flex-direction: column;
    align-items: center;
    .up_txt {
      margin-top: 10px;
      font-size: 14px;
      color: #343434;
    }
  }
  .no_value {
    padding: 24px 0;
    display: inline-flex;
    flex-direction: column;
    align-items: center;
    .up_txt {
      margin-top: 10px;
      font-size: 14px;
      color: #343434;
    }
  }
`;
