<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-select v-model="queryParams.workUnit" placeholder="请选择作业单位" clearable size="small">
             <el-option
              v-for="dict in workUnitOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="parseInt(dict.dictValue)"
             ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="作业区域" prop="workArea">
        <el-select v-model="queryParams.workArea" placeholder="请选择作业区域" clearable size="small">
             <el-option
            v-for="dict in workAreaOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="parseInt(dict.dictValue)"
                 ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="楼层位置" prop="floorLocation">
        <el-select v-model="queryParams.floorLocation" placeholder="请选择楼层位置" clearable size="small">
            <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="选择 作业开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="作业结束时间" prop="workEndTime">
        <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.workEndTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择作业结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="联系人" prop="contact">
        <el-input
          v-model="queryParams.contact"
          placeholder="请输入联系人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入联系方式"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['invoice:bookingworkticket:edit']"
        >修改</el-button>
      </el-col>
        <el-col :span="1.5">
            <el-button
                    type="info"
                    icon="el-icon-upload2"
                    size="mini"
                    @click="handleImport"
                    v-hasPermi="['invoice:bookingworkticket:edit']"
            >导入</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>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bookingworkticketList" :span-method="mergeMethod"  @selection-change="handleSelectionChange" :height="clientHeight" border>

      <el-table-column label="作业单位" align="center" prop="bookingworkticket.workUnit" :formatter="workUnitFormat"/>
      <el-table-column label="作业区域单元" align="center" prop="bookingworkticket.workArea" :formatter="workAreaFormat"/>
      <el-table-column label="楼层位置" align="center" prop="bookingworkticket.floorLocation" :formatter="floorLocationFormat"/>
      <el-table-column label=" 作业开始时间" align="center" prop="workStartTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.bookingworkticket.workStartTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="作业结束时间" align="center" prop="workEndTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.bookingworkticket.workEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="作业类型" align="center" prop="workType" :formatter="workTypeFormat"/>
      <el-table-column label="风险等级" align="center" prop="riskLevel" :formatter="riskLevelFormat"/>
      <el-table-column label="作业内容描述" align="center" prop="workDescription" :show-overflow-tooltip="true"/>
      <el-table-column label="作业人员数" align="center" prop="workPeopleNumber" :show-overflow-tooltip="true"/>
      <el-table-column label="预计作业时间" align="center" prop="estimateWorktime" :show-overflow-tooltip="true"/>
      <el-table-column label="联系人" align="center" prop="bookingworkticket.contact" :show-overflow-tooltip="true"/>
      <el-table-column label="联系方式" align="center" prop="bookingworkticket.phonenumber" :show-overflow-tooltip="true"/>
      <el-table-column label="状态" align="center" prop="bookingworkticket.status" width="100" :formatter="statusFormat" />
      <el-table-column label="操作" align="center" fixed="right" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['invoice:bookingworkticket:edit']"
          >修改</el-button>
           <el-button
         v-if="scope.row.status== 0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDelete(scope.row)"
          >删除</el-button>
           <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="association(scope.row)"
             v-hasRole="['dbbz','admin']"
          >关联票号</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="billSee(scope.row)"
            > {{ $t('票据预览') }}</el-button>
          <el-button
            type="text"
            size="mini"
            @click="addAprrove(scope.row)"
          >{{ $t('预约开票申请') }}</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="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
       <el-row>
        <el-col :span="12">
            <el-form-item label="承包商" prop="workUnit">
          <el-select v-model="form.workUnit" placeholder="请选择作业单位">
            <el-option
              v-for="dict in workUnitOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="parseInt(dict.dictValue)"
             ></el-option>
          </el-select>
        </el-form-item>
          </el-col>
        <el-col :span="12">
        <el-form-item label="作业区域" prop="workArea">
          <el-select v-model="form.workArea" placeholder="请选择作业区域">
             <el-option
            v-for="dict in workAreaOptions"
            :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-col>
        <el-col :span="12">
        <el-form-item label="楼层位置" prop="floorLocation">
          <el-select v-model="form.floorLocation" 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="请选择用户单位">
             <el-option
            v-for="dict in userUnitOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="parseInt(dict.dictValue)"
             ></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.dictValue"
            :label="dict.dictLabel"
            :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
            </el-col>
      </el-row>
      </el-form>

            <el-form v-for="(ruleForm, index) in ruleForm" :key="index" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
    <el-divider><i class="el-icon-more" style="color:green;font-size:100%"></i><i class="el-icon-more" style="color:green;font-size:100%"></i> <span ><font color="green">关联的作业内容</font></span>
    <i class="el-icon-more" style="color:green;font-size:100%"></i><i class="el-icon-more" style="color:green;font-size:100%"></i></el-divider>
          <el-form-item label="作业内容描述" prop="workDescription">
            <el-input v-model="ruleForm.workDescription"></el-input>
          </el-form-item>
               <el-row>
        <el-col :span="12">
              <el-form-item label="作业类型" prop="workType">
        <el-select v-model="ruleForm.workType" placeholder="请选择作业类型" 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="12">
          <el-form-item label="风险等级" prop="riskLevel">
        <el-select v-model="ruleForm.riskLevel" placeholder="请选择风险等级" clearable size="small">
          <el-option
            v-for="dict in riskLevelOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="parseInt(dict.dictValue)"
          />
        </el-select>
      </el-form-item>
       </el-col>
      </el-row>
            <el-row>
        <el-col :span="12">
          <el-form-item label="作业人数" prop="workPeopleNumber">
            <el-input v-model="ruleForm.workPeopleNumber"></el-input>
          </el-form-item>
            </el-col>
        <el-col :span="12">
             <el-form-item label="预计作业时间" prop="estimateWorktime">
        <el-input v-model="ruleForm.estimateWorktime"  style="width: 190px"></el-input>
      </el-form-item>
       </el-col>
      </el-row>
        </el-form>

        <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   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">{{$t('新页面打开PDF')}}</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 :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
          <el-upload
                  ref="upload"
                  :limit="1"
                  accept=".xlsx, .xls"
                  :headers="upload.headers"
                  :action="upload.url + '?updateSupport=' + upload.updateSupport"
                  :disabled="upload.isUploading"
                  :on-progress="handleFileUploadProgress"
                  :on-success="handleFileSuccess"
                  :auto-upload="false"
                  drag
          >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                  将文件拖到此处，或
                  <em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                  <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
                  <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
              </div>
              <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
          </el-upload>
          <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitFileForm">确 定</el-button>
              <el-button @click="upload.open = 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, importTemplate, seeBookingworkticket} from "@/api/invoice/bookingworkticket";
import { listWorkcontent, getWorkcontent, delWorkcontent, addWorkcontent, updateWorkcontent, exportWorkcontent,getWorkcontentBybookingticketId} from "@/api/invoice/workcontent";
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"

export default {
  name: "Bookingworkticket",
  components: { Treeselect,AddApprove},
  data() {
    return {
      ppt:false,
      pptView:false,
      tInvoiceWorkcontentList:[],
        //作业内容表头
      tabletou:['作业类型','风险等级','作业内容描述','作业人员数','作业预计时间','监护人单位'],
      //用户名和承包商名
      username:"",
      addAprroveVisible: false,
      hisAprroveVisible: false,
      //bookticked关联ID
      btid:"",
      // 遮罩层
      loading: true,
      loadingFlash: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 预约作业票台账表格数据
      bookingworkticketList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      clientHeight:300,
        // 状态字典
      statusOptions: [],
      // 作业单位字典
      workUnitOptions: [],
      // 作业区域字典
      workAreaOptions: [],
      // 单元号字典
      unitNumberOptions: [],
      // 楼层字典
      floorLocationOptions: [],
       // 用户单位字典
      userUnitOptions: [],
       // 用户主管字典
      userMgOptions: [],
        // 作业类型字典
      workTypeOptions: [],
        // 风险等级字典
      riskLevelOptions: [],
        // 监护人单位字典
      guardianUnitOptions: [],

      // 是否显示弹出层
      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,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        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
      },
      // 表单参数
      form: {  },
       ruleForm: [{} ],
         flag: true,
      // 表单校验
      rules: {
        workUnit: [
          { required: true, message: "作业单位不能为空", trigger: "blur" }
        ],
         riskLevel: [
          { required: true, message: "风险等级不能为空", trigger: "blur" }
        ],
      }
    };
  },
  watch: {
        // 根据名称筛选部门树
        deptName(val) {
            this.$refs.tree.filter(val);
        }
   },
  created() {
      //设置表格高度对应屏幕高度
      this.$nextTick(() => {
          this.clientHeight = document.body.clientHeight -250
      })
           this.getList();
    this.getTreeselect();
      this.getDicts("booking_work_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("book_work_area").then(response => {
      this.workAreaOptions = response.data;
    });
    this.getDicts("book_unit_number").then(response => {
      this.unitNumberOptions = response.data;
    });
    this.getDicts("book_floor_location").then(response => {
      this.floorLocationOptions = response.data;
    });
    this.getDicts("book_user_mg").then(response => {
      this.userMgOptions = response.data;
    });
      this.getDicts("book_user_unit").then(response => {
      this.userUnitOptions = response.data;
    });
    this.getDicts("book_work_unit").then(response => {
      this.workUnitOptions = response.data;
    });
    this.getDicts("book_work_type").then(response => {
      this.workTypeOptions = response.data;
    });
    this.getDicts("book_risk_level").then(response => {
      this.riskLevelOptions = response.data;
    });
    this.getDicts("book_guardian_unit").then(response => {
      this.guardianUnitOptions = response.data;
    });

  },
  methods: {
    addAprrove(row) {
      var rows = row ? [row] : this.bookingworkticketList.map(item => {
        return item
      })
      for (let i = 0; i < rows.length; i++) {
        if (rows[i].status != 0) {
          this.$alert(this.$t('当前设备正在申请中，无法重复申请'), this.$t('提示'), {
            type: 'warning'
          })
          return
        }
      }
      this.$nextTick(() => {
        this.$refs.addApprove.init(rows)
      })
      this.addAprroveVisible = true
    },
// 表单添加一行
    add() {
      var arr = { }
      this.ruleForm.push(arr)
      this.flags()
    },
    // 表单减少一行
    reduce() {
        this.flags()
      this.ruleForm.length = this.ruleForm.length - 1

    },
    // 判断数组长度
    flags() {
      console.log(this.ruleForm.length)
      if (this.ruleForm.length <2) {
        this.flag = true
      } else {
      	//先赋值为true再赋为false, 不然会没反应
      this.flag=true
        this.flag = false
      }
    },
    // 重置方法
    resetForm1() {
      this.ruleForm = [{}]
    },

    /** 查询预约作业票台账列表 */
    getList() {
        this.loading = true;
       listBookingworkticket(this.queryParams).then(response => {
         this.bookingworkticketList=response.rows;
          for(let i = 0; i <  this.bookingworkticketList.length; i++) {
                  Object.assign(this.bookingworkticketList[i],{workUnit:this.bookingworkticketList[i].bookingworkticket.workUnit}
                  ,{workArea:this.bookingworkticketList[i].bookingworkticket.workArea}
                  ,{floorLocation:this.bookingworkticketList[i].bookingworkticket.floorLocation}
                  ,{contact:this.bookingworkticketList[i].bookingworkticket.contact}
                  ,{phonenumber:this.bookingworkticketList[i].bookingworkticket.phonenumber}
                  ,{status:this.bookingworkticketList[i].bookingworkticket.status});

          }
          console.log(this.bookingworkticketList)
       this.total = response.total;
        this.loading = false;
      });
    },
     /** 查询部门下拉树结构 */
     getTreeselect() {
          treeselect().then(response => {
              this.deptOptions = response.data;
          });
     },
 // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 字典翻译
    workUnitFormat(row, column) {
      return this.selectDictLabel(this.workUnitOptions, row.workUnit);
    },
    // 字典翻译
    workAreaFormat(row, column) {
      return this.selectDictLabel(this.workAreaOptions, row.bookingworkticket.workArea);
    },
    // 字典翻译
    unitNumberFormat(row, column) {
      return this.selectDictLabel(this.unitNumberOptions, row.unitNumber);
    },
    // 字典翻译
    floorLocationFormat(row, column) {
      return this.selectDictLabel(this.floorLocationOptions, row.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.selectDictLabel(this.workTypeOptions, row.workType);
    },
    // 字典翻译
    riskLevelFormat(row, column) {
      return this.selectDictLabel(this.riskLevelOptions, row.riskLevel);
    },
    // 字典翻译
    guardianUnitFormat(row, column) {
      return this.selectDictLabel(this.guardianUnitOptions, row.guardianUnit);
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    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");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.bookingticketId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.resetForm1();
        var roles =this.$store.state.user.roles
   this.open = true;
      this.title = "添加预约作业票台账";

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
   //   console.log(row)
      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.ruleForm.length=response.data.tInvoiceWorkcontentList.length
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
              this.form.tInvoiceWorkcontentList=this.ruleForm
            updateBookingworkticket(this.form).then(response => {

              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.tInvoiceWorkcontentList=this.ruleForm
            addBookingworkticket(this.form).then(response => {

           this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.resetForm1();
            });


          }
        }
      });

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.bookingticketId || this.ids;
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delBookingworkticket(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有预约作业票台账数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportBookingworkticket(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
      /** 导入按钮操作 */
      handleImport() {
          this.upload.title = "用户导入";
          this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
          importTemplate().then(response => {
              this.download(response.msg);
          });
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
          this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
          this.upload.open = false;
          this.upload.isUploading = false;
          this.$refs.upload.clearFiles();
          this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
          this.getList();
      },
      // 提交上传文件
      submitFileForm() {
          this.$refs.upload.submit();
      },
      //关联票号
      association(){
        console.log(this.$store.state.user)
        var userName = this.$store.state.user.roles;
        this.msgSuccess(userName);
      },
        //合并单元格
      mergeMethod({ row, column, rowIndex, columnIndex }) {
      // console.log(row)
       //  console.log(column)
        if (columnIndex === 1) {
          const _row = this.setTable(this.bookingworkticketList).merge[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col
          };
        }
        if (columnIndex === 11) {
          const _row = this.setTable(this.bookingworkticketList).merge[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col
          };
        }
         if (columnIndex === 12) {
          const _row = this.setTable(this.bookingworkticketList).merge[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col
          };
        }
        if (columnIndex === 13) {
          const _row = this.setTable(this.bookingworkticketList).merge[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col
          };
        }


      },
      //单元格整理
        setTable(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;
            }
          }
        });
        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.officeConvertCommon(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)
        }
        // this.$nextTick(() => {
        //   const iframe = window.frames['iFrame']
        //   const handleLoad = () => {
        //     setTimeout(() => {
        //       const Do = (iframe.contentWindow || iframe.contentDocument)
        //       console.log(Do.document.getElementsByTagName('table')[0])
        //       Do.document.getElementsByTagName('table')[0].style.width = "100%"
        //       Do.document.getElementsByTagName('table')[0].setAttribute("class","table")
        //     }, 500)
        //   }
        //   iframe.addEventListener('load', handleLoad, true)
        // })
      }).catch(result => {

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

      })
      }





    },
      //文件预览
    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)
      }
    },

  }
};
</script>

