<template>
  <div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item 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 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 prop="taskStatus">
        <el-select
          v-model="queryParams.taskStatus"
          placeholder="请选择状态"
          clearable
          filterable
          style="width: 240px"
        >
            <el-option label="未完成" value="1"></el-option>
            <el-option label="已终止" value="5"></el-option>
            <el-option label="已完成" value="3,4"></el-option>
        </el-select>
      </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-form-item>
    </el-form>

    <el-table v-loading="loading" :data="tableList" row-key="id"  border :max-height="650">
      <!-- <el-table-column type="selection" width="55" align="center" :selectable="selectable"/> -->
      <el-table-column align="center" label="序号" 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="createTime" width="100"/>
      <el-table-column label="业务联系单号" align="center" prop="code" width="110" />
      <el-table-column label="实施单位" align="center" prop="impUnitName" width="120px" :show-overflow-tooltip="true"/>
      <el-table-column label="申请项目部" align="center" prop="leaseUnit" width="150px"/>
      <el-table-column label="申请工程" align="center" prop="leaseProject" width="150px"/>
      <el-table-column label="类型名称" align="center" prop="maTypeNames" width="150px" :show-overflow-tooltip="true"/>
      <!-- <el-table-column label="领料人" align="center" prop="leasePerson" :show-overflow-tooltip="true"/> -->
      <el-table-column label="申请人"   align="center" prop="createBy" width="100" :show-overflow-tooltip="true"/>
      <el-table-column label="申请人电话" align="center" prop="phone" width="100px" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.phone? scope.row.phone.slice(0, 3) + '****' + scope.row.phone.slice(-4) : '' }}</span>
          </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="taskStatusName" :show-overflow-tooltip="true" width="80">
      </el-table-column>
      <el-table-column label="备注" align="center" width="100" prop="remark" :show-overflow-tooltip="true"/>
      <el-table-column label="是否授权" align="center" width="100" prop="remark" :show-overflow-tooltip="true">
        <template slot-scope="{ row }">
          <span>{{ row.isAuth == '0' ? '已授权' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" style="margin-bottom: 10px" type="normal"
            @click="handleView(scope.row)"
            >查看</el-button>
          <el-button size="mini" style="margin-bottom: 10px" type="success"
            v-if="scope.row.taskStatusName == '未完成'"
            @click="handleUpdate(scope.row)"
            >发布</el-button>
          <el-button size="mini" type="danger"
            v-if="scope.row.taskStatusName == '未完成'"
            @click="handleStop(scope.row)"
            >终止</el-button>
          <el-button  size="mini" type="warning" @click="handleLld(scope.row)">
            业务联单
          </el-button>
          <el-button v-if="scope.row.isAuth == '0'" size="mini" type="warning" @click="handleAuthorization(scope.row)">
            项目部授权委托书
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 弹框 -->
    <el-dialog title="业务联系单" :visible.sync="dialogVisible" width="46%">
      <div id="print-content1" style="padding: 0 30px">
        <span>发：</span>
        <!-- 标题 -->
        <div style="text-align: center; font-size: 16px">
          <h3 style="font-size: 25px">{{ dialogForm.impUnitName }}</h3>
          <h2 style="font-size: 35px; margin: 0 20%; display: flex; justify-content: space-around; align-items: center">
            <span>业</span>
            <span>务</span>
            <span>联</span>
            <span>系</span>
            <span>单</span>
          </h2>
        </div>
        <div
          style="display: flex; justify-content: space-between; align-items: center; line-height: 1.9; padding: 0 15px"
        >
          <span style="text-decoration: underline">{{ dialogForm.leaseProject }}</span>
          <span>
            <span style="text-decoration: underline">{{ dialogForm.code }}</span>
            号
          </span>
        </div>

        <!-- 内容 -->
        <div style="border: 3px solid #000; min-height: 800px; line-height: 1.9; position: relative">
          <div style="font-weight: 800; border-bottom: 1px solid #888; display: flex">
            <div style="width: 50%; padding-left: 10px">主送单位：{{ '技术质量科' }}</div>
            <div style="width: 50%; padding-left: 10px; border-left: 1px solid #888">
              抄送单位：{{ '物资管理中心' }}
            </div>
          </div>
          <!-- 内容 -->
          <div style="padding-left: 10px; min-height: 300px">
            <div>联系内容：</div>
            <div style="text-indent: 2em">
              因在
              <span style="font-weight: 800">
                {{ dialogForm.leaseProject }}
              </span>
              进行架线施工需要，现需领用以下工具器，详见附件一：
              <!-- dialogForm.maTypeNames -->
               <div>{{ dialogForm.maTypeNames }}</div>
            </div>
          </div>
          <!-- 说明 -->
          <div style="padding-left: 10px; min-height: 200px">
            <div>说明：</div>
            <div>领料单位：{{ dialogForm.leaseUnit }}</div>
            <!-- <div>项目部材料站站长联系人：{{ '徐青松' }} {{ '15234213324' }}</div> -->
            <div>项目部技术联系人：{{ dialogForm.createBy }}：{{ dialogForm.phone }}</div>
            <div>领取人员：{{ dialogForm.leasePerson }}：{{ dialogForm.phone }}</div>
          </div>

          <div
            style="
              width: 100%;
              display: flex;
              border-top: 1px solid #888;
              border-bottom: 1px solid #888;
              position: absolute;
              bottom: 90px;
              right: 0;
            "
          >
            <div style="width: 35%; padding-left: 10px">主管：{{ '' }}</div>
            <div style="width: 43%; padding-left: 10px; border-left: 1px solid #888">
              联系：{{ dialogForm.leasePerson }} {{ dialogForm.phone }}
            </div>
            <div style="width: 22%; padding-left: 10px; border-left: 1px solid #888">
              {{ handleTimeFormat(dialogForm.supplierTime) }}
            </div>
          </div>

          <div
            style="
              width: 100%;
              display: flex;
              border-top: 1px solid #888;
              border-bottom: 1px solid #888;
              position: absolute;
              bottom: 0;
              right: 0;
            "
          >
            <div style="width: 50%; padding-left: 10px">签复：</div>
            <div
              style="
                width: 50%;
                padding-left: 100px;
                border-left: 1px solid #888;
                display: flex;
                justify-content: space-around;
                align-items: center;
              "
            >
              <span>年</span>
              <span>月</span>
              <span>日</span>
            </div>
          </div>
        </div>

        <!-- 附件 -->
        <div style="margin-top: 100px">
          <div style="font-size: 20px; padding-left: 40px; line-height: 1.9">
            附件一：{{ dialogForm.leaseProject }}
            <span style="margin-left: 20px">{{ dialogForm.code }}</span>
            号附件
          </div>
          <div></div>
        </div>
        <table border="1" style="width: 100%; border-collapse: collapse">
          <thead>
            <tr>
              <th style="width: 55px; text-align: center">序号</th>
              <th
                v-for="(column, index) in dialogColumns"
                :key="column.prop"
                :style="{ width: column.width, textAlign: 'center' }"
              >
                {{ column.label }}
              </th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(row, rowIndex) in dialogList" :key="rowIndex">
              <td style="text-align: center">{{ rowIndex + 1 }}</td>
              <td v-for="(column, colIndex) in dialogColumns" :key="colIndex" :style="{ textAlign: 'center' }">
                {{ row[column.prop] }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="print">打 印</el-button>
        <el-button type="success" icon="el-icon-download" @click="downloadPDF">下载PDF</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
import {
  getListLeaseApply,
  applySend,
  applySendAll,
  applyEnd,
} from "@/api/lease/apply";
import {
  getLeasePublishList,
} from "@/api/leasePublish/index";
import {  getLeaseTask, getCodePDF } from '@/api/business/index'
import vueEasyPrint from "vue-easy-print";
import printJS from 'print-js';
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

export default {
  name: "Home",
  components: { vueEasyPrint },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,

      // 总条数
      total: 0,
      // 字典表格数据
      tableList: [],

      // 弹出层标题
      title: "",
      // 日期范围
      dateRange: [],
      statusDataRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        time: null, //申请时间
        keyWord: "",
        taskStatus: '1', //状态
        startTime: undefined,
        endTime: undefined
      },

      dialogVisible: false, // 弹框显示
      dialogForm: {
        proName: '', // 项目名称
        code: '' // 业务单号
      },
      dialogColumns: [
        { label: '名称', prop: 'maTypeName', width: '150px' },
        { label: '规格', prop: 'typeName', width: '150px' },
        { label: '单位', prop: 'unitName', width: '60px' },
        { label: '数量', prop: 'preNum', width: '60px' },
        { label: '备注', prop: 'remark', width: '' }
      ],
      dialogList: []
    };
  },
  created() {
    const end = new Date()
    let start = new Date()
    start.setMonth(start.getMonth() - 1)
    this.queryParams.startTime = this.format(start)
    this.queryParams.endTime = this.format(end)
    this.getList()
    console.log('时间', new Date(this.queryParams.startTime).getTime())
  },
  methods: {
    format(date) {
      const y = date.getFullYear()
      const m = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${y}-${m}-${day}`
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.sendTemp = [];
      this.ids = selection.map((item) => item.id);
      selection.forEach((item) => {
        this.sendTemp.push({ id: item.id, taskId: item.taskId });
      });
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    //是否可用勾选框
    selectable(row) {
      if (row.taskStatus == 1) {
        return true;
      } else {
        return false;
      }
    },
    getList() {
      this.loading = true;
      const params = {
        keyWord: this.queryParams.keyWord,
        status: this.queryParams.taskStatus,
        startTime: this.queryParams.startTime,
        endTime: this.queryParams.endTime,
        pageSize: this.queryParams.pageSize,
        pageNum: this.queryParams.pageNum,
      };
      getLeasePublishList(params).then((response) => {
        this.tableList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      const end = new Date()
      let start = new Date()
      start.setMonth(start.getMonth() - 1)
      this.queryParams.startTime = this.format(start)
      this.queryParams.endTime = this.format(end)
      this.resetForm("queryForm");
      this.queryParams.keyWord = "";
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$emit("addTools");
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.$emit("queryTools", row.taskId, row.id);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$emit("editTools", row.taskId, row.id);
    },

    // 表单重置
    reset() {
      this.form = {
        taskId: "",
        remark: "",
      };
      this.resetForm("form");
    },

    /** 导出按钮操作 */
    handleExport() {
      const formatTime = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}${month}${day}_${hours}${minutes}${seconds}`;
      };
      const params = {
        keyWord: this.queryParams.keyWord,
        status: this.queryParams.taskStatus,
        startTime: this.queryParams.startTime,
        endTime: this.queryParams.endTime,
        pageSize: this.queryParams.pageSize,
        pageNum: this.queryParams.pageNum,
      };

      const currentTime = formatTime(new Date());
      this.download(
        "/material/leaseTask/exportPublish",
         params,
        `领料申请发布_${currentTime}.xlsx`
      );
    },

    // 终止按钮
    handleStop(row) {
      const param = { id: row.id, taskId: row.taskId };
      this.$modal
        .confirm("是否确认终止所选择的数据项？")
        .then(function () {
          return applyEnd(param);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("终止成功");
        })
        .catch(() => {});
    },

    //发布按钮
    handleSend(row) {
      const param = { id: row.id, taskId: row.taskId };
      this.$modal
        .confirm("是否确认发布所选择的数据项？")
        .then(function () {
          return applySend(param);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("发布成功");
        })
        .catch(() => {});
    },

    handleSendAll() {
      if (this.ids.length == 0) {
        this.$alert("请至少勾选一个领料申请", "提示", {
          type: "warning",
          confirmButtonText: "确定",
        });
        return;
      } else {
        applySendAll(this.sendTemp).then((response) => {
          if (response.code == 200) {
            this.$modal.msgSuccess("发布成功");
          }
          this.getList();
        });
      }
    },

    // 获取弹框内容
    async handleLld(row) {
      console.log('🚀 ~ getDialogContent ~ row:', row.taskId)
      const loading = this.$loading({
        lock: true,
        text: '加载中...'
      })
      try {
        // 获取业务联系单
        const res = await getLeaseTask(row.id)
        console.log('🚀 ~ getDialogContent ~ res:', res)
        // 获取PDF
        // const PDFres = await getCodePDF(row.taskId)
        // console.log('🚀 ~ getDialogContent ~ res:', PDFres)
        this.dialogVisible = true
        this.dialogForm = {
          ...res.data.leaseApplyInfo,
          // pdfUrl: PDFres.data.url
        }
        this.dialogList = res.data.leaseApplyDetailsList
        loading.close()
      } catch (error) {
        console.log('🚀 ~ 获取弹框内容 ~ error:', error)
        loading.close()
      }
    },
    handleAuthorization (row) {
      // 打开新页面
      window.open(row.fileUrl, '_blank')
    },
    // 处理时间格式 2021-09-01 转换为 2021年09月01日
    handleTimeFormat(time) {
      if (time) {
        return time.replace(/-/g, '年').replace(/-/g, '月') + '日'
      }
      return ''
    },

    // 打印
    print() {
      printJS({
        printable: 'print-content1',
        type: 'html', //
        // targetStyles: ['*'], // 打印的元素样式
        scanStyles: false, // 是否扫描页面样式
        // css: [
        //   'https://unpkg.com/element-ui/lib/theme-chalk/index.css' // Element UI 的样式表
        // ],
        maxWidth: '1400'
        // 其他配置选项
      })
    },

    // 下载PDF
    async downloadPDF() {
      try {
        this.$modal.loading('正在生成PDF，请稍候...')

        // 获取要转换的DOM元素
        const element = document.getElementById('print-content1')
        if (!element) {
          this.$modal.closeLoading()
          this.$message.error('未找到要导出的内容')
          return
        }

        // 使用html2canvas将DOM元素转换为canvas
        const canvas = await html2canvas(element, {
          scale: 2, // 提高清晰度
          useCORS: true, // 允许加载跨域图片
          allowTaint: true,
          logging: false, // 关闭日志记录
          backgroundColor: '#ffffff'
        })

        // 创建PDF文档
        const pdf = new jsPDF('p', 'mm', 'a4')

        // 获取canvas的宽度和高度
        const imgWidth = 210 // A4纸的宽度(mm)
        const pageHeight = 297 // A4纸的高度(mm)
        const imgHeight = (canvas.height * imgWidth) / canvas.width

        let heightLeft = imgHeight
        let position = 0

        // 将canvas转换为图片
        const imgData = canvas.toDataURL('image/jpeg', 1.0)

        // 如果内容超过一页，需要分页
        if (heightLeft > pageHeight) {
          // 第一页
          pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight)
          heightLeft -= pageHeight

          // 添加后续页面
          while (heightLeft > 0) {
            position = heightLeft - imgHeight
            pdf.addPage()
            pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight)
            heightLeft -= pageHeight
          }
        } else {
          // 单页内容
          pdf.addImage(imgData, 'JPEG', 0, 0, imgWidth, imgHeight)
        }

        // 生成PDF文件名
        const fileName = `业务联系单_${this.dialogForm.code || '未命名'}_${new Date().getTime()}.pdf`

        // 下载PDF
        pdf.save(fileName)

        this.$modal.closeLoading()
        this.$message.success('PDF下载成功')
      } catch (error) {
        console.error('生成PDF失败:', error)
        this.$modal.closeLoading()
        this.$message.error('生成PDF失败，请稍后重试')
      }
    },

  },

};
</script>
<style lang="scss" scoped>

</style>
