<!-- jz排序组件 -->
<template>
  <div class="jzSortCom">
    <div class="jsItem" v-for="{ label, key } in sortData" :key="key" @click.stop="handleSortChange(key)">
      <!-- 排序字段名称 -->
      <span>{{ label }}</span>
      <!-- 排序图标 -->
      <div class="isIconList">
        <img :src="getSortIcon(key, 'ascending')" class="up" />
        <img :src="getSortIcon(key, 'descending')" />
      </div>
    </div>
  </div>
</template>

<script setup>
import sortIcon from '@/assets/images/sortIcon.png'; // 排序图标
import sortIconAct from '@/assets/images/sortIconAct.png'; // 排序图标-选中

defineProps({
  // 排序初始化数据 Array<{ label: string; key: string }>
  sortData: {
    type: Array,
    default: () => []
  }
});

const sortRes = defineModel({}); // 组件值 {key: string; order: 'asc' | 'desc' | ''}

// 获取排序图标
const getSortIcon = (key, order) => {
  return sortRes.value.key === key && sortRes.value.order === order ? sortIconAct : sortIcon;
};

// 排序change事件
const handleSortChange = (keyName) => {
  // 排序映射
  const sortMap = new Map([
    [1, 'descending'],
    [2, 'ascending'],
    [3, ''],
    ['descending', 1],
    ['ascending', 2],
    ['', 3],
    [undefined, 3]
  ]);
  const { key, order } = sortRes.value;
  let kn = keyName; // 当前点击的key
  let st = 1; // 同上映射：1 降序 2 升序 3 无排序
  if (keyName === key) {
    const orderNum = sortMap.get(order); // 当前排序状态
    st = orderNum === 3 ? 1 : orderNum + 1; // 下一个排序状态
  }
  sortRes.value = { key: kn, order: sortMap.get(st) }; // 更新排序状态
};
</script>

<style scoped lang="scss">
.jzSortCom {
  display: flex;
  align-items: center;

  .jsItem {
    display: flex;
    align-items: center;
    font-size: 15px;
    color: #a8abb2;
    letter-spacing: 1px;
    font-weight: 600;
    cursor: pointer;

    .isIconList {
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      margin-left: 6px;

      img {
        width: 10px;
        height: auto;
        background-color: transparent;

        &.up {
          transform: rotate(180deg);
        }
      }

      img+img {
        margin-top: 2px;
      }
    }
  }

  .jsItem+.jsItem {
    margin-left: 60px;
  }
}
</style>
