import { reactive, computed, toRefs } from "vue";
import { isArray, isObject } from "@/utils/is";
import { cloneDeep, pick, get, omit, defaultsDeep } from "lodash-es";
import { More, ArrowDown, ArrowRight } from "@element-plus/icons-vue";
import {
  ElIcon,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElButton,
  ElButtonGroup,
  ElBadge,
  ElTooltip,
  ElText
} from "element-plus";

/**
 * @description base 动态按钮hooks
 * @param {Function} api 获取表格数据 api 方法 (必传)
 * @param {Object} initParam 获取数据初始化参数 (非必传，默认为{})
 * @param {Function} dataCallBack 对后台返回的数据进行处理的方法 (非必传)
 * @param {Function} requestError 错误处理
 * */
export const useButtonGroup = (mainData: any, assemblySize: string) => {
  //   const state = reactive<Detail.DetailStateProps>({
  //     baseData: {},
  //     // 查询参数(只包括查询)
  //     searchParam: {},
  //     // 初始化默认的查询参数
  //     searchInitParam: {},
  //     // 总参数(包含分页和查询参数)
  //     totalParam: {}
  //   });

  /**
   * 排除多余属性，仅展示需要的属性继承
   * @param data Object
   */
  const omitAttr = (data: any) => {
    return omit(data, ["label", "power", "clickFunc", "slotName", "render", "disabledTextCallBack"]);
  };

  /**
   * @description 获取按钮icon
   * @param item data
   * @returns icon render
   */
  const getIconSlot = (item: any) => {
    console.log("item , item.icon, typeof item.icon :>> ", JSON.stringify(item), item.icon, typeof item.icon);
    let iconRender: any = {};
    switch (typeof item.icon) {
      case "function":
        iconRender = { icon: () => item.icon() };
        break;
      case "string":
        iconRender = {
          icon: () => {
            return <i class={["iconfont", item.icon]} />;
          }
        };
        // delete item.icon;
        break;
      case "object":
        iconRender = {
          icon: () => {
            return <ElIcon>{item.icon.render()}</ElIcon>;
          }
        };
        break;
      default:
        break;
    }
    return iconRender;
  };

  /**
   * @description 折叠后，按钮组渲染
   */
  const buttonsMenuRender = (item: any) => {
    let iconRender = getIconSlot(item);
    let _item = cloneDeep(item);
    typeof _item.icon == "string" && delete _item.icon;

    let btnDisabledTxt = mainData && item.disabledTextCallBack ? item.disabledTextCallBack(mainData) : "";
    // console.log("btnDisabledTxt :>> ", btnDisabledTxt.value);

    // 排除多余属性，仅展示需要的属性继承
    let btnAttr = omitAttr(_item);

    if (item.render) {
      // return item.render(item);
      return <ElDropdownItem>{item.render(item)}</ElDropdownItem>;
    } else if (item.hasOwnProperty("disabledTextCallBack")) {
      let disabled = Boolean(btnDisabledTxt);
      return (
        <ElDropdownItem {...btnAttr}>
          <ElTooltip
            class="box-item"
            disabled={!disabled}
            effect="dark"
            content={btnDisabledTxt}
            placement="right"
            enterable={false}
            hide-after={0}
          >
            <ElText
              text
              {...btnAttr}
              class={{ "is-disabled": disabled, "flx-1": true }}
              disabled={disabled}
              onClick={item.clickFunc}
              v-slots={iconRender}
            >
              {item.label}
            </ElText>
          </ElTooltip>
        </ElDropdownItem>
      );
    } else {
      return (
        <ElDropdownItem {...btnAttr} onClick={item.clickFunc} class="flx-1">
          {item.label}
        </ElDropdownItem>
      );
    }
  };

  const buttonGroupInnderRender = (item: any, ifMenu: boolean, placement: string) => {
    return (
      <div class="flx-center">
        <span class="flx-1">{item.label}</span>
        {!ifMenu && <ElIcon>{placement == "bottom" ? <ArrowDown /> : <ArrowRight />}</ElIcon>}
      </div>
    );
  };

  /**
   * @description 按钮组，下拉菜单渲染器
   * @param item
   * @param placement el-dropdown 菜单弹出位置
   */
  const bottonDropdownRender = (item: any, placement?: string) => {
    let _item = cloneDeep(item[0]);
    let iconRender = getIconSlot(item[0]);
    let _placement: any = placement ?? "bottom";
    /**
     * @description 判断是否为菜单按钮
     */
    let ifMenu = !_item.hasOwnProperty("clickFunc") ?? false;
    let idx = ifMenu ? 1 : 0; // 若是菜单按钮，下拉菜单跳过第一个
    let ifShowDot = false;
    let _buttonsRd = item.map((itm: any, index: number) => {
      if (!ifShowDot && index > 0) {
        let btnDisabledTxt = mainData && itm.hasOwnProperty("disabledTextCallBack") && itm.disabledTextCallBack(mainData);
        if (!btnDisabledTxt) {
          ifShowDot = true;
        }
      }
      return index >= idx && buttonsMenuRender(itm);
    });
    _buttonsRd = _buttonsRd.filter((itm: any) => itm);

    console.log("_buttonsRd menu :>> ", _buttonsRd);
    let _dropdown = {
      dropdown: () => {
        return (
          <>
            <ElDropdownMenu>{_buttonsRd}</ElDropdownMenu>
          </>
        );
      }
    };

    typeof _item.icon == "string" && delete _item.icon;
    let _btnAttr = omitAttr(_item);
    let btnDisabledTxt = mainData && _item.disabledTextCallBack ? _item.disabledTextCallBack(mainData) : "";
    let disabled = Boolean(btnDisabledTxt);
    return (
      <ElDropdown v-slots={_dropdown} placement={_placement} popper-class="button-group__menu">
        {_placement == "bottom" ? (
          <span>
            <ElTooltip
              class="box-item"
              disabled={!disabled}
              effect="dark"
              content={btnDisabledTxt}
              placement="top"
              enterable={false}
              hide-after={0}
            >
              <ElButton
                {..._btnAttr}
                class={{ "is-disabled": disabled }}
                disabled={disabled}
                size={assemblySize}
                onClick={_item.clickFunc}
                v-slots={iconRender}
                style={{ cursor: ifMenu ? "default" : "pointer" }}
              >
                <ElBadge is-dot={!ifMenu && ifShowDot}>{buttonGroupInnderRender(_item, ifMenu, _placement)}</ElBadge>
              </ElButton>
            </ElTooltip>
          </span>
        ) : (
          <span>
            <ElTooltip
              class="box-item"
              disabled={!disabled}
              effect="dark"
              content={btnDisabledTxt}
              placement="top"
              enterable={false}
              hide-after={0}
            >
              <ElText
                {..._btnAttr}
                class={{ "is-disabled": disabled, "menu-more__text": true }}
                disabled={disabled}
                onClick={_item.clickFunc}
                v-slots={iconRender}
              >
                {buttonGroupInnderRender(_item, ifMenu, _placement)}
              </ElText>
            </ElTooltip>
          </span>
        )}
      </ElDropdown>
    );
  };

  return {
    // ...toRefs(state),
    omitAttr,
    getIconSlot,
    buttonsMenuRender,
    bottonDropdownRender
  };
};
