import {getConfig, queryResourceList} from "../../../src/services/file-setter";
import {
  Button,
  Dialog,
  Icon,
  Input,
  Pagination,
  Search,
  Upload,
} from "@alifd/next";
import * as React from "react";
import "./index.less";

interface FileSetterProps {
  value: string;
  defaultValue: string;
  placeholder: string;
  onChange: (val: string) => void;
}

interface ResourceProps {
  createTime: string;
  fileId: string;
  resourceFileName: string;
  resourceId: string;
  resourceName: string;
  updateTime: string;
}

const fileType = ["image/jpeg", "image/png", "image/webp", "image/svg+xml"];

export default class FileSetter extends React.PureComponent<
  FileSetterProps,
  any
> {
  static displayName = "FileSetter";
  state = {
    visible: false,
    resourceList: [],
    totalPageNum: 0,
  };

  async componentDidMount() {
    const res = await queryResourceList({});

    this.setState({
      resourceList: res.data?.list ?? [],
      totalPageNum: res.data?.totalPageNum ?? 0,
    });
  }

  onOpen = () => {
    this.setState({
      visible: true,
    });
  };

  onClose = () => {
    this.setState({
      visible: false,
    });
  };

  onSearch = async (value: string) => {
    const res = await queryResourceList({
      keyword: value,
    });

    this.setState({
      resourceList: res.data?.list,
      totalPageNum: res.data?.totalPageNum,
    });
  };

  onCutWords = (w: string) => {
    let w_n = w;
    if (w.length > 14) {
      w_n = w.slice(0, 7) + "..." + w.slice(w.length - 7, w.length);
    }
    return w_n;
  };

  pageChange = async (current: number) => {
    const res = await queryResourceList({
      pageNum: current,
    });

    this.setState({
      resourceList: res.data?.list ?? [],
      totalPageNum: res.data?.totalPageNum ?? 0,
    });
  };

  // 上传前置判断
  onBeforeUpload = (file: any) => {
    return new Promise<void>((resolve, reject) => {
      if (!fileType.includes(file.type)) {
        reject();
        return;
      }
      const reader = new FileReader();
      reader.onload = (e) => {
        if (e.total > 2 * 1024 * 1024) {
          Dialog.alert({
            content: `File size must be < 2M`,
            title: "Warning",
          });
          reject();
          return;
        }

        const img = new Image();
        img.onload = () => {
          resolve();
        };
        img.src = String(reader.result);
      };
      reader.readAsDataURL(file);
    });
  };

  onSelectResource = (value: string) => {
    const config = getConfig();
    const fullDownloadUrl = config.downloadUrl + value;
    this.props.onChange(fullDownloadUrl);
    this.setState({
      visible: false,
    });
  };

  onSuccessUpload = async () => {
    // SuccessUpload
    const res = await queryResourceList({});

    this.setState({
      resourceList: res.data?.list ?? [],
      totalPageNum: res.data?.totalPageNum ?? 0,
    });
  };

  render() {
    const {onChange, placeholder, value} = this.props;
    // @ts-ignore
    const requestHeaders = window.parent.zwlce?.utils.getRequestHeaders();
    return (
      <>
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
          }}>
          <Input
            size="small"
            value={value}
            placeholder={placeholder || ""}
            onChange={(val: any) => onChange(val)}
          />
          <Button
            type="normal"
            aria-label="upload button"
            onClick={this.onOpen}
            style={{marginLeft: 20}}>
            <Icon type="upload"/>
          </Button>
        </div>
        <Dialog
          v2
          title="资源中心"
          height={650}
          style={{width: "920px"}}
          visible={this.state.visible}
          onOk={this.onClose}
          onClose={this.onClose}
          onCancel={this.onClose}
          footerActions={["cancel"]}>
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              paddingLeft: 13,
              paddingRight: 40,
            }}>
            <Search
              shape="simple"
              onSearch={this.onSearch}
              placeholder="请输入关键字"
              style={{width: "424px", height: "32px"}}
            />
            <Upload
              action={getConfig().uploadUrl}
              // @ts-ignore
              listType={false}
              accept="image/jpeg, image/png, image/webp, image/svg+xml"
              beforeUpload={this.onBeforeUpload}
              onSuccess={this.onSuccessUpload}
              headers={requestHeaders}
            >
              <Button type="primary">
                <Icon type="add"/> 资源上传
              </Button>
            </Upload>
          </div>
          {this.state.resourceList.length === 0 ? (
            <div className="noList">
              <img alt="" src="./images/暂无数据.svg"/>
              <span className="noListTitle">暂无数据</span>
            </div>
          ) : (
            <div className="listWrapper">
              {this.state.resourceList.map((a: ResourceProps, i) => {
                return (
                  <div
                    key={i}
                    className="listMain"
                    onClick={() => this.onSelectResource(a.fileId)}>
                    <img src={getConfig().downloadUrl + a.fileId} alt="img"/>
                    <div className="listContent">
                      <div className="listTitle">
                        {this.onCutWords(a.resourceFileName)}
                      </div>
                      <div className="listInfo">{a.updateTime}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
          <div
            style={{
              display: "flex",
              alignItems: "center",
              flexDirection: "column",
            }}>
            {this.state.resourceList.length !== 0 && (
              <Pagination
                defaultCurrent={1}
                onChange={(current: number) => {
                  this.pageChange(current).catch(e => console.warn(e));
                }}
                total={this.state.totalPageNum * 10}
              />
            )}
          </div>
        </Dialog>
      </>
    );
  }
}
