<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="日期">
        <el-date-picker
          v-model="queryParams.time"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 240px"
        ></el-date-picker>
      </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-button type="success" icon="el-icon-plus" size="mini" @click="handleAdd">新增</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="90" 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" width="450" prop="material" show-overflow-tooltip />
      <el-table-column label="车牌号" align="center" width="280" prop="carCode" show-overflow-tooltip />
      <el-table-column label="姓名" align="center" width="275" prop="name" show-overflow-tooltip />
      <el-table-column label="日期" align="center" width="273" prop="addDate" show-overflow-tooltip />
      <el-table-column label="操作" align="center" width="270">
        <template slot-scope="{ row }">
          <el-button size="mini" type="success" @click="openPass(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 :visible.sync="exitPermitDialogVisible" width="800px" append-to-body @close="handleDialogClose">
      <el-form :model="exitForm" label-width="80px" size="small" inline @submit.native.prevent>
      </el-form>
      <div>
        <vue-easy-print tableShow ref="remarksPrintRefPass" style="padding: 0 20px; font-size: 18px">
          <div id="passId" style="padding: 0 20px; font-size: 18px">
            <div style="text-align: center; font-weight: 600; font-size: 36px; margin-bottom: 40px">
              出&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;门&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;证&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            </div>
            <div style="text-align: end">{{ passCode }}</div>
            <div style="line-height: 1.96">
              <div>门卫:</div>
              <div>
                <span style="margin-left: 25px">现有&nbsp;</span>
                <span style="min-width: 80px; border-bottom: 1px solid #000; padding: 0 5px">
                {{ exitForm.name }}
              </span>
                ,车牌号
                <span style="min-width: 80px; border-bottom: 1px solid #000; padding: 0 5px">
                {{ exitForm.carCode }}
              </span>
                &nbsp;,携带
                <span style="min-width: 80px; border-bottom: 1px solid #000; padding: 0 5px">{{ exitForm.material }}</span>
                &nbsp;出门，请予放行。
              </div>
            </div>
            <div style="margin: 60px 0 15px; text-align: end">（公章）</div>
            <div style="text-align: end">{{ exitForm.addDate }}</div>
            <div>此证盖章有效</div>
            <div v-if="exitPermitDialogVisible" style="position: absolute; top: 150px; left: 590px">
              <canvas id="canvas" width="200" height="200"></canvas>
            </div>
            <div v-if="showImg" style="position: absolute; top: 150px; left: 590px">
              <img :src="canvasImgUrl" width="200" height="200" />
            </div>
          </div>
        </vue-easy-print>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="printPass">打 印</el-button>
        <el-button @click="handleDialogClose">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="90px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入姓名"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item label="物资" prop="material">
          <el-input
            v-model="form.material"
            placeholder="请输入物资"
            maxlength="200"
          />
        </el-form-item>
        <el-form-item label="车牌号" prop="carCode">
          <el-input
            v-model="form.carCode"
            placeholder="请输入车牌号"
            maxlength="11"
          />
        </el-form-item>
        <el-form-item label="日期" prop="addDate">
          <el-date-picker
            v-model="form.addDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitForm"
          :loading="isLoading"
        >确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getExitPermitList, addExitPermit} from '@/api/materialsStation/auth'
import chapter from "@/utils/chapter";
import vueEasyPrint from 'vue-easy-print'
import printJS from 'print-js'

export default {
  components: { vueEasyPrint },
  name: 'IdCardUploadComponent',
  data() {
    return {
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      total: 0, // 总条数
      loading: false, // 遮罩层
      showSearch: true, // 显示搜索条件
      tableList: [], // 列表数据源
      queryTime: [], // 日期数据源
      selectList: [], // 列表选中数据
      // 列表查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        time: null,
        keyWord: '',
        taskStatus: ''
      },
      loadingDialogVisible: false,
      currentPreviewImage: null,
      loadingTicketData: {
        sort: '',
        proName: '',
        carCode: '',
        linkMan: '',
        phone: '',
        reserveDate: '',
        signUrl: ''
      },
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        name: '',
        material: '',
        carCode: '',
        addDate: ''
      },
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        material: [
          { required: true, message: "物资不能为空", trigger: "blur" }
        ],
        carCode: [
          { required: true, message: "车牌号不能为空", trigger: "blur" }
        ],
        addDate: [
          { required: true, message: "日期不能为空", trigger: "change" }
        ]
      },
      isLoading: false,
      title: '新增装货单',
      exitPermitDialogVisible: false,
      exitPermitData: {
        name: '',
        material: '',
        date: ''
      },
      showImg: false,
      canvasImgUrl: '',
      exitForm:{}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 新增
    handleAdd() {
      this.resetForm();
      this.open = true;
    },

    // 重置表单
    resetForm() {
      this.form = {
        linkMan: '',
        proName: '',
        carCode: '',
        reserveDate: ''
      };
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.resetForm();
    },

    // 提交表单
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.isLoading = true;
          addExitPermit(this.form).then(response => {
            this.$message.success("新增成功");
            this.open = false;
            this.getList();
          }).finally(() => {
            this.isLoading = false;
          });
        }
      });
    },

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

        // 重置选择状态
        this.$nextTick(() => {
          this.selectList = []
          this.$refs.multipleTable.clearSelection()
        })
      })
    },

    // 搜索按钮
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    // 重置按钮
    resetQuery() {
      this.queryParams.time = []
      this.resetForm('queryForm')
      this.queryParams.keyWord = ''
      this.queryParams.taskStatus = ''
      this.handleQuery()
    },
    // 出门证
    openPass(row) {
      this.exitPermitDialogVisible = true;
      this.showImg = false;
      this.exitForm = row;

      // 等待对话框完全打开
      this.$nextTick(() => {
        setTimeout(() => {
          chapter('出门证专用章', '安徽送变电工程有限公司机具（物流）分公司');
        }, 500);
      });
    },
    printPass() {
      this.showImg = true;

      // 确保canvas已完成渲染
      this.$nextTick(() => {
        const canvas = document.getElementById('canvas');
        if (canvas) {
          this.canvasImgUrl = canvas.toDataURL('image/png');

          // 再次等待DOM更新
          this.$nextTick(() => {
            // 使用printJS作为备选方案
            printJS({
              printable: 'passId',
              type: 'html',
              style: `
            @page { size: A5; margin: 0; }
            body { margin: 0.5cm; font-family: SimSun; }
            #passId { font-size: 18px; padding: 0 20px; }
          `,
              scanStyles: false
            });

            // 或者继续使用vue-easy-print
            // this.$refs.remarksPrintRefPass.print();

            this.showImg = false;
          });
        }
      });
    },
    handleDialogClose() {
      this.exitPermitDialogVisible = false
      this.showPass = false
      this.exitForm = {}
    },
  }
}
</script>

<style lang="scss" scoped>
.exit-permit {
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
  padding: 40px;
  font-family: "SimSun", "宋体", serif;
  background: white;
  border: 1px solid #ddd;

  .permit-title {
    font-size: 32px;
    font-weight: bold;
    text-align: center;
    margin-bottom: 50px;
    letter-spacing: 8px;
    color: #333;
  }

  .permit-content {
    .guard-section {
      margin-bottom: 25px;

      .guard-text {
        font-size: 20px;
        color: #333;
      }
    }

    .main-content {
      margin: 30px 0 60px 0;

      .main-text {
        font-size: 20px;
        line-height: 2.5;
        text-indent: 2em;
        color: #333;

        .underline {
          text-decoration: underline;
          padding: 0 8px;
          text-decoration-skip-ink: none;
          font-weight: 500;
        }
      }
    }
  }

  .permit-footer {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-top: 80px;

    .footer-left {
      .validity-text {
        font-size: 18px;
        color: #333;
        margin: 0;
      }
    }

    .footer-right {
      .stamp-container {
        display: flex;
        flex-direction: column;
        align-items: center;

        .stamp-circle {
          width: 120px;
          height: 120px;
          border: 3px solid #333;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-bottom: 15px;
          position: relative;

          .stamp-inner {
            text-align: center;

            .stamp-text-top {
              font-size: 14px;
              margin-bottom: 8px;
              color: #333;
            }

            .stamp-text-center {
              font-size: 13px;
              color: #333;
              line-height: 1.2;
            }
          }
        }

        .date-section {
          .date-text {
            font-size: 16px;
            color: #333;
            margin: 0;
            text-align: center;
          }
        }
      }
    }
  }
}

/* 打印样式优化 */
@media print {
  body * {
    visibility: hidden;
  }
  #passId,
  #passId * {
    visibility: visible;
  }
  #passId {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    margin: 0;
    padding: 20px;
  }
}

.dialog-footer {
  text-align: center;
  margin-top: 20px;

  .el-button {
    margin: 0 10px;
  }
}

.preview-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: #f5f5f5;
}
</style>
