import "./index.less";
import $ from "jquery";

interface IProps {
  /**
   * jquery selector
   */
  selector: string;
  /**
   * select事件
   */
  onChange?: () => void;
}

export default class Dropdown {
  constructor(p: IProps) {
    let select = $(p.selector);
    let options = select.find("option");
    let menu = $("<div />").addClass("bs-dropdown");
    let button = $("<div />").addClass("button");
    let list = $("<ul />");
    $("<em />").prependTo(button);
    options.each(function (i) {
      let option = $(this);
      list.append($("<li />").text(option.text()));
    });

    menu.css("--t", select.find(":selected").index() * -36.5 + "px");

    select.wrap(menu);

    button.append(list).insertAfter(select);

    list.clone().insertAfter(button);

    $(document)
      .on("click", ".bs-dropdown", function (e) {
        let menu = $(this);
        if (!menu.hasClass("open")) menu.addClass("open");
      })
      .on("click", function (e: any) {
        e.stopPropagation();
        if ($(".bs-dropdown").has(e.target).length === 0) {
          $(".bs-dropdown").removeClass("open");
        }
      })
      .on("click", ".bs-dropdown > ul > li", function (e) {
        let li = $(this);
        let menu = li.parent().parent();
        let select = menu.children("select");
        let selected = select.find("option:selected");
        let index = li.index();

        menu.css("--t", index * -36.5 + "px");
        selected.removeAttr("selected");
        select.find("option").eq(index).attr("selected", "selected");
        p.onChange && p.onChange();

        menu.addClass(index > selected.index() ? "tilt-down" : "tilt-up");

        setTimeout(() => {
          menu.removeClass("open tilt-up tilt-down");
        }, 500);
      });
  }
}
