<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="日期" prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="开始日期"
          @change="() => queryParams.endTime = ''"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item>-</el-form-item>
      <el-form-item prop="endTime">
        <el-date-picker
          v-model="queryParams.endTime"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="结束日期"
          :picker-options="{ disabledDate: (t) => t.getTime() < new Date(queryParams.startTime).getTime() - 86400000}"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item label="关键字" prop="keyWord">
        <el-input
          v-model="queryParams.keyWord"
          placeholder="请输入关键字"
          clearable
          maxlength="50"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table
      border
      :data="tableList"
      v-loading="loading"
      ref="multipleTable"
      row-key="id"
    >
      <el-table-column label="序号" width="60" align="center" type="index">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工程名称" align="center" prop="proName" show-overflow-tooltip />
      <el-table-column label="装卸类型" align="center" width="100" prop="type" show-overflow-tooltip />
      <el-table-column label="车牌号" align="center" width="150" prop="carCode" show-overflow-tooltip />
      <el-table-column label="联系人" align="center" width="150" prop="linkMan" show-overflow-tooltip />
      <el-table-column label="联系电话" align="center" width="160" prop="phone" show-overflow-tooltip />
      <el-table-column label="日期" align="center" width="150" prop="reserveDate" show-overflow-tooltip />
      <el-table-column label="排号" align="center" width="120" prop="sort" show-overflow-tooltip />
      <el-table-column label="操作" align="center" width="170">
        <template slot-scope="{ row }">
          <el-button size="mini" v-if="row.sort===null" type="success" @click="handleView(row)">排号</el-button>
          <el-button size="mini" v-if="row.type==='装' && row.sort!==null" type="warning" @click="dialogView(row)">装货单</el-button>
          <el-button size="mini" v-if="row.type==='卸' && row.sort!==null" type="warning" @click="dialogView(row)">卸货单</el-button>
          <el-button size="mini" type="danger" @click="delClick(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="total"
      v-show="total > 0"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 审核排号 -->
    <el-dialog title="审核排号" :visible.sync="viewDialogVisible" width="500px" append-to-body>
      <el-form :model="viewForm" label-width="60px" class="view-dialog-form">
        <el-form-item label="排号：">
          <el-input
            style="display: inline-block; width: auto; vertical-align: middle;"
            v-model="viewForm.sort"
            @input="handleSortInput"
            placeholder="请输入排号"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="viewDialogVisible = false">关闭</el-button>
        <!-- 使用 type="primary" 并通过 style 设置背景颜色 -->
        <el-button
          type="primary"
          @click="confirmAction"
          style="background-color: #409EFF; color: white;"
        >
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="卸货单预览"
      :visible.sync="previewDialogVisible"
      width="50%"
      top="5vh">
      <div class="preview-container">
        <!-- 图片预览 -->
        <img
          v-if="currentPreviewImage"
          :src="currentPreviewImage"
          alt="卸货单"
          style="max-width: 100%; border: 1px solid #eee;">

        <!-- 卸货单内容 - 添加print-content类 -->
        <div
          id="unloading-ticket"
          class="unloading-ticket print-content"
          v-else>
          <h2 style="text-align: center;">卸车排位号</h2>
          <table class="ticket-table" style="margin: 0 auto;">
            <tr>
              <td width="100" style="text-align: center;">号类</td>
              <td style="font-weight: bold; font-size: 25px; text-align: center;">{{ currentTicketData.sort }}</td>
            </tr>
            <tr>
              <td style="text-align: center;">工程名称</td>
              <td style="text-align: center;">{{ currentTicketData.proName }}</td>
            </tr>
            <tr>
              <td style="text-align: center;">车牌号码</td>
              <td style="font-weight: bold; font-size: 25px; text-align: center;">{{ currentTicketData.carCode }}</td>
            </tr>
            <tr>
              <td style="text-align: center;">联系人</td>
              <td style="font-weight: bold; font-size: 25px; text-align: center;">{{ currentTicketData.linkMan }}</td>
            </tr>
            <tr>
              <td style="text-align: center;">联系电话</td>
              <td style="font-weight: bold; font-size: 25px; text-align: center;">{{ currentTicketData.phone }}</td>
            </tr>
            <tr>
              <td style="text-align: center;">日期</td>
              <td style="text-align: center;">{{ currentTicketData.reserveDate }}</td>
            </tr>
            <tr>
              <td style="text-align: center;">签字</td>
              <td style="height: 50px; text-align: center;">
                <img :src="currentTicketData.signUrl" style="width: 100px;height: 100px;transform: rotate(-90deg);max-width: 100%;"  alt="">
              </td>
            </tr>
          </table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="printTicket">打印</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="装货单预览"
      :visible.sync="loadingDialogVisible"
      width="50%"
      top="5vh">
      <div class="preview-container">
        <!-- 图片预览 -->
        <img
          v-if="currentPreviewImage"
          :src="currentPreviewImage"
          alt="装货单"
          style="max-width: 100%; border: 1px solid #eee;">

        <!-- 卸货单内容 - 添加print-content类 -->
        <div
          id="loading-ticket"
          class="loading-ticket loading-print-content"
          v-else>
          <h2 style="text-align: center;">装货排位号</h2>
          <table class="loading-ticket-table" style="margin: 0 auto;">
            <tr>
              <td width="100" style="text-align: center;">号类</td>
              <td style="font-weight: bold; font-size: 25px; text-align: center;">{{ loadingTicketData.sort }}</td>
            </tr>
            <tr>
              <td style="text-align: center;">工程名称</td>
              <td style="text-align: center;">{{ loadingTicketData.proName }}</td>
            </tr>
            <tr>
              <td style="text-align: center;">车牌号码</td>
              <td style="font-weight: bold; font-size: 25px; text-align: center;">{{ loadingTicketData.carCode }}</td>
            </tr>
            <tr>
              <td style="text-align: center;">联系人</td>
              <td style="font-weight: bold; font-size: 25px; text-align: center;">{{ loadingTicketData.linkMan }}</td>
            </tr>
            <tr>
              <td style="text-align: center;">联系号码</td>
              <td style="font-weight: bold; font-size: 25px; text-align: center;">{{ loadingTicketData.phone }}</td>
            </tr>
            <tr>
              <td style="text-align: center;">日期</td>
              <td style="text-align: center;">{{ loadingTicketData.reserveDate }}</td>
            </tr>
            <tr>
              <td style="text-align: center;">签字</td>
              <td style="height: 50px; text-align: center;">
                <img :src="loadingTicketData.signUrl" style="width: 100px;height: 100px;transform: rotate(-90deg);max-width: 100%;"  alt="">
              </td>
            </tr>
          </table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="loadingDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="loadingPrintTicket">打印</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {
  getAuthDetail,
  getLeasePublishAuthList,
  getTeamList,
  sumbitAuthData,
  uploadIdCard,
  getAuthInfo, getHandlingOrderList, uploadSort, getSort, delHandlingOrder
} from '@/api/materialsStation/auth'
import { getToken } from '@/utils/auth'
import { validateIdCard } from '@/utils/bonus'
import vueEasyPrint from 'vue-easy-print'
import {acceptInnerVerifyer} from "@/api/purchase/goodsAccept";
import printJS from "print-js";
import {delType} from "@/api/system/dict/type";
export default {
  components: { vueEasyPrint },
  name: 'HandlingOrder',
  data() {
    return {
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      total: 0, //                总条数
      loading: false, //           遮罩层
      showSearch: true, //        显示搜索条件
      tableList: [], //            列表数据源
      queryTime: [], //           日期数据源
      selectList: [], //          列表选中数据
      url: null,
      fileName: null,
      // 列表查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        time: null,
        keyWord: '',
        taskStatus: '',
        startTime: '',
        endTime: ''
      },
      //新增弹窗
      open: false,
      dialogForm: {
        maTypeName: null,
        maTypeId: null,
        typeId: null,
        supplierId: null,
        qrNum: null,
        remark: null
      },

      fileList: [],
      uploadList: [],

      titles: '',
      authDialogVisible: false,
      currentRow: null, // 当前操作的行数据

      materialReceivers: [],
      viewDialogVisible: false,
      viewForm: {
        sort: null,
        id: null // 新增 id 字段
      },
      pdfPreviewVisible: false,
      pdfViewerUrl: '',
      isEditMode: false, // 是否处于编辑模式
      dialogTitle: '新增授权', // 弹窗标题
      isBatchMode: false, // 是否批量模式
      selectedItems: [], // 批量授权时选择的申请单
      authorizeVisible: false, // 授权委托书
      authorizeData: {
        leaseUnit: '',
        leaseProject: '',
        detailsList: [],
        userName: '',
        createTime: ''
      },

      previewDialogVisible: false,
      currentPreviewImage: null,
      currentTicketData: {
        timeType:'',
        type: '',
        proName: '',
        carCode: '',
        linkMan: '',
        phone: '',
        reserveDate: '',
        sort:'',
        signUrl:''
      },
      loadingDialogVisible: false,
      loadingTicketData: {
        timeType:'',
        type: '',
        proName: '',
        carCode: '',
        linkMan: '',
        phone: '',
        reserveDate: '',
        sort:'',
        signUrl:''
      },
      timeType:'',
      sort:''
    }
  },
  created() {
    this.getList()
  },
  watch: {
    // 监听弹框显示状态
    authDialogVisible(newVal) {
      if (!newVal) {
        // 弹框关闭时重置上传相关状态
        this.resetUploadState()
        this.$refs.authFormRef.resetFields() // 重置表单
      }
    }
  },
  methods: {
    // 限制输入框只能输入数字
    handleSortInput(value) {
      // this.viewForm.sort = value.replace(/[^0-9]/g, '');
    },
    // 是否可用勾选框
    selectable(row) {
      return row.authId === null
    },

    // 获取列表
    getList() {
      this.loading = true
      const params = {
        keyWord: this.queryParams.keyWord,
        startTime: this.queryParams.startTime,
        endTime: this.queryParams.endTime,
        pageSize: this.queryParams.pageSize,
        pageNum: this.queryParams.pageNum
      }
      getHandlingOrderList(params).then(response => {
        this.tableList = response.data.rows
        this.total = response.data.total
        this.loading = false

        // 重置选择状态 - 确保清理干净
        this.$nextTick(() => {
          this.selectList = []
          this.selectedItems = [] // 确保清空
          this.$refs.multipleTable.clearSelection()
        })
      })
    },
    confirmAction() {
      const param = {
        id: this.viewForm.id,
        sort: this.viewForm.sort,
        timeType: this.timeType
      }
      uploadSort(param).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess(response.msg)
          this.viewDialogVisible = false
          this.getList() // 刷新列表
        } else {
          this.$modal.msgError(response.msg)
        }
      })
    },
    // 搜索按钮
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置按钮
    resetQuery() {
      this.queryParams.time = []
      this.resetForm('queryForm')
      this.queryParams.keyWord = ''
      this.queryParams.taskStatus = ''
      this.handleQuery()
    },

    // 表单验证（统一验证）
    handleView(row) {
      this.viewDialogVisible = true
      this.viewForm.sort = row.sort // 可选：将原排号显示在输入框中
      this.viewForm.id = row.id // 保存当前行的 id
    },
    // 转换时间格式
    formatTime(time) {
      const date = new Date(time)
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      return `${year} 年 ${month} 月 ${day} 日`
    },
    dialogView(row) {
      if (row.type === '卸' && row.sort !== null) {
        this.showUnloadingTicket(row);
      } else if (row.type === '装' && row.sort !== null) {
        this.showLoadingTicket(row);
      }
    },
    delClick(row){
      const params = {
        id: row.id
      }
      this.$modal
        .confirm('是否确认删除所选择的数据项？')
        .then(function () {
          return delHandlingOrder(params)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
// 显示卸货单
    showUnloadingTicket(row) {
      this.currentTicketData = {
        timeType:row.timeType,
        sort: row.sort,
        proName: row.proName,
        carCode: row.carCode,
        linkMan: row.linkMan,
        phone: row.phone,
        reserveDate: row.reserveDate,
        signUrl: row.signUrl,
      };
      this.currentPreviewImage = null; // 确保不使用图片预览
      this.previewDialogVisible = true;
    },
    printTicket() {
      // 创建一个打印专用的样式
      const printStyle = `
    .unloading-ticket {
      width: 100%;
      max-width: 500px;
      margin: 0 auto;
      padding: 20px;
    }
    .ticket-table {
      width: 100%;
      border-collapse: collapse;
    }
    .ticket-table td {
      padding: 10px;
      border: 1px solid #ddd;
    }
    .ticket-table td:first-child {
      font-weight: bold;
      background-color: #f5f5f5;
    }
    h2 {
      text-align: center;
    }
  `;

      printJS({
        printable: 'unloading-ticket',
        type: 'html',
        targetStyles: ['*'],
        scanStyles: false,
        style: printStyle,
        onPrintDialogClose: () => {
          // 打印对话框关闭后的回调
        }
      });
    },
    // 显示装货单
    showLoadingTicket(row) {
      this.loadingTicketData = {
        timeType:row.timeType,
        sort: row.sort,
        proName: row.proName,
        carCode: row.carCode,
        linkMan: row.linkMan,
        phone: row.phone,
        reserveDate: row.reserveDate,
        signUrl: row.signUrl,
      };
      this.currentPreviewImage = null; // 确保不使用图片预览
      this.loadingDialogVisible = true;
    },
    loadingPrintTicket() {
      // 创建一个打印专用的样式
      const printStyle = `
    .loading-ticket {
      width: 100%;
      max-width: 500px;
      margin: 0 auto;
      padding: 20px;
      border: 2px solid #ddd;
      background-color: #fff;
    }
    .loading-ticket-table {
      width: 100%;
      border-collapse: collapse;
    }
    .loading-ticket-table td {
      padding: 10px;
      border: 2px solid #ddd;
      text-align: left;
    }
    .loading-ticket-table td:first-child {
      font-weight: bold;
      background-color: #f5f5f5;
      width: 100px;
    }
    h2 {
      text-align: center;
      margin-bottom: 20px;
    }
  `;

      printJS({
        printable: 'loading-ticket',
        type: 'html',
        targetStyles: ['*'],
        scanStyles: false,
        style: printStyle,
        onPrintDialogClose: () => {
          // 打印对话框关闭后的回调
        }
      });
    },
  }
}
</script>
<style lang="scss" scoped>

/* 统一显示和打印的样式 */
.unloading-ticket {
  width: 100%;
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ddd;
  background-color: #fff;

  h2 {
    text-align: center;
    margin-bottom: 20px;
  }
}

.ticket-table {
  width: 100%;
  border-collapse: collapse;

  td {
    padding: 10px;
    border: 1px solid #ddd;
    text-align: left;

    &:first-child {
      font-weight: bold;
      background-color: #f5f5f5;
      width: 100px;
    }
  }
}

/* 打印专用样式 */
@media print {
  body * {
    visibility: hidden;
  }

  .unloading-ticket,
  .unloading-ticket * {
    visibility: visible;
  }

  .unloading-ticket {
    position: absolute;
    left: 0;
    top: 0;
    width: auto;
    max-width: none;
    border: none;
    padding: 0;
    margin: 0;
  }
}


.loading-ticket {
  width: 100%;
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ddd;
  background-color: #fff;

  h2 {
    text-align: center;
    margin-bottom: 20px;
  }
}
.loading-ticket-table {
  width: 100%;
  border-collapse: collapse;

  td {
    padding: 10px;
    border: 1px solid #ddd;
    text-align: left;

    &:first-child {
      font-weight: bold;
      background-color: #f5f5f5;
      width: 100px;
    }
  }
}
/* 打印专用样式 */
@media print {
  body * {
    visibility: hidden;
  }

  .loading-ticket,
  .loading-ticket * {
    visibility: visible;
  }

  .loading-ticket {
    position: absolute;
    left: 0;
    top: 0;
    width: auto;
    max-width: none;
    border: none;
    padding: 0;
    margin: 0;
  }
}



/* 批量授权标签容器 */
.selected-items-container {
  max-height: 150px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  padding: 10px;
  border-radius: 4px;
  margin-top: 10px;
}

/* 批量授权标签 */
.selected-item-tag {
  margin-right: 10px;
  margin-bottom: 5px;
}

/* 批量授权标题 */
.batch-title {
  font-size: 16px;
  margin-bottom: 10px;
  color: #333;
}
.el-upload.is-disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

/* 弹窗标题样式 */
.el-dialog__header {
  border-bottom: 1px solid #eee;
}

.el-dialog__title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}
/* 查看对话框样式 */
.view-dialog-form {
  margin-left: 0px;
}

.id-photo-view {
  display: flex;
  justify-content: center;
  align-items: center;
}

.file-size {
  color: #999;
  font-size: 12px;
  margin-left: 5px;
}

/* 图片预览模态框样式 */
.image-preview-modal {
  width: 80%;
  max-width: 800px;
}

.image-preview-modal .el-message-box__content {
  display: flex;
  justify-content: center;
  padding: 20px;
}

/* PDF预览对话框样式 */
.pdf-preview-dialog .el-dialog__body {
  padding: 10px;
}

/* 调整表单整体左移 */
.auth-dialog-form {
  margin-left: 0px;
}

/* 调整领料人列表标签位置 */
.receiver-list-label {
  margin-left: -10px;
}

/* 调整表格位置 */
.receiver-table-item {
  margin-left: -30px;
}

/* 表格样式调整 */
.receiver-table {
  margin-left: -30px;
  width: calc(100% + 30px);
}

.id-photo-upload {
  display: flex;
  justify-content: space-around;
  gap: 10px;
}

.upload-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.upload-status {
  color: #67c23a;
  font-weight: bold;
  font-size: 14px;
}
.uploadImg {
  padding-top: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.boxCode {
  margin-top: 10px;
  padding-bottom: 20px;
  font-size: 18px;
}
::v-deep.el-table .fixed-width .el-button--mini {
  width: 60px !important;
  margin-bottom: 10px;
}
</style>
