<template>
  <div class="list-sorter-wrapper" ref="sortFileds">
    <div @click="sort(row.name)" v-for="(row,index) in fields" :key="index" class="list-sorter-item">
      {{ row.label }}
      <div>
        <rt-icon class="list-sorter-icon rotate" name="rt-xrm-sort-down" size="6"></rt-icon>
        <rt-icon class="list-sorter-icon" name="rt-xrm-sort-down" size="6"></rt-icon>
      </div>
    </div>
  </div>
</template>
<script>
  export default {
    name: 'rtSorList',
    props: {
      fields: {
        type: Array,
        required: true
      },
      value: {
        type: String,
        required: true
      }
    },
    model: {
      prop: 'value',
      event: 'input'
    },
    methods: {
      sort(filed) {
        // 当前元素
        const el = event && event.currentTarget;
        // 当前元素未被选中时，清除之前元素的样式
        if (!el.classList.contains('sorted')) {
          const oldEl = this.$refs.sortFileds.querySelectorAll('.sorted');
          oldEl.forEach(item => {
            item.classList.remove('sorted');
          });
          el.classList.add('sorted');
          el.children[0].children[0].classList.add('sorted');
          this.$emit('input', filed + ' asc');
          return;
        }

        // 当前元素已被选中，调整排序的升降序
        if (el.children[0].children[0].classList.contains('sorted')) {
          el.children[0].children[0].classList.remove('sorted');
          el.children[0].children[1].classList.add('sorted');
          this.$emit('input', filed + ' desc');
        } else if (el.children[0].children[1].classList.contains('sorted')) {
          el.children[0].children[0].classList.add('sorted');
          el.children[0].children[1].classList.remove('sorted');
          this.$emit('input', filed + ' asc');
        }
      }
    }
  };
</script>
<style lang="less">
  .list-sorter-wrapper {
    position: relative;
    display: flex;
    flex: 1;
    .list-sorter-item {
      text-align: center;
      font-size: 14px;
      color: #888;
      flex: 1;
      &.sorted {
        color: #53a4fc;
      }
      div {
        display: inline-block;
        height: 11px;
        .list-sorter-icon {
          display: flex;
          color: #222;
          &.rotate {
            transform: rotateX(180deg);
          }
          &.sorted {
            color: #53a4fc;
          }
        }
      }

      &.filter {
        color: #53a4fc;
      }
    }
  }
</style>
