<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-form :inline="true" class="print-options">
        <el-form-item label="打印规格">
          <el-select v-model="selectedSize" placeholder="请选择打印规格">
            <el-option label="大号 (9.5cm × 3.5cm)" value="large"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="缩放">
          <el-input-number
            v-model="scale"
            :min="50"
            :max="150"
            :step="10"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="打印方向">
          <el-select v-model="printOrientation" placeholder="请选择打印方向">
            <el-option label="纵向" value="portrait"></el-option>
            <el-option label="横向" value="landscape"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="print-preview-container">
        <div id="deliverySheet" :style="{ transform: `scale(${scale / 100})` }">
          <div class="tips-t" v-for="(item, index) in codeList" :key="index">
            <div class="content-wrapper">
              <div class="barcode-container">
                <svg :id="`barcode-${index}`"></svg>
              </div>
              <div class="numOrder">{{ String(item).toUpperCase() }}</div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancle">取消</el-button>
        <el-button type="primary" @click="handlePrintGoodsLend">打印</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as API_Setting from "@/api/setting";
import * as API_ProductClass from "@/api/productClass";
import JsBarcode from "jsbarcode";
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: [],
      selectedSize: "large",
      scale: 100,
      codeList: [], // 假设这里存储了需要生成条形码的数据
      PrintVisible: false,
      printOrientation: "portrait", // 默认为纵向打印
    };
  },
  mounted() {
    this.GET_SystemLogs();
    this.rowDrop();
  },
  watch: {
    PrintVisible(newVal) {
      if (newVal) {
        this.$nextTick(() => {
          this.generateBarcodes();
        });
      }
    },
  },
  methods: {
    generateBarcodes() {
      this.$nextTick(() => {
        this.codeList.forEach((item, index) => {
          JsBarcode(`#barcode-${index}`, item, {
            format: "CODE128",
            width: 2,
            height: 60,
            displayValue: false,
          });
        });
      });
    },
    /*  handlePrintGoodsLend() {
      this.generateBarcodes();
      this.$nextTick(() => {
        const printContent = document.getElementById("deliverySheet").innerHTML;
        const printWindow = window.open("", "_blank");
        printWindow.document.write(`
          <html>
            <head>
              <title>打印标签</title>
              <style>
                @page {
                  size: 95mm 35mm;
                  margin: 0;
                }
                body {
                  margin: 0;
                  width: 95mm;
                  height: 35mm;
                }
                .tips-t {
                  width: 95mm;
                  height: 35mm;
                  box-sizing: border-box;
                  padding: 2mm;
                  page-break-after: always;
                  display: flex;
                  flex-direction: column;
                  justify-content: center;
                  align-items: center;
                }
                .content-wrapper {
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                }
                .barcode-container {
                  margin-bottom: 2mm;
                }
                .numOrder {
                  font-size: 14px;
                }
              </style>
            </head>
            <body>${printContent}</body>
          </html>
        `);
        printWindow.document.close();
        printWindow.focus();
        printWindow.print();
        printWindow.close();
      });
    }, */

    handleCancle() {
      this.PrintVisible = false;
    },
    /** 多选改变 */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 批量打印
    batchPrint() {
      const ids = this.multipleSelection.map((item) => item.sku);
      this.codeList = ids;
      this.PrintVisible = true;
    },
    /** 打印对账详情 */
    handlePrintGoodsLend() {
      // 生成条形码
      this.generateBarcodes();

      // 准备打印样式
      const style = `
    @page {
      size: ${this.printOrientation};
      margin: 0;
    }
    body {
      margin: 0;
    }
    .tips-t {
      width: 95mm;
      height: 35mm;
      page-break-after: always;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      box-sizing: border-box;
      padding: 2mm;
    }
    .content-wrapper {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    .barcode-container {
      margin-bottom: 2mm;
    }
    .numOrder {
      font-size: 14px;
    }
    ${
      this.printOrientation !== "landscape"
        ? `
      .tips-t {
        transform: rotate(90deg);
        transform-origin: top left;
        width: 35mm;
        height: 95mm;
        position: absolute;
        left: 35mm;
        top: 0;
      }
    `
        : ""
    }
  `;

      // 使用 print-js 打印
      Print({
        printable: "deliverySheet",
        type: "html",
        css: style,
        style: style,
        scanStyles: false,
        targetStyles: ["*"],
      });
    },
    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;
}

.print-preview-container {
  overflow: auto;
  width: 100%;
  height: 400px;
  display: flex;
  justify-content: center;
  align-items: flex-start;

  &.portrait {
    #deliverySheet {
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .tips-t {
      width: 95mm;
      height: 35mm;
    }
  }

  &.landscape {
    #deliverySheet {
      display: flex;
      flex-wrap: wrap;
      justify-content: flex-start;
    }

    .tips-t {
      width: 35mm;
      height: 95mm;
      margin-right: 2mm;
    }
  }
}

#deliverySheet {
  transform-origin: top left;
}

.tips-t {
  border: 1px solid #ccc;
  margin-bottom: 2mm;
  padding: 2mm;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .content-wrapper {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  .numOrder {
    font-size: 14px;
    margin-top: 1mm;
  }

  .barcode-container {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-bottom: 2mm;

    svg {
      max-width: 100%;
      height: auto;
    }
  }
}
#deliverySheet {
  transform-origin: top left;
  padding: 10mm;
}

#deliverySheet.portrait .tips-t {
  width: 95mm;
  height: 35mm;
}

#deliverySheet.landscape .tips-t {
  width: 35mm;
  height: 95mm;
}
.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

@media print {
  @page {
    size: auto;
    margin: 0;
  }

  body {
    margin: 0;
  }

  .print-options,
  .dialog-footer {
    display: none;
  }

  #deliverySheet {
    transform: none !important;
  }

  .tips-t {
    page-break-inside: avoid;
    margin-bottom: 0;
  }
}
</style>