<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-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</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" prop="material" show-overflow-tooltip />
      <el-table-column label="车牌号" align="center" width="300" prop="carCode" show-overflow-tooltip />
     <el-table-column label="领料单号" align="center" width="200" prop="code" show-overflow-tooltip />
      <el-table-column label="日期" align="center" width="200" prop="addDate" show-overflow-tooltip />
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="操作" align="center" width="280">
        <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">
          <div id="passId" style="margin: 20px;padding: 40px 60px; font-size: 18px;border: 2px solid #000; position: relative">
            <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="line-height: 1.96;margin-right: 65px;">
              <div>门卫:</div>
              <div>
                <span style="margin-left: 25px">现有&nbsp;</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: 40px 75px 15px; text-align: end">（公章）</div>
            <div style="text-align: end;margin-right: 50px;">{{ formatDate(exitForm.addDate) }}</div>
            <div>此证盖章有效</div>
            <div v-if="exitPermitDialogVisible" style="position: absolute; bottom: 39px; left: 460px">
              <canvas id="canvas" width="200" height="200"></canvas>
            </div>
            <!-- <div v-if="showImg" style="position: absolute; top: 126px; left: 460px">
              <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-item label="领料单号" prop="codeList">
          <el-select
            v-model="form.codeList"
            placeholder="请选择领料单号"
            style="width: 100%"
            clearable
            filterable
            multiple
            :filter-method="filterCodeList"
          >
            <el-option v-for="(item, index) in codeList" :key="index" :label="item.code" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注:" prop="remark">
          <el-input v-model="form.remark" type="textarea" maxlength="999" placeholder="请输入备注" style="width: 100%" clearable />
        </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, getCodeListApi} from '@/api/materialsStation/auth'
import chapter from "@/utils/chapter";
import vueEasyPrint from 'vue-easy-print'
import printJS from 'print-js'
import { formatTime } from '@/utils/bonus'

export default {
  components: { vueEasyPrint },
  name: 'ExitPermit',
  data() {
    const validateCodeList = (rule, value, callback) => {
      if ((!value || value.length === 0) && !this.form.remark) {
        callback(new Error('领料单号和备注至少填写一个'))
      } else {
        callback()
      }
    }
    const validateRemark = (rule, value, callback) => {
      if (!value && (!this.form.codeList || this.form.codeList.length === 0)) {
        callback(new Error('备注和领料单号至少填写一个'))
      } else {
        callback()
      }
    }
    return {
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      total: 0, // 总条数
      loading: false, // 遮罩层
      showSearch: true, // 显示搜索条件
      tableList: [], // 列表数据源
      queryTime: [], // 日期数据源
      selectList: [], // 列表选中数据
      // 列表查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        time: null,
        keyWord: '',
        taskStatus: '',
        startTime: null,
        endTime: null
      },
      loadingDialogVisible: false,
      currentPreviewImage: null,
      loadingTicketData: {
        sort: '',
        proName: '',
        carCode: '',
        linkMan: '',
        phone: '',
        reserveDate: '',
        signUrl: ''
      },
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        name: '',
        material: '',
        carCode: '',
        // 默认当前时间
        addDate: '',
        codeList: '',
        remark: '',
      },
      // 表单验证规则
      rules: {
        material: [
          { required: true, message: "物资不能为空", trigger: "blur" }
        ],
        carCode: [
          { required: true, message: "车牌号不能为空", trigger: "blur" }
        ],
        addDate: [
          { required: true, message: "日期不能为空", trigger: "change" }
        ],
        codeList: [{ validator: validateCodeList, trigger: 'change' }],
        remark: [{ validator: validateRemark, trigger: 'blur' }]
      },
      codeList: [],
      fullCodeList: [],
      filterTimer: null,
      isLoading: false,
      title: '新增装货单',
      exitPermitDialogVisible: false,
      exitPermitData: {
        name: '',
        material: '',
        date: ''
      },
      showImg: false,
      canvasImgUrl: '',
      exitForm:{}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 处理时间 2025-08-20 转为 2025年08月20日
    formatDate(date) {
      if (!date) return '';
      const options = { year: 'numeric', month: 'long', day: 'numeric' };
      return new Date(date).toLocaleDateString('zh-CN', options);
    },
    handleAdd() {
      this.resetForm();
      this.open = true;
      this.form.addDate = new Date().toISOString().slice(0, 10)
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
      this.getCodeList()
    },

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

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

    // 提交表单
    submitForm() {
      console.log('🚀 ~ this.form:', this.form)
      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.startTime,
        endTime: this.queryParams.endTime,
        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.queryParams.startTime = ''
      this.queryParams.endTime = ''
      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: A4; 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 = {}
    },
    async getCodeList() {
      try {
        const res = await getCodeListApi()
        const fullList = res.data || []

        // 保存完整数据，不直接展示
        this.fullCodeList = fullList

        // 默认展示前200条
        this.codeList = fullList.slice(0, 200)
      } catch (error) {
        console.log('🚀 ~ error:', error)
        
      }
    },
    filterCodeList(value) {
      clearTimeout(this.filterTimer)

      this.filterTimer = setTimeout(() => {
        if (!value) {
          this.codeList = this.fullCodeList.slice(0, 200)
          return
        }

        const v = value.toString().toLowerCase()

        this.codeList = this.fullCodeList
          .filter(item => {
            const codeStr = (item.code || '').toString().toLowerCase()
            return codeStr.includes(v)
          })
          .slice(0, 200)

      }, 500)
    },
    handleExport() {
        const currentTime = formatTime(new Date())
        
        this.download(
          '/material/back_apply_info/exportExitPermitList',
          { ...this.queryParams },
          `出门证_${currentTime}.xlsx`
        )
      },
  }
}
</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>
