<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="作业单位" prop="workUnit">
        <el-input
          v-model="queryParams.workUnit"
          placeholder="请输入作业单位"
          clearable
          size="small"
          @input="handleQuery"
        />
      </el-form-item>
      <el-form-item label="作业区域" prop="workArea">
        <el-select v-model="queryParams.workArea" placeholder="请选择作业区域" clearable size="small" @change="handleQuery" filterable>
          <el-option
            v-for="dict in workAreaOptions"
            :key="dict.id"
            :label="dict"
            :value="dict"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="楼层位置" prop="floorLocation">
        <el-select v-model="queryParams.floorLocation" placeholder="请选择楼层位置" clearable size="small"
                   @change="handleQuery" filterable>
          <el-option
            v-for="dict in floorLocationOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="parseInt(dict.dictValue)"
          ></el-option>
        </el-select>
      </el-form-item>
<!--      <el-form-item label="预约作业日期" prop="workStartTime">-->
<!--        <el-date-picker clearable size="small" style="width: 200px"-->
<!--                        v-model="queryParams.workStartTime"-->
<!--                        type="date"-->
<!--                        value-format="yyyy-MM-dd"-->
<!--                        placeholder="选择预约作业日期"-->
<!--                        @input="handleQuery">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->

      <el-form-item label="预约作业日期" prop="workStartTime">
        <el-date-picker
          v-model="chooseDate"
          @change="handleQuery"
          type="daterange"
          style="width: 508px"
          align="right"
          unlink-panels
          :range-separator="$t('至')"
          :start-placeholder="$t('开始日期')"
          :end-placeholder="$t('结束日期')"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="创建时间" prop="createdate">
        <el-date-picker clearable size="small" style="width: 200px"
                        v-model="queryParams.createdate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择创建时间"
                        @input="handleQuery">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="作业类型" prop="workType">
        <el-select v-model="queryParams.workType" placeholder="请选择作业类型" clearable size="small" @change="handleQuery" filterable>
          <el-option
            v-for="dict in workTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="parseInt(dict.dictValue)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="票号" prop="allNo">
        <el-input
          v-model="queryParams.allNo"
          placeholder="请输入联系人"
          clearable
          size="small"
          @input="handleQuery"
        />
      </el-form-item>
      <el-form-item label="票盒" prop="tag">
        <el-select v-model="queryParams.tag" clearable filterable @change="handleQuery" placeholder="请选择票盒">
          <el-option-group
            v-for="group in tagOptions"
            :key="group.tag"
            :label="group.tag">
            <el-option
              v-for="item in group.children"
              :key="item.tag"
              :label="item.tag"
              :value="item.tag">
            </el-option>
          </el-option-group>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" 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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['invoice:bookingworkticket:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['invoice:bookingworkticket:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExportToday"
          v-hasPermi="['invoice:bookingworkticket:export']"
        >导出当日
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-copy-document"
          size="mini"
          :disabled="multiple"
          @click="tickedStatis()"
        >作业票统计
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExportZb"
          v-hasPermi="['invoice:bookingworkticket:export']"
        >值班导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExportNowAll"
          v-hasPermi="['invoice:bookingworkticket:export']"
        >导出当前所有
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="cancelQuery"></right-toolbar>
    </el-row>

    <u-table v-loading="loading" :data="bookingworkticketList" ref="multipleTable"
              :span-method="mergeMethod" @selection-change="handleSelectionChange" :height="clientHeight" border
             use-virtual :row-key="row => { return row.id }"
             showBodyOverflow="title"
             :data-changes-scroll-top =false
              >
      <u-table-column type="selection" width="55" align="center" :reserve-selection="true"/>
      <u-table-column label="作业单位" align="center" prop="bookingworkticket.workUnit" width="80"
                       :show-overflow-tooltip="true"/>
      <u-table-column label="作业区域单元" align="center" prop="bookingworkticket.workArea" width="100"
                       :show-overflow-tooltip="true"/>
      <u-table-column label="楼层位置" align="center" prop="bookingworkticket.floorLocation" width="80"
                       :formatter="floorLocationFormat"/>
      <u-table-column label="用户主管" align="center" prop="bookingworkticket.userMgName" width="60"
                       :show-overflow-tooltip="true"/>
      <u-table-column label=" 预约作业日期" align="center" prop="workStartTime" width="90">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.bookingworkticket.workStartTime, '{y}-{m}-{d}') }}</span>
        </template>
      </u-table-column>
      <u-table-column :label="$t('新票/续票')" align="center" prop="xpxp" width="60">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.xpxp == 10" size="small" type="success">新票</el-tag>
          <el-tag v-else-if="scope.row.xpxp == 12" size="small" type="info">续票</el-tag>
        </template>
      </u-table-column>
      <u-table-column label="作业类型" align="center" prop="workType" width="120" :show-overflow-tooltip="true" :formatter="workTypeFormat"/>

      <u-table-column label="作业内容描述" align="center" prop="workDescription" width="160" :show-overflow-tooltip="true"/>
      <u-table-column label="作业人员数" align="center" prop="workPeopleNumber" width="70" :show-overflow-tooltip="true"/>
      <u-table-column label="预计作业时间" align="center" prop="estimateWorktime" width="70" :show-overflow-tooltip="true"/>
      <u-table-column label="联系人" align="center" prop="bookingworkticket.contact" width="80"
                       :show-overflow-tooltip="true"/>
      <u-table-column label="联系方式" align="center" prop="bookingworkticket.phonenumber" width="100"
                       :show-overflow-tooltip="true"/>
      <u-table-column label="创建时间" align="center" prop="bookingworkticket.createdate" width="90">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.bookingworkticket.createdate, '{y}-{m}-{d}') }}</span>
        </template>
      </u-table-column>
      <u-table-column label="预约状态" align="center" prop="bookingworkticket.status" :formatter="statusFormat" />
      <u-table-column label="票号" align="center" width="40" prop="reservationNumber">
        <template slot-scope="scope">
          <span>  {{ scope.row.reservationNumber }}</span>
          <el-button
            v-if="scope.row.bookingworkticket.status== 3"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="association(scope.row)"
            v-hasPermi="['invoice:bookingworkticket:edit','invoice:bookingworkticket:query']"
          ></el-button>
        </template>
      </u-table-column>
      <u-table-column label="危害工作许可证号" align="center" prop="whgzxkzh" width="100" :show-overflow-tooltip="true"/>
      <u-table-column label="动火作业许可证号" align="center" prop="dhzyxkzh" width="100" :show-overflow-tooltip="true"/>
      <u-table-column label="火票级别" align="center" prop="hpjb" width="50" :formatter="hpjbFormat"/>
      <u-table-column label="限制空间许可证号" align="center" prop="xzkjxkzh" width="100" :show-overflow-tooltip="true"/>
      <u-table-column label="盲板作业许可证号" align="center" prop="mbzyxkzh" width="100" :show-overflow-tooltip="true"/>
      <u-table-column label="高处作业许可证号" align="center" prop="gczyxkzh" width="100" :show-overflow-tooltip="true"/>
      <u-table-column label="高处作业级别" align="center" prop="gczyjb" width="50" :formatter="gczyjbFormat"/>
      <u-table-column label="延期许可证号" align="center" prop="yqxkzh" width="100" :show-overflow-tooltip="true"/>
      <u-table-column label="票盒" align="center" prop="tag" width="60" :show-overflow-tooltip="true"/>
      <u-table-column label="开票" align="center" fixed="right" width="90">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.addStatus == 1" size="small" type="success">已开票</el-tag>
          <el-button
            v-else-if="scope.row.bookingworkticket.status== 3"
            size="mini"
            type="text"
            @click="tickedStatis(scope.row)"
          > <span>开票</span>
          </el-button>
        </template>

      </u-table-column>
      <u-table-column label="续票预约" fixed="right" align="center" width="90">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.bookingworkticket.status== 3"
            size="mini"
            type="text"
            @click="handleXp(scope.row)"
          > <span>续票预约</span>
          </el-button>
        </template>
      </u-table-column>
      <u-table-column label="操作" align="center" fixed="right" width="100" class-name="small-padding ">
<!--        <template slot-scope="scope">-->
<!--          <el-button-->
<!--            v-if="scope.row.bookingworkticket.status== 3 && scope.row.xpxp == 10"-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-view"-->
<!--            @click="billSee(scope.row)"-->
<!--          > 票据预览-->
<!--          </el-button>-->
<!--          <el-button-->
<!--            v-if="scope.row.bookingworkticket.status== 3 && scope.row.xpxp == 10"-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-download"-->
<!--            @click="handleDownload(scope.row)"-->
<!--          >下载申请单-->
<!--          </el-button>-->

<!--        </template>-->
        <template slot-scope="scope">
          <el-button @click="handleCancel(scope.row)" v-if="scope.row.bookingworkticket.status== 3" type="text" size="small" style="margin-right: 6px">作废</el-button>
          <el-dropdown v-if="scope.row.bookingworkticket.status== 3 && scope.row.xpxp == 10" size="mini" @command="(command) => handleCommand(command, scope.row)">
      <span class="el-dropdown-link">
        <el-button
          type="text"
          size="mini"
        >更多<i class="el-icon-arrow-down"></i></el-button>
      </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="billSee">票据预览</el-dropdown-item>
              <el-dropdown-item  command="handleDownload" >下载申请单</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </u-table-column>
    </u-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :page-sizes="[20,100,200,500]"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改预约作业票台账对话框 -->
    <el-dialog  :close-on-click-modal="false"  :title="title" :visible.sync="open" width="1200px" append-to-bod :before-close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="承包商" prop="workUnit">
              <el-input v-model="form.workUnit" placeholder="请输入作业单位" :disabled="edit"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="作业区域" prop="workArea">
              <el-select v-model="form.workArea" placeholder="请选择作业区域">
                <el-option
                  v-for="dict in workAreaOptions"
                  :key="dict.id"
                  :label="dict"
                  :value="dict"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="归属部门" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
          </el-col>
          <el-col :span="12">
            <el-form-item label="楼层位置" prop="floorLocation">
              <el-select v-model="form.floorLocation" multiple placeholder="请选择楼层位置">
                <el-option
                  v-for="dict in floorLocationOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="parseInt(dict.dictValue)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="作业时间" prop="workStartTime">
              <el-date-picker clearable size="small" style="width: 190px"
                              v-model="form.workStartTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择作业时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="作业结束" prop="workEndTime">-->
          <!--              <el-date-picker clearable size="small" style="width: 190px"-->
          <!--                              v-model="form.workEndTime"-->
          <!--                              type="date"-->
          <!--                              value-format="yyyy-MM-dd"-->
          <!--                              placeholder="选择作业结束时间">-->
          <!--              </el-date-picker>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户单位" prop="userUnit">
              <el-select v-model="form.userUnit" placeholder="请选择用户单位"
                         @change="checkCategoryPromotionUpdate(form.userUnit)">
                <el-option
                  v-for="dict in userUnitOptions"
                  :key="dict.userUnit"
                  :label="dict.userUnit"
                  :value="dict.userUnit"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户主管" prop="userMg">
              <el-select v-model="form.userMg" placeholder="请先选择好用户单位">
                <el-option
                  v-for="dict in userMgOptions"
                  :key="dict.userId"
                  :label="dict.nickName"
                  :value="dict.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-card v-for="(ruleForm, index) in ruleForm" :key="index" shadow="always">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
          <el-row>
            <el-col :span="18">
              <el-form-item label="作业内容描述" prop="workDescription">
                <el-input type="text" v-model="ruleForm.workDescription"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-button type="success" plain @click.prevent="addDomain(ruleForm)" style="float: right;">拷贝</el-button>
            </el-col>
            <el-col :span="3">
              <el-button type="info" plain @click.prevent="removeDomain(ruleForm)" style="float: right;">删除</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="作业类型" prop="workType">
                <el-select v-model="ruleForm.workType" placeholder="请选择作业类型" multiple clearable size="small">
                  <el-option
                    v-for="dict in workTypeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="parseInt(dict.dictValue)"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="作业人数" prop="workPeopleNumber">
                <el-input-number v-model="ruleForm.workPeopleNumber" :min="1" :max="999" ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="预计作业时间" prop="estimateWorktime">
                <el-input-number v-model="ruleForm.estimateWorktime" :min="1" :max="999" ></el-input-number>H
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-button @click="resetForm1()">重置</el-button>
      <el-button @click="add">新增一条</el-button>
      <el-button @click="reduce" :disabled="flag">移除一条</el-button>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 报告附件对话框 -->
    <el-dialog  :close-on-click-modal="false"  v-loading="loadingFlash" element-loading-background="rgba(0,0,0,0.2)" v-dialogDrag :title="pdf.title"
               :visible.sync="pdf.open" width="1300px" height="800px" :center="true" append-to-body>
      <div style="margin-top: -60px;float: right;margin-right: 40px;">
        <el-button size="mini" type="text" @click="openPdf">新页面预览</el-button>
      </div>
      <div style="margin-top: -30px">
        <iframe id="iFrame" class="iframe-html" :src="pdf.pdfUrl" frameborder="0" width="100%" height="700px"
                v-if="ppt"></iframe>
      </div>
    </el-dialog>
    <!-- 预约续票 -->
    <el-dialog  :close-on-click-modal="false"  title="预约续票" :visible.sync="xpVisible" width="30%" center>
      <el-form :model="xpForm" :rules="rulesXp" ref="xpForm" label-width="60px">
        <el-form-item label="作业时间" prop="workStartTime">
          <el-date-picker clearable size="small" style="width: 190px"
                          v-model="xpForm.workStartTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择作业时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="延期许可证号" prop="yqxkzh">
          <el-input v-model="xpForm.yqxkzh" placeholder="请输入延期许可证号"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitXp">确 定</el-button>
        <el-button @click="xpVisible=false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog  :close-on-click-modal="false"  title="关联票号" :visible.sync="guanlianVisible" width="30%" center>
      <el-form :model="licenseForm" :rules="licenseRules" ref="licenseForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="危害工作许可证号" prop="whgzxkzh">
          <el-input v-model="licenseForm.whgzxkzh" placeholder="请输入危害工作许可证号"/>
        </el-form-item>
        <el-form-item label="动火作业许可证号" prop="dhzyxkzh">
          <el-input v-model="licenseForm.dhzyxkzh" placeholder="请输入动火作业许可证号"/>
        </el-form-item>
        <el-form-item label="火票级别" prop="hpjb">
          <el-select v-model="licenseForm.hpjb" clearable placeholder="请选择火票级别">
            <el-option
              v-for="dict in hpjbOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="限制空间许可证号" prop="xzkjxkzh">
          <el-input v-model="licenseForm.xzkjxkzh" placeholder="请输入限制空间许可证号"/>
        </el-form-item>
        <el-form-item label="盲板作业许可证号" prop="mbzyxkzh">
          <el-input v-model="licenseForm.mbzyxkzh" placeholder="请输入盲板作业许可证号"/>
        </el-form-item>
        <el-form-item label="高处作业许可证号" prop="gczyxkzh">
          <el-input v-model="licenseForm.gczyxkzh" placeholder="请输入高处作业许可证号"/>
        </el-form-item>
        <el-form-item label="高处作业级别" prop="gczyjb">
          <el-select v-model="licenseForm.gczyjb" clearable placeholder="请选择高处作业级别">
            <el-option
              v-for="dict in gczyjbOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="票盒" prop="tag">
          <el-select v-model="licenseForm.tag" clearable filterable placeholder="请选择票盒">
            <el-option-group
              v-for="group in tagOptions"
              :key="group.tag"
              :label="group.tag">
              <el-option
                v-for="item in group.children"
                :key="item.tag"
                :label="item.tag"
                :value="item.tag">
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-hasPermi="['invoice:bookingworkticket:edit']" @click="submitassociation">确 定
        </el-button>
        <el-button @click="guanlianVisible=false">取 消</el-button>
      </div>
    </el-dialog>
    <add-approve v-if="addAprroveVisible" ref="addApprove" @refreshDataList="getList"></add-approve>
  </div>
</template>

<script>
import {
  listBookingworkticket,
  getBookingworkticket,
  delBookingworkticket,
  addBookingworkticket,
  updateBookingworkticket,
  exportBookingworkticket,
  exportBookingworkticketZb,
  exportBookingworkticketNowAll,
  cancelBookingworkticket,
  importTemplate,
  seeBookingworkticket,
  assion
} from "@/api/invoice/bookingworkticket";
import {
  listWorkcontent,
  getWorkcontent,
  delWorkcontent,
  addWorkcontent,
  updateWorkcontent,
  exportWorkcontent,
  getWorkcontentBybookingticketId
} from "@/api/invoice/workcontent";
import {listDevice, getDevice, delDevice, updateDevice, exportDevice, selectDevice} from "@/api/invoice/device";
import {listTagAll} from "@/api/invoice/tag";
import {
  listUnit,
  getUnit,
  delUnit,
  addUnit,
  updateUnit,
  exportUnit,
  getUserByUnit,
  getAllUserUnit
} from "@/api/invoice/unit";
import {
  getUserByUserName
} from "@/api/system/user";
import {
  listJobticket,
  getJobticket,
  delJobticket,
  addJobticket,
  updateJobticket,
  exportJobticket,
  batchAddJobticket
} from "@/api/ehs/jobticket";
import {treeselect} from "@/api/system/dept";
import {getToken} from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import AddApprove from "../approveinvoice/index"
import {addInvoice} from "@/api/invoice/invoice";
import base from "@/assets/js/base";

export default {
  name: "Bookingworkticket",
  components: {Treeselect, AddApprove},
  data() {
    var checkHpjb = (rule, value, callback) => {
      if (this.licenseForm.dhzyxkzh && !value) {
        callback(new Error('火票级别不能为空'));
      } else {
        callback();
      }
    }
    var checkGczyjb = (rule, value, callback) => {
      if (this.licenseForm.gczyxkzh && !value) {
        callback(new Error('高处级别不能为空'));
      } else {
        callback();
      }
    }
    return {
      //关联票号
      associationParams: {},
      reservationNumber: "",
      guanlianVisible: false,
      xpVisible: false,
      //禁用
      edit: true,
      ppt: false,
      pptView: false,
      imgs: [],
      tInvoiceWorkcontentList: [],
      addAprroveVisible: false,
      hisAprroveVisible: false,
      // 遮罩层
      loading: true,
      loadingFlash: false,
      // 选中数组
      ids: [],
      dataListSelections: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 预约作业票台账表格数据
      bookingworkticketList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      clientHeight: 300,
      // 状态字典
      statusOptions: [],
      // 作业区域字典
      workAreaOptions: [],
      // 楼层字典
      floorLocationOptions: [],
      // 用户单位字典
      userUnitOptions: [],
      // 用户主管字典
      userMgOptions: [],
      // 作业类型字典
      workTypeOptions: [],
      // 风险等级字典
      riskLevelOptions: [],
      // 火票级别字典
      hpjbOptions: [],
      // 高处作业级别字典
      gczyjbOptions: [],
      tagOptions: [],
      // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/invoice/bookingworkticket/importData"
      },
      pdf: {
        title: '',
        pdfUrl: '',
        numPages: null,
        open: false,
        pageNum: 1,
        pageTotalNum: 1,
        loadedRatio: 0,
      },
      //日期快速选择
      pickerOptions: {
        shortcuts: [{
          text: this.$t('最近一周'),
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: this.$t('最近一个月'),
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: this.$t('最近三个月'),
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      //日期选择器
      chooseDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        workUnit: null,
        workArea: null,
        unitNumber: null,
        floorLocation: null,
        workStartTime: null,
        workEndTime: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        contact: null,
        phonenumber: null,
        status: null,
        deptId: null,
        userMg: null,
        userUnit: null,
        allNo: null,
        tag: null
      },
      //申请的参数
      approveForm: {},
      // 表单参数
      form: {},
      //预约票参数
      ruleForm: [{}],
      //许可证表单参数
      licenseForm: {},
      //续票参数
      xpForm: {},
      flag: true,
      // 表单校验
      rules: {
        workArea: [
          {required: true, message: "作业区域不能为空", trigger: "blur"}
        ],
        floorLocation: [
          {required: true, message: "楼层位置不能为空", trigger: "blur"}
        ],
        workStartTime: [
          {required: true, message: "作业时间不能为空", trigger: "blur"}
        ],
        workEndTime: [
          {required: true, message: "作业结束时间不能为空", trigger: "blur"}
        ],
        userMg: [
          {required: true, message: "用户主管不能为空", trigger: "blur"}
        ],
        userUnit: [
          {required: true, message: "用户单位不能为空", trigger: "blur"}
        ],
        workType: [
          {required: true, message: "作业类型不能为空", trigger: "blur"}
        ],
        workDescription: [
          {required: true, message: "作业内容不能为空", trigger: "change"},
          {validator: this.checkSame, trigger: 'blur'}
        ],
        workPeopleNumber: [
          {required: true, message: "作业人数不能为空", trigger: "change"}
        ],
        estimateWorktime: [
          {required: true, message: "预计作业时间不能为空", trigger: "change"}
        ],
      },
      // 表单校验
      rulesXp: {
        workStartTime: [
          {required: true, message: "作业时间不能为空", trigger: "blur"}
        ],
      },
      licenseRules: {
        hpjb: [
          { validator: checkHpjb, trigger: 'blur' }
        ],
        gczyjb: [
          { validator: checkGczyjb, trigger: 'blur' }
        ],
        tag: [
          {required: true, message: "票盒不能为空", trigger: "blur"}
        ],
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },

  },
  created() {
    //设置表格高度对应屏幕高度
    this.$nextTick(() => {
      this.clientHeight = document.body.clientHeight - 250

    })
    this.getNowFormatDate()
    this.getList()
    this.getTreeselect()
    this.getTagList()
    //初始化作业区域、 初始化用户单位下拉框
    this.getDeviceup();
    this.getDicts("booking_work_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("book_floor_location").then(response => {
      this.floorLocationOptions = response.data;
    });
    // this.getDicts("book_user_unit").then(response => {
    //   this.userUnitOptions = response.data;
    // });
    getAllUserUnit({}).then(response => {
      this.userUnitOptions = response.data;
      console.log(this.userUnitOptions)
    });
    this.getDicts("book_work_type").then(response => {
      this.workTypeOptions = response.data;
    });
    this.getDicts("book_risk_level").then(response => {
      this.riskLevelOptions = response.data;
    });
    this.getDicts("HPJB").then(response => {
      this.hpjbOptions = response.data;
    });
    this.getDicts("GCZYJB").then(response => {
      this.gczyjbOptions = response.data;
    });

  },
  methods: {
    // 自定义校验重复数据规则
    checkSame(rule, value, callback) {
      // rule 对应使用bargainMoney自定义验证的 对象
      // value 对应使用bargainMoney自定义验证的 数值
      // callback 回调函数
      let arr = []
      this.ruleForm.forEach(item => {

        arr.push(item.workDescription)
      })
      for (var i = 0; i < arr.length; i++) {
        for (var j = i + 1; j < arr.length; j++) {
          if (arr[i] == arr[j]) {
            return callback(new Error("作业内容已重复，请重新填写"));
          } else {
            return callback();
          }
        }
        return callback();
      }

    },
    //得到行key
    getRowKey(row) {
      return row.guid;
    },
    //作业票统计
    tickedStatis(row) {
      console.log(row)
      var rows = this.dataListSelections.map(item => {
        return item
      })
      let putData = row? [row] : rows
      for (let i = 0; i <putData.length ; i++) {
        if (putData[i].bookingworkticket.status != 3) {
          this.$alert(this.$t('只能提交状态为已完成的预约票'), this.$t('提示'), {
            type: 'warning'
          })
          return
        }
      }
      batchAddJobticket(putData).then(response => {
        this.msgSuccess(this.$t(response.msg));
       this.getList()
      });
    },
    //根据用户单位 查询对应选择的用户主管  根据用户单位 字段 查找对应的多个主管 返回 Sysuser的集合(id,name)
    checkCategoryPromotion(oneId) {
      getUserByUnit(oneId).then(response => {
        //     this.form.userMg=null;
        this.userMgOptions = response.data;
        //   let arr=  response.data.userIds.split(',');
      });
    },
    //修改用户单位时，级联的用户主管下拉数据应清空，否则会造成用户修改了用户单位，但未重新选择相应的用户主管
    checkCategoryPromotionUpdate(oneId) {
      this.form.userMg = null;
      getUserByUnit(oneId).then(response => {
        //     this.form.userMg=null;
        this.userMgOptions = response.data;
        //   let arr=  response.data.userIds.split(',');
      });
    },

    //得到作业区域下拉框
    getDeviceup() {
      const queryForm = {
        pageNum: 1,
        pageSize: 99999,
        devName: null,
        workArea: null,
        regionalHead: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        deptId: null,
        remarks: null
      };
      selectDevice(queryForm).then(response => {
        this.workAreaOptions = response.data
      });
    },
    //得到票盒下拉框
    getTagList() {
      listTagAll().then(response => {
        this.tagOptions = response
      });
    },
    addAprrove(row) {
      this.reset();

      var rows = row ? [row] : this.bookingworkticketList.map(item => {
        return item
      })
      for (let i = 0; i < rows.length; i++) {
        if (rows[i].status === 3) {
          this.$alert(this.$t('预约已确认，无法重复申请'), this.$t('提示'), {
            type: 'warning'
          })
          return
        } else if (rows[i].status != 0 && rows[i].status != 5) {
          this.$alert(this.$t('预约正在申请中，无法重复申请'), this.$t('提示'), {
            type: 'warning'
          })
          return
        }
      }
      this.$nextTick(() => {
        this.approveForm.invoiceId = row.bookingticketId;
        this.approveForm.userSupId = row.bookingworkticket.userMg;

        addInvoice(this.approveForm).then(response => {
          this.msgSuccess(this.$t('预约成功'));
        })
      })
      this.addAprroveVisible = true
    },
    //拷贝
    addDomain(domain) {
      let arr = {}
      arr.workType = domain.workType;
      arr.workDescription = domain.workDescription;
      arr.riskLevel = domain.riskLevel;
      arr.workPeopleNumber = domain.workPeopleNumber;
      arr.estimateWorktime = domain.estimateWorktime;
      this.ruleForm.push(
        arr
      );
      this.flags()
    },
    //删除自身
    removeDomain(item) {
      //如果子类大于1  可点击删除按钮
      if (this.ruleForm.length > 1) {
        var index = this.ruleForm.indexOf(item)
        if (index !== -1) {
          this.ruleForm.splice(index, 1)
        }
      }
      this.flags()
    },
// 表单添加一行
    add() {
      var arr = {}
      this.ruleForm.push(arr)
      this.flags()
    },
    // 表单减少一行
    reduce() {

      this.ruleForm.length = this.ruleForm.length - 1
      this.flags()
    },
    // 判断数组长度
    flags() {
      //如果小于1则自动补一栏 如果大于5则提示
      if (this.ruleForm.length < 2) {
        this.flag = true
      } else if (this.ruleForm.length < 1) {
        this.ruleForm.push({});
      } else if (this.ruleForm.length > 5) {
        this.ruleForm.length = this.ruleForm.length - 1;
        this.msgSuccess("最多只能添加5条相关作业内容,若需要请重新预约");
      } else {
        //先赋值为true再赋为false, 不然会没反应
        this.flag = true
        this.flag = false
      }
    },
    //时间
    getNowFormatDate() {
      var date = new Date();
      var seperator1 = "-";
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate;
      // this.queryParams.createdate=currentdate
      return currentdate;
    },
    // 重置方法
    resetForm1() {
      this.ruleForm = [{}]
    },

    /** 查询预约作业票台账列表 */
    getList() {
      this.loading = true;
      let oldParams = JSON.stringify(this.queryParams)
      listBookingworkticket(this.queryParams).then(response => {
        //解决防止出现结果和搜索不一致的问题
        if (oldParams != JSON.stringify(this.queryParams)){
          this.loading = false;
          return
        }
          this.bookingworkticketList = response.rows;
          this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 预约票状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.bookingworkticket.status);
    },
    // 工作区域字典翻译
    workAreaFormat(row, column) {
      return this.selectDictLabel(this.workAreaOptions, row.bookingworkticket.workArea);
    },
    // 楼层位置字典翻译
    floorLocationFormat(row, column) {

      return this.selectDictLabels(this.floorLocationOptions, row.bookingworkticket.floorLocation);
    },
    // 用户主管字典翻译
    userMgFormat(row, column) {
      return this.selectDictLabel(this.userMgOptions, row.userMg);
    },
    // 用户单位字典翻译
    userUnitFormat(row, column) {
      return this.selectDictLabel(this.userUnitOptions, row.userUnit);
    },
    // 作业类型字典翻译
    workTypeFormat(row, column) {
      return this.selectDictLabels(this.workTypeOptions, row.workType);
    },
    // 火票级别字典翻译
    hpjbFormat(row, column) {
      return this.selectDictLabel(this.hpjbOptions, row.hpjb);
    },
    // 高处作业级别字典翻译
    gczyjbFormat(row, column) {
      return this.selectDictLabel(this.gczyjbOptions, row.gczyjb);
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.$nextTick(() => {
        this.$refs.ruleForm[0].resetFields();
        if (this.$refs.ruleForm[1] != null) {
          this.$refs.ruleForm[1].resetFields();
        }
        if (this.$refs.ruleForm[2] != null) {
          this.$refs.ruleForm[2].resetFields();
        }
        if (this.$refs.ruleForm[3] != null) {
          this.$refs.ruleForm[3].resetFields();
        }
        if (this.$refs.ruleForm[4] != null) {
          this.$refs.ruleForm[4].resetFields();
        }
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        workUnit: null,
        workArea: null,
        unitNumber: null,
        floorLocation: null,
        workStartTime: null,
        workEndTime: null,
        delFlag: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        contact: null,
        phonenumber: null,
        status: 0,
        deptId: null,
        userMg: null,
        userUnit: null
      };
      this.resetForm("form");
      this.userMgOptions=[];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.chooseDate == null) {
        this.chooseDate = []
      }
      this.queryParams.startDate = this.chooseDate[0]
      this.queryParams.endDate = this.chooseDate[1]
     this.getList(JSON.stringify(this.queryParams));
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.createdate = null
      this.handleQuery();
    },
    //取消搜索
    cancelQuery() {
      this.resetForm("queryForm");
      this.getNowFormatDate()
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.bookingticketId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.dataListSelections = selection
      // console.log(selection)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.resetForm1();
      var names = this.$store.state.user.name
      //查询用户归属的部门名称
      getUserByUserName(names).then(response => {
        this.form.workUnit = response.data.dept.deptName;
        //默认是用户自己的部门
        this.form.deptId = response.data.dept.deptId;
      });
      this.open = true;
      this.title = "添加预约作业票台账";

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.bookingticketId || this.ids
      getBookingworkticket(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改预约作业票台账";
        this.ruleForm = response.data.tInvoiceWorkcontentList
        //  回显用户主管
        this.checkCategoryPromotion(this.form.userUnit);
        //  console.log(row.floorLocation)  将后台的字符串数组重新转换为el-select要的数组格式
        let arr = row.bookingworkticket.floorLocation.split(",")
        let st = []
        // 将字符串数组的每一项转换成Number，生成一个新的数组
        for (var arrInt in arr) {
          st.push(parseInt(arr[arrInt]))
        }
        this.form.floorLocation = st
        //作业类型也要多选 同楼层
        for (let j = 0; j < this.ruleForm.length; j++) {
          let arr1 = this.ruleForm[j].workType.split(",")
          let st1 = []
          // 将字符串数组的每一项转换成Number，生成一个新的数组
          for (var arrInt in arr1) {
            st1.push(parseInt(arr1[arrInt]))
          }
          this.ruleForm[j].workType = st1
        }
        this.ruleForm.length = response.data.tInvoiceWorkcontentList.length
      });
    },
    //校验
    getFormPromise(formDone) {
      return new Promise(resolve => {
        formDone.validate(res => {
          resolve(res);
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      let arr = []
      const basicForm = this.$refs.form;
      arr.push(basicForm)
      const genForm = this.$refs.ruleForm[0];
      arr.push(genForm)
      if (this.$refs.ruleForm[1] != null) {
        const genForm1 = this.$refs.ruleForm[1];
        arr.push(genForm1)
      }
      if (this.$refs.ruleForm[2] != null) {
        const genForm2 = this.$refs.ruleForm[2];
        arr.push(genForm2)
      }
      if (this.$refs.ruleForm[3] != null) {
        const genForm3 = this.$refs.ruleForm[3];
        arr.push(genForm3)
      }
      if (this.$refs.ruleForm[4] != null) {
        const genForm4 = this.$refs.ruleForm[4];
        arr.push(genForm4)
      }
      //多重校验
      Promise.all(arr.map(this.getFormPromise)).then(res => {
        const validateResult = res.every(item => !!item);
        console.log(validateResult)
        if (validateResult) {
          if (this.form.id != null) {
            this.form.tInvoiceWorkcontentList = this.ruleForm
            this.form.floorLocation = this.form.floorLocation.join(',')
            for (let b = 0; b < this.ruleForm.length; b++) {
              this.ruleForm[b].workType = this.ruleForm[b].workType.join(',')
            }
            updateBookingworkticket(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.tInvoiceWorkcontentList = this.ruleForm
            this.form.floorLocation = this.form.floorLocation.join(',')
            for (let b = 0; b < this.ruleForm.length; b++) {
              this.ruleForm[b].workType = this.ruleForm[b].workType.join(',')
            }
            addBookingworkticket(this.form).then(response => {
              if (response.code == 500) {
                return
              }
              // console.log(this.form)
              //   console.log(this.ruleForm)
              this.approveForm.invoiceId = response.data
              this.approveForm.userSupId = this.form.userMg
              addInvoice(this.approveForm).then(response => {
                this.msgSuccess("已提交申请");
                this.open = false;
                this.getList();
                this.resetForm1();
                this.cancel();
              })
            });

          }
        } else {
          this.msgError("表单校验未通过，每项申请内容都必填");
        }
      });

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.bookingticketId || this.ids;
      this.$confirm('是否确认删除?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delBookingworkticket(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 删除按钮操作 */
    handleCancel(row) {
      const id = row.bookingticketId;
      this.$confirm('是否确认作废?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return cancelBookingworkticket(id);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      queryParams.status = null
      this.$confirm('是否确认导出所有预约作业票台账数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportBookingworkticket(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    /** 值班导出按钮操作 */
    handleExportZb() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有预约作业票台账数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportBookingworkticketZb(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },

    /** 当前所有导出按钮操作 */
    handleExportNowAll() {
      const queryParams = this.queryParams;
      queryParams.status = 7
      this.$confirm('是否确认导出预约作业票台账数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportBookingworkticket(queryParams);
      }).then(response => {
        queryParams.status = null
        this.download(response.msg);
      })
    },
    /** 导出按钮操作 */
    handleExportToday() {
      const queryParams = {};
      queryParams.workStartTime = this.getNowFormatDate()
      this.$confirm('是否确认导出?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportBookingworkticket(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    // 预约续票
    handleXp(row) {
      this.xpForm = base.deepClone(row)
      if(!this.xpForm.yqxkzh) {
        this.xpForm.yqxkzh = 'V'
      }
      this.xpVisible = true
    },
    //提交预约续票
    submitXp() {
      this.$refs["xpForm"].validate(valid => {
        if (valid) {
          let newForm = {}
          newForm = this.xpForm.bookingworkticket
          newForm.tInvoiceWorkcontentList = []
          this.xpForm.bookingworkticket = null
          newForm.tInvoiceWorkcontentList[0] = this.xpForm
          newForm.workStartTime = this.xpForm.workStartTime
          newForm.tInvoiceWorkcontentList[0].xpxp = 12    //续票
          newForm.status = 0
          addBookingworkticket(newForm).then(response => {
            if (response.code == 500) {
              this.getList();
              this.xpVisible = false
              return
            }
            this.approveForm.invoiceId = response.data
            this.approveForm.userSupId = newForm.userMg
            addInvoice(this.approveForm).then(response => {
              this.msgSuccess("已提交申请");
              this.getList();
              this.xpVisible = false
            })
          });
        }
      })
    },
    //关联票号
    association(row) {
      this.guanlianVisible = true
      this.associationParams = row
      getWorkcontent(row.id).then(response => {
        this.licenseForm = response.data
      });
    },
    //提交票号
    submitassociation() {
      this.$refs["licenseForm"].validate(valid => {
        if (valid) {
          this.guanlianVisible = false
          let arr = []
          arr.push(this.licenseForm.whgzxkzh)
          arr.push(this.licenseForm.dhzyxkzh)
          arr.push(this.licenseForm.xzkjxkzh)
          arr.push(this.licenseForm.mbzyxkzh)
          arr.push(this.licenseForm.gczyxkzh)
          const putData = {}
          let num = 0
          arr.forEach(item => {
            if (item === null || item === '') {
              num = num + 1
            }
          })
          if (num < 5) {
            putData.id = this.associationParams.id
            putData.whgzxkzh = this.licenseForm.whgzxkzh
            putData.hpjb = this.licenseForm.hpjb
            putData.dhzyxkzh = this.licenseForm.dhzyxkzh
            putData.xzkjxkzh = this.licenseForm.xzkjxkzh
            putData.mbzyxkzh = this.licenseForm.mbzyxkzh
            putData.gczyxkzh = this.licenseForm.gczyxkzh
            putData.gczyjb = this.licenseForm.gczyjb
            putData.tag = this.licenseForm.tag
          } else {
            return this.msgError("请至少关联一张许可证号");
          }
          updateWorkcontent(putData).then(response => {
            this.getList()
          });
          assion(this.associationParams.bookingticketId).then(response => {

          });

          this.msgSuccess("请求成功");
        }
      })

    },
    //校验表单中作业内容是否重复

    //合并单元格
    mergeMethod({row, column, rowIndex, columnIndex}) {
      // console.log(row)
      if ([1, 2, 3, 4, 5, 10, 11, 12, 13, 27].includes(columnIndex)) {
        const _row = this.setTable(this.bookingworkticketList).merge[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    },
    //单元格整理
    setTable(tableData) {
      //    console.log(tableData)
      let spanArr = [],
        concat = 0;
      tableData.forEach((item, index) => {
        if (index === 0) {
          spanArr.push(1);
        } else {
          if (item.bookingticketId === tableData[index - 1].bookingticketId) {
            //第一列需合并相同内容的判断条件
            spanArr[concat] += 1;
            spanArr.push(0);
          } else {
            spanArr.push(1);
            concat = index;
          }
        }
      });
      // this.$nextTick(() => {
      //   this.$refs.multipleTable.doLayout();
      //
      //   // table加ref="multipleTable" 表格不会错位 不对齐
      // });
      return {
        merge: spanArr
      };
    },
    //票据预览的
    billSee(row) {
      //office预览
      console.log(row.bookingworkticket.filename)
      this.loadingFlash = true
      this.pdf.open = true
      this.pdf.title = row.bookingworkticket.filename
      this.pdf.pdfUrl = ""

      this.ppt = true
      //如果是PDF等直接可以打开的就不调接口，否则调用接口
      if (row.bookingworkticket.filename.endsWith('pdf')) {
        this.pdf.pdfUrl = process.env.VUE_APP_BASE_API + '/pdf/web/viewer.html?file=' + process.env.VUE_APP_BASE_API + row.fileUrl
        this.loadingFlash = false
      } else {
        const formatDate = new FormData();
        formatDate.append("filepath", row.bookingworkticket.filename)

        //调用文件预览api
        let res = this.officeConvert.bookConvertCommon(formatDate)


        //查看接受的全局方法的返回结果 console.log(res)
        //利用.then方法接受Promise对象
        res.then((result) => {
          //关闭加载中
          this.loadingFlash = false

          if (result.msg.includes("csv")) {
            this.pdf.pdfUrl = process.env.VUE_APP_BASE_API + result.data
            this.$alert(result.msg, this.$t('检查乱码'), {dangerouslyUseHTMLString: true});
            //    this.$message({message: result.msg, center: true,type:'warning',  offset:400, });

          } else if (result.msg.includes("不存在")) {
            //文件不存在时提示
            this.pdf.pdfUrl = ""
            this.$alert(result.msg, this.$t('预览失败'), {dangerouslyUseHTMLString: true});
            //    this.$message({message: result.msg, center: true,type:'warning',  offset:400, });
            this.pdf.open = false
          } else if (result.msg.includes("不支持此格式")) {

            this.pdf.pdfUrl = ""
            this.$alert(result.msg, this.$t('预览失败'), {dangerouslyUseHTMLString: true});
            //    this.$message({message: result.msg, center: true,type:'warning',  offset:400, });
            this.pdf.open = false
          } else {
            //成功时直接给地址
            this.pdf.pdfUrl = process.env.VUE_APP_BASE_API + result.data
            console.log(this.pdf.pdfUrl)
          }
        }).catch(result => {

          //请求失败，关闭loading，pdf地址直接为为空，不显示
          this.pdf.pdfUrl = ""
          this.loadingFlash = false;

        })
      }

    },
    handleCommand(command,row) {
      if (command == 'billSee') {
        this.billSee(row)
      }else if (command == 'handleDownload') {
        this.handleDownload(row)
      }
    },
    //文件预览
    openPdf() {
      //ppt就跳路由预览，office就直接打开文件新页面
      const didi = {imgs: this.imgs}
      if (this.pptView == true && this.ppt == false) {
        let routeUrl = this.$router.resolve({
          path: "/cpms/index.html#/pptyulan",
          query: didi
        });
        window.open("/cpms/index.html#/pptyulan?id=" + this.pdf.pdfUrl, '_blank')
        console.log(this.imgs)
      } else {
        window.open(this.pdf.pdfUrl)
      }
    },
    // 文件下载处理
    handleDownload(row) {
      console.log(row)
      var name = row.bookingworkticket.filename;
      var url = row.bookingworkticket.filename;
      var suffix = url.substring(url.lastIndexOf("."), url.length);
      console.log(url)
      const a = document.createElement('a')
      a.setAttribute('download', name)
      a.setAttribute('target', '_blank')
      a.setAttribute('href', process.env.VUE_APP_BASE_API + url)
      a.click()
    },

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

</style>

