<template>
  <div class="app-container">
    <!-- 搜索 -->
    <SearchBlock v-model="query" :menus="queryOption" @change="queryTable"></SearchBlock>
    <!-- 表格工具按钮 -->
    <div class="table-operate">
      <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        size="mini"
        @click="handleAdd"
        v-hasPermi="['gangkou:vehicle:add']"
        >新增</el-button
      >
      <el-button
        type="danger"
        plain
        icon="el-icon-delete"
        size="mini"
        :disabled="selection.length === 0"
        @click="handleMultDelete"
        v-hasPermi="['gangkou:vehicle:remove']"
        >删除选中</el-button
      >
      <el-button
        type="success"
        plain
        size="mini"
        :disabled="selection.length === 0"
        @click="handlePrint"
      >打印预览</el-button
      >
<!--      <el-button-->
<!--        type="info"-->
<!--        plain-->
<!--        icon="el-icon-upload2"-->
<!--        size="mini"-->
<!--        @click="handleImport"-->
<!--        v-hasPermi="['gangkou:vehicle:import']"-->
<!--      >导入</el-button>-->
<!--      <el-button-->
<!--        type="warning"-->
<!--        plain-->
<!--        icon="el-icon-download"-->
<!--        size="mini"-->
<!--        @click="handleExport"-->
<!--      >导出</el-button>-->
    </div>
    <!-- 表格 -->
    <el-table
      ref="table"
      tooltip-effect="dark"
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      border
      @sort-change="sortChange"
      :default-sort="sort"
    >
      <el-table-column v-hasPermi="['gangkou:vehicle:remove']" type="selection" width="50" />
      <el-table-column label="车辆编号" align="center" prop="vehicleNumber" sortable='custom' show-overflow-tooltip min-width='120' />
      <el-table-column label="车牌号" align="center" prop="vehicleNo" show-overflow-tooltip min-width='120' />
      <el-table-column label="车辆类型" align="center" prop="vehicleType" show-overflow-tooltip min-width='120' />
      <el-table-column label="设备型号" align="center" prop="vehicleModel" show-overflow-tooltip min-width='120' />
      <el-table-column label="发动机号" align="center" prop="engineNo" show-overflow-tooltip min-width='120' />
      <el-table-column label="车辆识别代码" align="center" prop="vinNo" show-overflow-tooltip min-width='120' />
      <el-table-column label="发动机型号" align="center" prop="engineModel" show-overflow-tooltip min-width='120' />
      <el-table-column label="设备马力" align="center" prop="horsePower" sortable='custom' show-overflow-tooltip min-width='120' />
      <el-table-column label="车辆轴数" align="center" prop="axlesNumber" sortable='custom' show-overflow-tooltip min-width='120' />
      <el-table-column label="装卸能力" align="center" prop="loadingCapacity" sortable='custom' show-overflow-tooltip min-width='120' />
      <el-table-column label="发动机厂家" align="center" prop="engineManufacturer" show-overflow-tooltip min-width='120' />
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip min-width='160' />
      <el-table-column width="86px" align="center" label="操作" fixed="right">
        <template slot-scope="scope">
          <el-link type="primary" v-hasPermi="['gangkou:vehicle:edit']" @click="handleEdit(scope.row)">编辑</el-link>
          <el-link type="danger" v-hasPermi="['gangkou:vehicle:remove']" @click="handleDelete(scope.row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格页脚 -->
    <pagination
      hide-on-single-page
      :total="total"
      :page.sync="page.pageNum"
      :limit.sync="page.pageSize"
      @pagination="getTableList"
    />
    <EditDialog ref="editDialog" @refresh="getTableList"></EditDialog>
    <el-dialog :visible.sync="isDialogVisible" title="打印预览">
      <!-- 确保此元素有正确的 ref -->
      <div id="barcodeWrapper" style="display: flex; flex-wrap: wrap; justify-content: space-around;">
        <!-- 条形码会动态插入到这里 -->
      </div>
      <span slot="footer" class="dialog-footer">
      <el-button @click="handlePrintPreview">打印</el-button>
      <el-button @click="isDialogVisible = false">关闭</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
import TableMixin from "@/mixins/table-mixin";
import EditDialog from "./components/EditDialog";
import { pageListVehicle, delVehicle } from "@/api/gangkou/vehicle/vehicle";
import JsBarcode from 'jsbarcode';

export default {
  name: 'Vehicle',
  mixins: [TableMixin],
  components: { EditDialog },
  data() {
    return {
      isDialogVisible: false,  // 控制弹窗是否可见
      // 选中数组
      ids: [],
      // 选中车牌号
      vehicleNos: [],
      // 车辆编号
      vehicleNumbers: [],
      queryOption: [
        {
          label: '车牌号',
          prop: 'vehicleNo',
          type: 'text',
          default: '',
        },
        {
          label: '车辆编号',
          prop: 'vehicleNumber',
          type: 'text',
          default: '',
        },
        {
          label: '车辆类型',
          prop: 'vehicleType',
          type: 'text',
          default: '',
        },
        {
          label: '设备型号',
          prop: 'vehicleModel',
          type: 'text',
          default: '',
        },
        {
          label: '发动机号',
          prop: 'engineNo',
          type: 'text',
          default: '',
        },
        {
          label: '车辆识别代码',
          prop: 'vinNo',
          type: 'text',
          default: '',
        },
        {
          label: '发动机型号',
          prop: 'engineModel',
          type: 'text',
          default: '',
        },
        {
          label: '设备马力',
          prop: 'horsePower',
          type: 'text',
          default: '',
        },
        {
          label: '车辆轴数',
          prop: 'axlesNumber',
          type: 'text',
          default: '',
        },
        {
          label: '装卸能力',
          prop: 'loadingCapacity',
          type: 'text',
          default: '',
        },
        {
          label: '发动机厂家',
          prop: 'engineManufacturer',
          type: 'text',
          default: '',
        },
      ]
    };
  },
  methods: {
    mx_pageInfo() {
      return {
        title: '车辆档案',
        exportUrl: '',
        pageListApi: pageListVehicle,
        deleteApi: delVehicle,
        query: {},
      };
    },
    handlePrint() {
      const vehicleNos = this.selection.map(item => item.vehicleNo);
      const vehicleNumbers = this.selection.map(item => item.vehicleNumber);
      // 显示弹窗
      this.isDialogVisible = true;
      // 清空现有条形码
      this.$nextTick(() => {
        // 确保 DOM 渲染后再获取 barcodeWrapper
        const barcodeWrapper = document.getElementById('barcodeWrapper');
        barcodeWrapper.innerHTML = ''; // 清空之前的条形码
        // 设置外层容器为 flex 布局，每行两个条形码
        barcodeWrapper.style.display = 'flex';
        barcodeWrapper.style.flexWrap = 'wrap'; // 允许换行
        barcodeWrapper.style.justifyContent = 'space-around'; // 确保条形码均匀分布
        barcodeWrapper.style.gap = '20px'; // 设置条形码之间的间隔
        vehicleNos.forEach((vehicleNo, i) => {
          // 创建条形码容器
          const barcodeContainer = document.createElement('div');
          barcodeContainer.style.marginBottom = '60px'; // 增加上下条形码之间的间距
          barcodeContainer.style.textAlign = 'center';
          barcodeContainer.style.position = 'relative'; // 设置相对定位来添加绝对定位的图片
          barcodeContainer.style.width = 'calc(50% - 10px)'; // 每行两个条形码，减去间距

          // 创建并添加图片到条形码容器的左上角
          const logoImg = document.createElement('img');
          logoImg.src = '/static/img/logo.aca359b6.png'; // 图片路径
          logoImg.style.position = 'absolute';
          logoImg.style.top = '-25px';
          logoImg.style.left = '0';
          logoImg.style.width = '40px'; // 设置图片的大小
          logoImg.style.height = 'auto'; // 保持图片的比例
          // 将图片添加到条形码容器中
          barcodeContainer.appendChild(logoImg);

          // 创建 canvas 用于生成条形码
          const barcodeCanvas = document.createElement('canvas');
          // 使用 JsBarcode 生成条形码
          JsBarcode(barcodeCanvas, vehicleNo, {
            format: 'CODE128',
            width: 2,
            height: 40,
            displayValue: false // 不显示条形码下方的值
          });
          // 设置条形码 canvas 宽度为 100%，保持响应式
          barcodeCanvas.style.maxWidth = '100%';
          barcodeCanvas.style.height = 'auto';
          // 将条形码添加到容器中
          barcodeContainer.appendChild(barcodeCanvas);
          // 创建车牌号和车辆编号文本
          const vehicleInfo = document.createElement('div');
          vehicleInfo.style.marginTop = '10px';
          vehicleInfo.innerHTML = `车辆编号：${vehicleNumbers[i]}   车牌号：${vehicleNos[i]}`;
          // 将车牌号和车辆编号文本添加到条形码容器中
          barcodeContainer.appendChild(vehicleInfo);
          // 将整个容器添加到 barcodeWrapper
          barcodeWrapper.appendChild(barcodeContainer);
        });
      });
    },
    handlePrintPreview() {
      // 获取要打印的内容
      var printContents = document.getElementById("barcodeWrapper").innerHTML;
      // 创建一个隐藏的 iframe 元素
      var iframe = document.createElement('iframe');
      iframe.style.position = 'absolute';
      iframe.style.width = '0px';
      iframe.style.height = '0px';
      iframe.style.border = 'none';
      document.body.appendChild(iframe);
      // 获取 iframe 的文档对象
      var iframeDoc = iframe.contentWindow.document;
      // 先打开 iframe 文档
      iframeDoc.open();
      // 插入 HTML 内容和 CSS 样式到 iframe
      iframeDoc.write(`
        <html>
          <head>
            <style>
              body {
                font-family: Arial, sans-serif;
                margin: 0;
                padding: 0;
              }
              .print-only {
                display: flex;
                flex-wrap: wrap;
                justify-content: space-around;
                padding: 20px;
              }
              /* 其他样式保持不变，根据需要调整 */
            </style>
          </head>
          <body>
            <div class="print-only">
              ${printContents}
            </div>
          </body>
        </html>
      `);
      iframeDoc.close();  // 关闭文档流
      // 使用 setTimeout 延迟执行打印
      setTimeout(function() {
        // 等待 iframe 加载完成后执行打印
        iframe.contentWindow.print();
        // 打印完成后移除 iframe
        document.body.removeChild(iframe);
      }, 500); // 延迟500毫秒，确保 iframe 已加载
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "客户信息导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      const fileName = `客户信息模板_${new Date().getTime()}.xlsx`;
      this.download(`jxc/cust/importTemplate`, {}, fileName);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/cm/vehicle/export', {
        ...this.queryParams
      }, `车辆信息_${new Date().getTime()}.xlsx`)
    },
  },
};
</script>

<style scoped lang="scss">
</style>

