<template>
  <section
    :class="`lj-infor-item ${keyattr && current == data[keyattr] ? 'is-current' : ''}`"
    style="cursor: pointer"
    @click="clickItem"
  >
    <RenderHeader v-bind="props" />
  </section>
</template>

<script setup lang="tsx" name="SalePriceItem">
import { ref, watch, onBeforeMount, nextTick, VNode, Component, useSlots } from "vue";
import { useI18n } from "vue-i18n";
import { isArray, isFunction, isObject } from "@/utils/is";
import { Close } from "@element-plus/icons-vue";

// <!-- <RenderWidget v-bind="props" :data="data" /> -->
interface ItemProps {
  /**
   * @description 标题
   */
  label?: string;
  /**
   * @description 属性值名称
   */
  value?: string;
  /**
   * @description 图标，支持iconfont |el-icon | render
   */
  icon?: string | Component | ((params?: any) => VNode);
  /**
   * @description 图标尺寸
   */
  iconsize?: string | number;
  // type?: string; // 'primary' | 'success' | 'info' | 'warning' | 'danger'
  /**
   * @description 标签
   */
  tag?: ItemProps[];
  /**
   * @description tag属性：标签位置
   */
  position?: "left" | "right" | any;
  /**
   * @description tag属性：属性对象
   */
  prop?: any;
  /**
   * @description tag属性：枚举类型
   */
  enum?: any;
  // /**
  //  * @description 标签属性整体
  //  */
  // className?: string;
  /**
   * @description 标签属性名
   */
  textClassName?: string;
}

// 接收父组件参数并设置默认值
interface SalePriceItemProps {
  /**
   * @argument 图标，支持iconfont |el-icon | render
   */
  icon?: string | Component | ((params?: any) => VNode);
  /**
   * @description 头部布局，左右布局，最多两层
   */
  header?: ItemProps | ItemProps[];
  /**
   * @description 头部右侧布局，最多两层
   */
  aside?: ItemProps | ItemProps[];
  /**
   * @desciption 数据
   */
  data: any;
  /**
   * @description 当前选中项
   */
  current?: any;
  /**
   * @description 关键id
   */
  keyattr?: any;
  /**
   * @description 是否可编辑
   */
  editable?: boolean;
}

const { t } = useI18n();
const slots = useSlots();
const props = withDefaults(defineProps<SalePriceItemProps>(), {
  data: () => {},
  editable: false
});

const emit = defineEmits(["clickItem", "delItem"]);
const clickItem = () => {
  emit("clickItem", props.data);
};

const delItem = () => {
  emit("delItem", props.data);
};

const getNumber = (value: number | string) => {
  let matches = value.toString().match(/\d+/);
  return matches ? Number(matches[0]) : 0;
};

const getEnumValue = (value: any, enumArr?: any, attr = "label") => {
  if (!enumArr) return value;
  let _value = enumArr.find((item: any) => item.value == value);
  return _value ? _value[attr] : "";
};

/**
 * @description 渲染主图标
 */
const RenderIcon = (rProp: any, className?: string) => {
  let iconRender: any = [];
  let _size = rProp.iconsize ? getNumber(rProp.iconsize) : "";
  if (rProp.icon) {
    let _render: any[] = [];
    switch (typeof rProp?.icon) {
      case "object":
        _render.push(
          <el-icon size={_size} class={className}>
            {rProp.icon.render()}
          </el-icon>
        );
        break;
      case "function":
        _render.push(rProp.icon(props.data));
        break;
      case "string":
        let styleSize = _size ? { fontSize: `${_size}px` } : {};
        _render.push(<i class={["iconfont", rProp.icon, className]} style={styleSize} />);
        break;
    }
    iconRender.push(_render);
  }
  return iconRender;
};

const RenderTag = (rProp: any) => {
  let _renderLeft: any[] = [];
  let _renderRight: any[] = [];
  if (rProp.tag) {
    if (isArray(rProp.tag)) {
      rProp.tag.forEach((item: any, index: number) => {
        let _type =
          item?.prop?.type && isFunction(item.prop.type)
            ? item.prop.type(props.data)
            : getEnumValue(props.data[item.value], item?.enum, "type");
        let _label = getEnumValue(props.data[item.value], item?.enum);
        let _icon = [];
        if (item.icon) {
          _icon = RenderIcon(item);
        }
        if (_label || !item?.enum) {
          if (item.position == "right") {
            _renderRight.push(
              <>
                <el-tag {...item.prop} type={_type} disable-transitions={true}>
                  {_icon}
                  {item?.enum && _label}
                </el-tag>
              </>
            );
          } else {
            _renderLeft.push(
              <>
                <el-tag {...item.prop} type={_type} disable-transitions={true}>
                  {_icon}
                  {item?.enum && _label}
                </el-tag>
              </>
            );
          }
        }
      });
    } else if (isObject(rProp.tag)) {
      let item = rProp.tag;
      let _type =
        item?.prop?.type && isFunction(item.prop.type)
          ? item.prop.type(props.data)
          : getEnumValue(props.data[item.value], item?.enum, "type");
      let _label = getEnumValue(props.data[item.value], item?.enum);
      let _icon = [];
      if (item.icon) {
        _icon = RenderIcon(item);
      }
      if (_label) {
        _renderLeft.push(
          <>
            <el-tag {...item.prop} type={_type} disable-transitions={true}>
              {_icon}
              {item?.enum && _label}
            </el-tag>
          </>
        );
      }
    }
  }
  return { left: _renderLeft, right: _renderRight };
};

/**
 * @description 渲染header-右侧模块aside
 * @todo 需要根据业务需求，调整右侧模块的布局
 */
const RenderAside = (rProp: any) => {
  let _render: any[] = [];
  if (rProp.aside) {
    if (isArray(rProp.aside)) {
      rProp.aside.forEach((item: any, index: number) => {
        // 其余显示在第二行
        let _label = item.label ? <span class="text-f-c text-secondary-text">{item.label}</span> : "";
        _render.push(
          <>
            <aside class="flx-col flx-shrink" style="text-align: right" title={item.label}>
              <div>{props.data[item.value]}</div>
              {_label}
            </aside>
          </>
        );
      });
    } else if (isObject(rProp.aside)) {
      let item = rProp.aside;
      // 第一行，作为主标题
      let _label = item.label ? <span class="text-f-c text-secondary-text">{item.label}</span> : "";
      _render.push(
        <>
          <aside class="flx-col flx-shrink" style="text-align: right" title={item.label}>
            <div>{props.data[item.value]}</div>
            {_label}
          </aside>
        </>
      );
    }
  }
  return _render;
};

/**
 * @description 渲染删除按钮
 * @param rProp
 */
const RenderDelBtn = (rProp: any) => {
  return (
    <>
      <div class="flx-shrink flx-center pl-4">
        <el-button class="del-btn" type="danger" plain size="small" circle icon={Close} onClick={delItem}></el-button>
      </div>
    </>
  );
};

/**
 * @description 渲染主图标
 */
const RenderHeader = (rProp: any) => {
  let _render: any[] = [];
  if (rProp.header) {
    if (isArray(rProp.header)) {
      if (rProp.header.length) {
        let item = rProp.header[0];
        // 第一行，作为主标题
        let _icon = [];
        if (item.icon) {
          _icon = RenderIcon(item, "mr-4");
        }
        // 标签
        let _tagLeft: any = [],
          _tagRight: any = [];
        if (item.tag && item.tag.length) {
          let _tag = RenderTag(item);
          _tagLeft = _tag.left;
          _tagRight = _tag.right;
        }
        let _textClassName = item?.textClassName ?? "";
        let _label = item.label ? <span class="text-body-m text-secondary-text pr-2">{item.label}</span> : "";
        _render.push(
          <>
            <div class="code flx-start text-body-b" title={item.label}>
              {_tagLeft}
              {_icon}
              {_label}
              <span class={_textClassName}>{props.data[item.value]}</span>
              {_tagRight}
            </div>
          </>
        );
      }
      let _tagRender: any[] = [];

      rProp.header.forEach((item: any, index: number) => {
        if (index > 0) {
          // 其余显示在第二行
          let _icon = [];
          if (item.icon) {
            _icon = RenderIcon(item);
          }
          // 标签
          let _tagLeft: any = [],
            _tagRight: any = [];
          if (item.tag && item.tag.length) {
            let _tag = RenderTag(item);
            _tagLeft = _tag.left;
            _tagRight = _tag.right;
          }
          let _textClassName = item?.textClassName ?? "";
          let _label = props.data[item.value] !== "" && item.label ? <span class="text-disable pr-2">{item.label}</span> : "";
          if (_label || _icon.length) {
            _tagRender.push(
              <>
                <span class="text-f-c text-primary-text flx" title={item.label}>
                  {_tagLeft}
                  {_icon}
                  {_label}
                  <span class={_textClassName}>{props.data[item.value]}</span>
                  {_tagRight}
                </span>
              </>
            );
          }
        }
      });
      _tagRender.length &&
        _render.push(
          <>
            <div class="tag-list mt-2">{_tagRender}</div>
          </>
        );
    } else if (isObject(rProp.header)) {
      let item = rProp.header;
      // 第一行，作为主标题
      let _icon = {};
      if (item.icon) {
        _icon = RenderIcon(item);
      }
      // 标签
      let _tagLeft: any = [],
        _tagRight: any = [];
      if (item.tag && item.tag.length) {
        let _tag = RenderTag(item);
        _tagLeft = _tag.left;
        _tagRight = _tag.right;
      }
      let _label = item.label ? <span class="text-body-m text-secondary-text pr-2">{item.label}</span> : "";
      _render.push(
        <>
          <div class="code flx-start" title={item.label}>
            {_tagLeft}
            {_icon}
            {_label}
            <span>{props.data[item.value]}</span>
            {_tagRight}
          </div>
        </>
      );
    }
  }
  return (
    <>
      <header class="flx-justify-between">
        <div class="title flx-1 flx-start overflow-hidden">
          {rProp.icon && <div class="lj-infor-item__avatars flx-center flx-shrink">{RenderIcon(rProp)}</div>}
          <div class="name flx-col flx-1">{_render}</div>
        </div>
        {RenderAside(rProp)}
        {rProp.editable && RenderDelBtn(rProp)}
      </header>
    </>
  );
};

// const RenderWidget = (rProp: any) => {
//   return (
//     <>
//       <section
//         class={`lj-infor-item ${
//           props.keyattr && props.current && props.current == props.data[props.keyattr] ? "is-current" : ""
//         }`}
//         style="cursor: pointer"
//         onClick={clickItem}
//       >
//         {RenderHeader(rProp)}
//       </section>
//     </>
//   );
// };
</script>

<style lang="scss" scope>
/* 通用信息模块布局 */
.lj-infor-item {
  position: relative;
  border-radius: $br-md;
  overflow: hidden;
  border: 1px solid $color-gray-4;
  // transition: all 0.2s ease-in-out;
  padding: $space-a1 $space-b1;
  user-select: none;

  box-sizing: border-box;

  & + & {
    margin-top: $space-a1;
  }

  &:hover {
    border-color: $color-primary-300;
  }

  & > header {
    position: relative;
    align-items: stretch;

    .title {
      .name {
        height: 100%;
      }
      .code {
        span + span {
          margin-left: 2px;
        }
      }
      .el-icon {
        margin-right: $space-a1;
      }
    }
    > aside + aside {
      margin-left: $space-a2;
    }
  }

  // & > main {
  //   position: relative;
  //   padding: $space-b1 $space-b2;
  // }

  &__avatars {
    width: $space-b4;
    height: $space-b4;
    .iconfont {
      font-size: $space-b3;
      color: $color-gray-7;
    }
  }

  .tag-list {
    display: flex;
    span {
      position: relative;
    }
    span + span {
      margin-left: $space-a1;
      padding-left: $space-a1;
    }
    span:not(.el-tag) + span:not(.el-tag) {
      &:before {
        position: absolute;
        content: "";
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 1px;
        height: 12px;
        background-color: $color-gray-5;
      }
    }
    .iconfont {
      // margin-right: 2px;
      font-size: 13px;
    }
  }
  &.is-current {
    background-color: $color-primary-100;

    .name {
      .code {
        color: $color-primary-600;
      }
    }
  }
}
</style>
