<template>
  <div>
    <en-table-layout :tableData="tableData.data" :loading="loading" class="draggable-table" @selection-change="handleSelectionChange">
      <div slot="toolbar" class="inner-toolbar inner-toolbar2">
        <div class="toolbar-btns">
          <el-button size="mini" type="primary" :disabled="multipleSelection.length === 0"
          @click="batchPrint">批量打印</el-button>
        </div>
        <!-- <en-table-search @search="searchEvent" @advancedSearch="advancedSearchEvent" advanced advancedWidth="465"
            placeholder=''>
            <template slot="advanced-content">
              <el-form ref="advancedForm" :model="advancedForm" label-width="80px">
                <el-form-item label="日志级别">
                  <el-select v-model="advancedForm.level" placeholder="请选择" clearable>
                    <el-option label="一般" value="normal" />
                    <el-option label="重要" value="important" />
                  </el-select>
                </el-form-item>
                <el-form-item label="操作时间">
                  <el-date-picker v-model="advancedForm.order_time_range" type="daterange" align="center" :editable="false"
                    unlink-panels :default-time="['00:00:00', '23:59:59']" range-separator="-" start-placeholder="开始日期"
                    end-placeholder="结束日期" value-format="timestamp"
                    :picker-options="{ disabledDate(time) { return time.getTime() - 1 >= new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime() + 86400000 - 1 }, shortcuts: MixinPickerShortcuts }">
                  </el-date-picker>
                </el-form-item>
              </el-form>
            </template>
</en-table-search> -->
      </div>

      <template slot="table-columns">
        <el-table-column label="" width="100">
          <template>
            <span class="drag-handle">&#9776;</span> <!-- 拖拽图标 -->
            <!-- 其他操作按钮 -->
          </template>
        </el-table-column>
        <el-table-column type="selection" width="55" />
        <el-table-column label="图标">
            <template slot-scope="scope">
              <img :src="scope.row.goods_vo.image_small_list" alt="" width="50px">
            </template>
          </el-table-column>
        <el-table-column prop="goods_vo.name" label="商品名称">
          <template slot-scope="scope">
            <span class="selectable">{{ scope.row.goods_vo.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods_vo.sn" label="商品编号">
          <template slot-scope="scope">
            <span class="selectable">{{ scope.row.goods_vo.sn }}</span>
          </template>
        </el-table-column>
        <el-table-column label="SKU" align="center">
          <template slot-scope="scope">
            <span class="selectable">{{ scope.row.sku }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="spec_name" label="规格型号">
          <!-- <template slot-scope="scope">
            <span class="selectable">{{ scope.row.spec_name }}</span>
          </template> -->
        </el-table-column>
        <!-- <el-table-column label="条码" align="center">
          <template slot-scope="scope">{{ scope.row.bar_code }}</template>
        </el-table-column> -->
        <!-- <el-table-column prop="sort" label="排序号">
          <template slot-scope="scope">
            <span class="selectable">{{ scope.row.sort }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="310">
          <template slot-scope="scope">
            <el-button size="mini" @click="PrintIng(scope.row)">打印SKU</el-button>
          </template>
        </el-table-column>
      </template>

      <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[20, 50, 70, 100]"
        :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.data_total">
      </el-pagination>
    </en-table-layout>

    <!--  <el-dialog title="日志详情" :visible.sync="showLogDetail" width="40%">
        <div class="logInfo">账号：{{ currDetailLog.operator_name }}</div>
        <div class="logInfo">操作描述：{{ currDetailLog.operate_detail }}</div>
        <div class="logInfo">请求方法：{{ currDetailLog.method }}</div>
        <div class="logInfo">请求参数：{{ currDetailLog.params }}</div>
        <div class="logInfo">ip地址：{{ currDetailLog.operate_ip }}</div>
        <div class="logInfo">日志级别：{{ currDetailLog.level === 'important' ? '重要' : '一般' }}</div>
        <div class="logInfo">操作时间：{{ currDetailLog.operate_time | unixToDate }}</div>
      </el-dialog> -->
    <el-dialog title="打印预览" :visible.sync="PrintVisible" width="940px" center @close="handleCancle">
      <el-button size="mini" type="primary" @click="handlePrintGoodsLend" class="print">打印</el-button>
      <div id="deliverySheet" style="width: 900px">
        <div class="tips-t" v-for="(item, index) in codeList" :key="index">
          <div>
            <!-- <div class="qrcode-pic" ref="codeItem" ></div> -->
            <div class="numOrder">

            </div>
            <div style="margin-top: 10px; font-size: 20px; text-align: center">
              <barcode :value="item" format="CODE128" height="65" width="1"></barcode>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as API_Setting from '@/api/setting';
import * as API_ProductClass from '@/api/productClass';
import Sortable from "sortablejs";
import Print from "print-js";
export default {
  name: 'systemLogs',
  data() {
    return {
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 20
      },
      // 列表数据
      tableData: '',
      // 时间输入框
      searchTime: '',
      // 是否显示日志详情弹窗
      showLogDetail: false,
      // 当前日志详情信息
      currDetailLog: {},
      // 高级搜索数据
      advancedForm: {},
      PrintVisible:false,
      codeList:[],
      barcodeValue:"",
      // 当前已选择的行
      multipleSelection: [],
    }
  },
  mounted() {
    this.GET_SystemLogs()
    this.rowDrop();
  },
  methods: {
    /** 多选改变 */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
     // 批量打印
     batchPrint() {
      const ids = this.multipleSelection.map((item) => item.sku);
      this.codeList = ids;
      this.PrintVisible = true;
    },
    /** 打印对账详情 */
    handlePrintGoodsLend() {
      Print({
        printable: "deliverySheet",
        type: "html",
        targetStyles: ["*"],
        ignoreElements: ["no-logs", "goods-image", "no-btn"],
      });
    },
    handleCancle() {
      this.PrintVisible = false;
      this.codeList = [];
    },
    // 打印
    PrintIng(row) {
      this.barcodeValue = row.sku;
      this.$nextTick(() => {
        this.codeList.push(row.sku);
        this.PrintVisible = true;
      });
    },
    // 行拖拽
    rowDrop() {
      const tbody = document.querySelector(".draggable-table .el-table__body-wrapper tbody");
      const _this = this;
      Sortable.create(tbody, {
        animation: 300,
        handle: ".drag-handle", // 只有拖拽图标可以触发拖拽
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.tableData.data.splice(newIndex, 1)[0];
          /* const sort = _this.tableData.data.splice(newIndex+1, 1)[0].sort; */
          _this.tableData.data.splice(newIndex, 0, currRow);
          /*  console.log("拖拽后的行详情：", currRow); */
          //console.log(currRow,sort);
          _this.updateList(currRow.id, newIndex);
        },
      });
    },
    // 更新列表顺序
    updateList(id, newIndex) {
      const data = [{
        position: 'own',
        product_id: this.tableData.data[newIndex].id,
        sort: this.tableData.data[newIndex].sort
      }];

      if (newIndex > 0) { // Check if there is a row before
        data.push({
          position: 'before',
          product_id: this.tableData.data[newIndex - 1].id,
          sort: this.tableData.data[newIndex - 1].sort
        });
      }

      if (newIndex < this.tableData.data.length - 1) { // Check if there is a row after
        data.push({
          position: 'after',
          product_id: this.tableData.data[newIndex + 1].id,
          sort: this.tableData.data[newIndex + 1].sort
        });
      }

      // 假设API需要商品ID和新的索引位置
      API_ProductClass.updateSort({ data: data }).then((res) => {
        this.$message.success("更新成功！");
        this.GET_SystemLogs();
      }).catch(() => { this.$message.error("更新失败！"); })
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_SystemLogs()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_SystemLogs()
    },
    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        keyword: data
      }
      Object.keys(this.advancedForm).forEach(key => delete this.params[key])
      this.params.page_no = 1
      this.GET_SystemLogs()
    },
    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm
      }
      delete this.params.start_time
      delete this.params.end_time
      if (this.advancedForm.order_time_range) {
        this.params.start_time = this.advancedForm.order_time_range[0] / 1000
        this.params.end_time = this.advancedForm.order_time_range[1] / 1000
      }
      delete this.params.keyword
      delete this.params.order_time_range
      this.params.page_no = 1
      this.GET_SystemLogs()
    },

    /** 获取日志列表 */
    GET_SystemLogs() {
      this.loading = true
      const params = this.MixinClone(this.params)
      Object.keys(params).forEach(key => {
        if (!params[key] && params[key] !== 0) {
          delete params[key]
        }
      })
      API_ProductClass.getProduct(params).then(response => {
        this.loading = false
        this.tableData = response
        this.params.page_no = response.page_no
        this.params.page_size = response.page_size
      }).catch(() => { this.loading = false })
    },
    /** 显示日志详情 */
    handleShowDetail(row) {
      this.showLogDetail = true
      this.currDetailLog = row
    }
  }
}
</script>

<style>
.print {
  margin-left: 790px;
}
.inner-toolbar2 {
  justify-content: flex-start !important;
}

.inner-toolbar2 .dateSearch {
  margin-right: 20px;
}

.toolbar-search {
  display: flex;
  width: 400px;
}

.toolbar-search .el-button {
  margin-left: 18px;
}
</style>
<style type="text/scss" lang="scss" scoped>
.nc-container {
  height: 32px !important;
  overflow: hidden;

}

.drag-handle {
  cursor: move;
  /* 设置鼠标为拖拽样式 */
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}

/deep/ .img-code {
  width: 80%;

  .el-input-group__append {
    padding: 0;
    margin: 0;

    img {
      display: block;
      height: 30px;
      cursor: pointer;
    }
  }
}

.dateSearch {}

.logInfo {
  margin-bottom: 20px;
}
</style>