<template>
  <div class="app-container">
    <div class="head-container">
      <el-button type="primary" icon="el-icon-plus" @click="$refs.addGroupRef.show()">
        添加分组
      </el-button>
      <addGroup ref="addGroupRef" @success="resetHandle" />
    </div>
    <div class="head-container" id="table_drag">
      <el-table :data="tableData.list" v-loading="tableData.loading" row-key="id">
        <el-table-column label="排序" sortable prop="sort"></el-table-column>
        <el-table-column label="分组名称" prop="name"></el-table-column>
        <el-table-column label="售卖时间管控" prop="useTime">
          <template v-slot="scope">
            <template v-if="scope.row.useTime == 1">

              <!-- {{ scope.row.saleStartTime + '-' + (scope.row.saleEndTime) }} -->
              {{ saleEndTimeFilter(scope.row.saleStartTime, scope.row.saleEndTime) }}
              <!-- {{ new Date(scope.row.saleEndTime+'').getTime() }} -->
            </template>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch v-model="scope.row.isShow" :active-value="1" :inactive-value="0"
              @change="showChange($event, scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template v-slot="scope">
            <el-button type="text" icon="el-icon-rank" v-if="isPcBowser">排序</el-button>
            <el-button type="text" size="mini" round icon="el-icon-edit" @click="$refs.addGroupRef.show(scope.row)"
              style="margin-left: 20px !important;">编辑</el-button>
            <el-popconfirm title="确定删除吗？" @confirm="delHandle([scope.row.id])">
              <el-button type="text" size="mini" round icon="el-icon-delete" slot="reference">
                删除
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination :total="tableData.total" :current-page="tableData.page + 1" :page-size="tableData.size" @size-change="sizeChange"
      @current-change="paginationChange" layout="total, sizes, prev, pager, next, jumper"></el-pagination>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
import addGroup from '../components/addGroup'
import { hasPermission } from '@/utils/limits.js'
import { tbProductGroupGet, tbProductGroupDelete, tbProductGroupPut, upGroupSort } from '@/api/shop'
export default {
  components: {
    addGroup
  },
  data() {
    return {
      tableData: {
        page: 0,
        size: 30,
        total: 0,
        loading: false,
        list: []
      }
    }
  },
  mounted() {
    this.getTableData()
    if (this.isPcBowser) {
      this.$nextTick(() => {
        this.tableDrag()
      })
    }
  },
  filters: {

  },
  methods: {
    sizeChange(e){
      this.tableData.size = e
      this.getTableData()
    },
    saleEndTimeFilter: (a, b) => {

      var currentDate = new Date(); // 当前日期对象
      var dateString = currentDate.toDateString(); // 获取当前日期的字符串表示（不包含时分秒）
      var dateTimeString = dateString + ' ' + a; // 拼接日期和时分秒字符串
      var dateTimeStringb = dateString + ' ' + b; // 拼接日期和时分秒字符串
      var timestamp = Date.parse(dateTimeString); // 将日期时间字符串转换为时间戳
      var timestamp2 = Date.parse(dateTimeStringb); // 将日期时间字符串转换为时间戳
      let ciri = timestamp > timestamp2 ? '次日' : ''
      return a + ' - ' + ciri + b
    },
    //表格拖拽
    async tableDrag() {
      
      const el = document.querySelector('#table_drag .el-table__body-wrapper tbody')
      new Sortable(el, {
        animation: 150,
        onEnd: async e => {
          // console.log('拖拽结束===', e);
          let res = await hasPermission('允许修改分组');
      if ( !res) { return; }
          if (e.oldIndex == e.newIndex) return
          let oid = this.tableData.list[e.oldIndex].id
          let nid = this.tableData.list[e.newIndex].id
          let ids = this.tableData.list.map(item => item.id)
          try {
            await upGroupSort({
              strId: oid,
              endId: nid,
              ids: ids
            })
            await this.getTableData()
          } catch (error) {
            console.log(error);
          }
        }
      });
    },
    // 状态切换
    async showChange(e, row) {
      let res = await hasPermission('允许修改分组');
      if ( !res) { row.isShow = (e == 0 ? 1 : 0);return; }
      
      try {
        await tbProductGroupPut(row)
        this.getTableData()
      } catch (error) {
        console.log(error);
      }
    },
    // 重置查询
    resetHandle() {
      this.tableData.page = 0;
      this.getTableData()
    },
    // 分页回调
    paginationChange(e) {
      this.tableData.page = e - 1
      this.getTableData()
    },
    // 删除
    async delHandle(ids) {
      let res = await hasPermission('允许修改分组');
      if ( !res) { return; }
      try {
        await tbProductGroupDelete(ids)
        this.$notify({
          title: '成功',
          message: `删除成功`,
          type: 'success'
        });
        this.getTableData()
      } catch (error) {
        console.log(error)
      }
    },
    // 获取商品列表
    async getTableData() {
      try {
        this.tableData.loading = true
        const res = await tbProductGroupGet({
          page: this.tableData.page,
          size: this.tableData.size,
          sort: 'id',
          shopId: localStorage.getItem('shopId')
        })
        this.tableData.loading = false
        this.tableData.list = res.content
        this.tableData.total = res.totalElements
      } catch (error) { }
    }
  }
}
</script>