<template>
  <a-modal
    :visible="visible"
    title="快速分类排序（拖拽票种进行分类和排序）"
    width="90%"
    ok-text="保存"
    cancel-text="关闭"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin
      class="ticketSort"
      :spinning="loading"
    >
      <div
        class="item-wrap"
        v-for="(group,index) in groupTickets"
        :key="index"
      >
        <a-card :title="group.category.name">
          <draggable
            v-bind="dragOptions"
            :list="group.tickets"
            tag="ul"
          >
            <!-- <li
              v-for="i in 1000"
              :key="i"
            >
              {{ i }}
            </li> -->
            <li
              class="list-group-item"
              v-for="(item) in group.tickets"
              :key="item.id"
            >
              {{ item.name }}
            </li>
          </draggable>
        </a-card>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import draggable from 'vuedraggable'
import { groupBy } from 'lodash'
import { getTicketCategory } from '@/api/ticketSetting/ticketCategory'
import { getTicketType, setTicketTypeById, updateseq } from '@/api/ticketSetting/ticket'

export default {
  components: {
    draggable
  },
  data () {
    return {
      visible: false,
      loading: false,
      confirmLoading: false,
      groupTickets: [],
      dragOptions: {
        animation: 200,
        group: 'description',
        disabled: false,
        ghostClass: 'ghost'
      }
    }
  },
  methods: {
    show () {
      this.visible = true
      this.getTicketCategory()
    },
    handleCancel () {
      this.visible = false
    },
    getTicketCategory () {
      this.loading = true
      getTicketCategory({ pageNum: 0, pageSize: 0, status: ['active'] }).then(res => {
        this.categoryList = res.extraInfo.list
        this.getTicketTypeList()
      })
    },
    getTicketTypeList () {
      const params = {
        type: 'BATCH',
        pageSize: 9999
      }
      getTicketType(params).then(res => {
        // 设置原始分类id
        res.extraInfo.list.forEach(i => { i.oldCategoryId = i.category.id })
        // 有分类的票种
        const ticketTypeList = res.extraInfo.list.filter(i => i.category.status !== 'deleted' && i.category.status !== 'inactive')
        // 无分类的票种
        const noCategoryTicketTypeList = res.extraInfo.list.filter(i => i.category.status === 'deleted' || i.category.status === 'inactive')
        // 按分类进行分组
        const groupTickets = groupBy(ticketTypeList, item => item.category.id)

        // 数据整理
        this.groupTickets = this.categoryList.map(item => {
          return {
            category: item,
            tickets: groupTickets[item.id] || []
          }
        })

        // 插入未分类票种
        this.groupTickets.push({
          category: { name: '未分类或无效分类', id: 0 },
          tickets: noCategoryTicketTypeList
        })
      }).finally(() => {
        this.loading = false
      })
    },
    async handleOk () {
      let updateItems = []

      // 只修改分类发生改变的票种
      this.groupTickets.forEach(group => {
        const items = group.tickets.filter(i => i.category.id !== group.category.id)
        items.forEach(i => {
          i.newCategoryId = group.category.id
        })
        updateItems = updateItems.concat(items)
      })

      let successIdx = 0
      this.loading = true
      // 更新排序
      await this.updateseq()

      if (updateItems.length === 0) {
        this.loading = false
        this.$message.success('更新成功。')
        this.$emit('update')
        return
      }

      // 更新分类
      updateItems.forEach(item => {
        item.category = item.newCategoryId
        item.tags && (item.tags = item.tags.map(i => i.id))

        setTicketTypeById(item.id, item).then(res => {

        }).finally(() => {
          successIdx++
          if (successIdx === updateItems.length) {
            this.$message.success('更新成功。')
            this.loading = false
            this.getTicketCategory()
            this.$emit('update')
          }
        })
      })
    },
    updateseq () {
      let orderItem = []
      this.groupTickets.forEach(group => {
        orderItem = orderItem.concat(group.tickets)
      })

      const orderIds = orderItem.map(i => i.id)
      return updateseq({ ids: orderIds })
    }
  }
}
</script>

<style lang="scss" scoped>
.ticketSort {
  ::v-deep .ant-spin-container {
    display: flex; width: 100%;
  }
  ::v-deep .ant-card {
    min-height: 100%;  margin-bottom: 0;
    ul {
      min-height: 300px;
    }
    .ant-card-body {
      padding: 0px;
    }
  }
  .item-wrap + .item-wrap {
    margin-left: 5px;
  }
  .item-wrap {
    flex: 1;
  }

  .flip-list-move {
    transition: transform .5s;
  }
  .no-move {
    transition: transform 0s;
  }

  .list-group-item {
    padding: 5px; cursor: move; border-bottom: 1px solid #ddd;border-top: 1px solid #ddd; background: #fff; margin-top: -1px;
    &:hover {
      background: rgb(253, 245, 231);
    }
  }

  .ghost {
    background: #c8ebfb;  opacity: .5;
  }

  .fixed-btn-wrap {
    position: fixed; bottom: 50px; left: 0; z-index: 20; width: 100%; text-align: center;
  }
  .loading {
    position: absolute; top: 0;left: 0; z-index: 30; display: flex; width: 100%;height: 100%; background: rgba(255, 255, 255, .1); justify-content: center;align-items: center;
  }
}

</style>
