<template>
  <div class="app-container">
    <!-- 搜索条件 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="SAI类型" prop="saiType">
        <el-form-item prop="saiType">
          <el-select
            clearable
            v-model="queryParams.saiType"
            placeholder="请选择SAI类型">
            <el-option key="SAI" label="SAI" value="SAI"></el-option>
            <el-option key="TPM" label="TPM" value="TPM"></el-option>
          </el-select>
        </el-form-item>
      </el-form-item>
      <el-form-item label="TPM状态" prop="tpmStatus">
        <el-select
          v-model="queryParams.tpmStatus"
          placeholder="请选择TPM状态">
          <el-option key="未完成" label="未完成" value="未完成"></el-option>
          <el-option key="已完成" label="已完成" value="已完成"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="登记人部门" prop="applicantDept">
        <el-form-item prop="applicantDept">
          <el-select
            clearable
            v-model="queryParams.applicantDept"
            placeholder="请选择部门">
            <el-option
              v-for="dict in applicantDeptOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form-item>
      <el-form-item label="登记人班组" prop="applicantTeam">
        <el-form-item prop="applicantTeam">
          <el-select
            clearable
            v-model="queryParams.applicantTeam"
            placeholder="请选择班组">
            <el-option
              v-for="dict in applicantTeamOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form-item>
      <el-form-item label="不安全状态" prop="unsafeStatus">
        <el-select v-model="queryParams.unsafeStatus" placeholder="请选择不安全状态" clearable>
          <el-option
            v-for="dict in unsafeStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="不安全行为" prop="unsafeAction">
        <el-select v-model="queryParams.unsafeAction" placeholder="请选择不安全行为" clearable>
          <el-option
            v-for="dict in unsafeActionOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="申请状态" prop="applyStatus">
        <el-select v-model="queryParams.applyStatus" placeholder="请选择申请状态">
          <el-option
            v-for="dict in applyStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="问题描述" prop="description">
        <el-input
          v-model="queryParams.description"
          placeholder="请输入问题描述"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="登记时间" prop="applyDate">
        <el-date-picker
          v-model="applyDateRange"
          type="daterange"
          align="right"
          unlink-panels
          :range-separator="$t('至')"
          :start-placeholder="$t('开始日期')"
          :end-placeholder="$t('结束日期')"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预计完成时间" prop="estimateFinishDate">
        <el-date-picker
          v-model="estimateFinishDateRange"
          type="daterange"
          align="right"
          unlink-panels
          :range-separator="$t('至')"
          :start-placeholder="$t('开始日期')"
          :end-placeholder="$t('结束日期')"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="片区" prop="workArea">
        <el-select
          clearable
          multiple
          v-model="queryParams.workArea"
          placeholder="请选择片区">
          <el-option key="EOEG" label="EOEG" value="EOEG"></el-option>
          <el-option key="NIS" label="NIS" value="NIS"></el-option>
        </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" style="margin-bottom: 0px;">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['production:eoegapply:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['production:eoegapply:export']"
        >导出全部</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExportSelected"
          v-hasPermi="['production:eoegapply:export']"
        >导出选中数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          size="mini"
          @click="handleAddSai"
          v-hasPermi="['production:sai:add']"
        >统计至SAI检查台账</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 各班组当年至今的提交数量 -->
    <el-descriptions title="" direction="vertical" :column="4" border style="margin-bottom: 20px;">
      <el-descriptions-item label="A班">
        <el-tag size="small">{{countA}}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="B班">
        <el-tag size="small">{{countB}}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="C班">
        <el-tag size="small">{{countC}}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="D班">
        <el-tag size="small">{{countD}}</el-tag>
      </el-descriptions-item>
    </el-descriptions>
    <!-- 总表 -->
    <el-table v-loading="loading" :data="applyList" @selection-change="handleSelectionChange" :height="clientHeight" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="SAI类型" align="center" prop="saiType" :show-overflow-tooltip="true" width="80"/>
      <el-table-column label="TPM状态" align="center" prop="tpmStatus" :show-overflow-tooltip="true" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.saiType=='TPM'">
            <span v-if="scope.row.tpmStatus == '已完成'"><el-tag type="success">已完成</el-tag></span>
            <span v-if="scope.row.tpmStatus == '未完成'"><el-tag type="info">未完成</el-tag></span>
          </span>
          <span v-if="scope.row.saiType=='SAI'">/</span>
        </template>
      </el-table-column>
      <el-table-column label="问题描述" align="center" prop="description" :show-overflow-tooltip="true" width="200"/>
      <el-table-column label="片区" align="center" prop="workArea" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.saiType=='TPM' && scope.row.tpmStatus == '已完成'">/</span>
          <span v-if="!(scope.row.saiType=='TPM' && scope.row.tpmStatus == '已完成')">{{scope.row.workArea}}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请状态" align="center" prop="applyStatus" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.saiType=='TPM' && scope.row.tpmStatus == '已完成'">/</span>
          <span v-if="!(scope.row.saiType=='TPM' && scope.row.tpmStatus == '已完成')">
            <span v-if="scope.row.applyStatus == 0"><el-tag type="info">未提交</el-tag></span>
            <span v-if="scope.row.applyStatus == 1"><el-tag type="warning">待评估</el-tag></span>
            <span v-if="scope.row.applyStatus == 2"><el-tag type="warning">进行中</el-tag></span>
            <span v-if="scope.row.applyStatus == 3"><el-tag type="warning">待验收</el-tag></span>
            <span v-if="scope.row.applyStatus == 4"><el-tag type="success">已完成</el-tag></span>
            <span v-if="scope.row.applyStatus == 5"><el-tag type="info">已取消</el-tag></span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="登记人部门" align="center" prop="applicantDeptName" :show-overflow-tooltip="true"/>
      <el-table-column label="登记人班组" align="center" prop="applicantTeam" :show-overflow-tooltip="true" :formatter="teamFormat"/>
      <el-table-column label="登记人" align="center" prop="applicantName" :show-overflow-tooltip="true"/>
      <el-table-column label="当前处理人" align="center" prop="handlerName" :show-overflow-tooltip="true"/>
      <el-table-column label="整改负责人" align="center" prop="executorName" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.saiType=='TPM' && scope.row.tpmStatus == '已完成'">/</span>
          <span v-if="!(scope.row.saiType=='TPM' && scope.row.tpmStatus == '已完成')">{{scope.row.executorName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="登记时间" align="center" prop="applyDate" width="100" sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applyDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预计完成时间" align="center" prop="estimateFinishDate" width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.saiType=='TPM' && scope.row.tpmStatus == '已完成'">/</span>
          <span v-if="!(scope.row.saiType=='TPM' && scope.row.tpmStatus == '已完成')">{{ parseTime(scope.row.estimateFinishDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际完成时间" align="center" prop="actualFinishDate" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.saiType=='TPM' && scope.row.tpmStatus == '已完成'">/</span>
          <span v-if="!(scope.row.saiType=='TPM' && scope.row.tpmStatus == '已完成')">{{ parseTime(scope.row.actualFinishDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="SAI级别" align="center" prop="saiLevel" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.saiType=='TPM'">/</span>
          <span v-if="scope.row.saiType=='SAI'">{{scope.row.saiLevel}}</span>
        </template>
      </el-table-column>
      <el-table-column label="SAI类别" align="center" prop="category" :show-overflow-tooltip="true" :formatter="saiCategoryFormat"/>
      <el-table-column label="操作" align="center" fixed="right" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- 申请状态为待评估/进行中/待验收 -->
          <!-- 当前登录用户为处理人（之一） -->
          <el-button
            size="mini"
            type="text"
            @click="handleDetail(scope.row)"
            icon="el-icon-edit-outline"
            v-if="(scope.row.applyStatus == 1 || scope.row.applyStatus == 2 || scope.row.applyStatus == 3)
            && ((scope.row.handler.indexOf(loginStaffInfo.userId) != -1))"
          >处理</el-button>
          <!-- 申请状态为已完成/已中止-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-if="scope.row.applyStatus == 4 || scope.row.applyStatus == 5"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            @click="processImg(scope.row.processId)"
            v-if="scope.row.applyStatus != 0"
          >{{ $t('流程图') }}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['production:eoegapply:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['production:eoegapply:remove']"
          >删除</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"
    />
    <!-- 添加或修改SAI开项管理对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="0px">
        <el-descriptions title="" :column="3" border>
          <el-descriptions-item label="SAI类型" :span="1">
            <el-form-item prop="saiType">
              <el-select
                v-model="form.saiType"
                placeholder="请选择SAI类型">
                <el-option key="SAI" label="SAI" value="SAI"></el-option>
                <el-option key="TPM" label="TPM" value="TPM"></el-option>
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="TPM状态" :span="2" v-if="form.saiType == 'TPM'">
            <el-form-item prop="tpmStatus">
              <el-select
                v-model="form.tpmStatus"
                placeholder="请选择TPM状态">
                <el-option key="未完成" label="未完成" value="未完成"></el-option>
                <el-option key="已完成" label="已完成" value="已完成"></el-option>
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="登记人部门">
            <el-form-item prop="applicantDept">
              <el-select
                filterable
                clearable
                v-model="form.applicantDept"
                @change="handleDeptOrTeamChange"
                placeholder="请选择部门">
                <el-option
                  v-for="dict in applicantDeptOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="登记人班组">
            <el-form-item prop="applicantTeam">
              <el-select
                filterable
                clearable
                v-model="form.applicantTeam"
                @change="handleDeptOrTeamChange"
                :disabled="applicantTeamDisabled"
                placeholder="请选择班组">
                <el-option
                  v-for="dict in applicantTeamOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="登记人">
            <el-form-item prop="applicant">
              <el-select
                filterable
                clearable
                v-model="form.applicant"
                placeholder="请选择登记人">
                <el-option
                  v-for="dict in applicantOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="问题描述" :span="3">
            <el-form-item prop="description">
              <el-input v-model="form.description" placeholder="请输入问题描述" type="textarea" :rows="3" />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="采取的措施" :span="3">
            <el-form-item prop="reaction">
              <el-input v-model="form.reaction" placeholder="请输入采取的措施" type="textarea" :rows="3"/>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="SAI级别" :span="1" v-if="form.saiType == 'SAI'">
            <el-form-item prop="saiLevel">
              <el-select v-model="form.saiLevel" placeholder="请选择SAI级别" @change="handleSaiLevelChange">
                <el-option key="1" label="1" value="1"></el-option>
                <el-option key="2" label="2" value="2"></el-option>
                <el-option key="3" label="3" value="3"></el-option>
              </el-select>
              <span @click="saiTypeInfo = true" style="padding-left: 5px; cursor: pointer;">
                <i class="el-icon-question"></i>
              </span>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="SAI类别" :span="2" v-if="form.saiType == 'SAI'">
            <el-form-item prop="category">
              <el-select
                @change="handleSaiCategoryChange"
                filterable
                clearable
                v-model="form.category"
                placeholder="请选择SAI类别">
                <el-option
                  v-for="dict in saiCategoryOptions2"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="片区" :span="1" v-if="form.saiType == 'SAI' || (form.saiType == 'TPM' && form.tpmStatus == '未完成')">
            <el-form-item prop="workArea">
              <el-select
                @change="handleSaiCategoryChange"
                filterable
                clearable
                v-model="form.workArea"
                placeholder="请选择片区">
                <el-option key="EOEG" label="EOEG" value="EOEG"></el-option>
                <el-option key="NIS" label="NIS" value="NIS"></el-option>
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="整改负责人" :span="2" v-if="form.saiType == 'SAI' || (form.saiType == 'TPM' && form.tpmStatus == '未完成')">
            <el-form-item prop="executor">
              <el-select
                filterable
                :disabled="assessDisabled"
                clearable
                v-model="form.executor"
                placeholder="请选择整改负责人">
                <el-option
                  v-for="dict in applicantOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="隐患" :span="3" v-if="form.saiType == 'SAI'">
            <el-radio v-model="unsafeChoice" label="1" @change="handleUnsafeChoiceChange" style="margin-right: 10px;">不安全状态</el-radio>
            <el-form-item prop="unsafeStatus" style="display: inline-block;">
              <el-select v-model="form.unsafeStatus" filterable placeholder="请选择不安全状态" :disabled="unsafeStatusDisabled" style="margin-right: 20px;" clearable>
                <el-option
                  v-for="dict in unsafeStatusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-radio v-model="unsafeChoice" label="2" @change="handleUnsafeChoiceChange" style="margin-right: 10px;">不安全行为</el-radio>
            <el-form-item prop="unsafeAction" style="display: inline-block;">
              <el-select v-model="form.unsafeAction" filterable placeholder="请选择不安全行为" :disabled="unsafeActionDisabled" clearable>
                <el-option
                  v-for="dict in unsafeActionOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="附件" :span="3">
            <el-form-item label="" prop="fileUrl">
              <el-upload
                ref="doc"
                :limit="5"
                :headers="doc.headers"
                :action="doc.url"
                :disabled="doc.isUploading"
                :on-progress="handleFileDocProgress"
                :on-success="handleFileDocSuccess"
                :on-remove="handleRemove"
                :auto-upload="true"
                :file-list="fileList"
                drag
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  {{ $t('将文件拖到此处，或') }}
                  <em>{{ $t('点击上传') }}</em>
                </div>
              </el-upload>
            </el-form-item>
            <el-table :data="doc.commonfileListApply" border v-if="form.saiApplyId">
              <el-table-column :label="$t('文件名')" align="center" prop="fileName" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <a  class="link-type"  @click="handleDownload(scope.row)">
                    <span>{{ scope.row.fileName }}</span>
                  </a>
                </template>
              </el-table-column>
              <el-table-column :label="$t('操作')" align="center" width="120" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    v-if="scope.row.fileName.endsWith('pdf')||scope.row.fileName.endsWith('xlsx')||scope.row.fileName.endsWith('md')
                 ||scope.row.fileName.endsWith('docx')||scope.row.fileName.endsWith('doc')||scope.row.fileName.endsWith('txt')
                 ||scope.row.fileName.endsWith('jpg')||scope.row.fileName.endsWith('png')||scope.row.fileName.endsWith('csv')
                 ||scope.row.fileName.endsWith('mp4')||scope.row.fileName.endsWith('svg')||scope.row.fileName.endsWith('dwg')
                 ||scope.row.fileName.endsWith('flv')||scope.row.fileName.endsWith('swf')||scope.row.fileName.endsWith('gif')
                 ||scope.row.fileName.endsWith('3gp')||scope.row.fileName.endsWith('mkv')||scope.row.fileName.endsWith('tif')"
                    size="mini"
                    type="text"
                    icon="el-icon-view"
                    @click="handleSee(scope.row)"
                  > {{ $t('预览') }}</el-button>
                  <el-button
                    v-if="scope.row.fileName.endsWith('ppt')||scope.row.fileName.endsWith('pptx') "
                    size="mini"
                    type="text"
                    icon="el-icon-view"
                    @click="handleSeePPT(scope.row)"
                  > {{ $t('ppt预览') }}</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-download"
                    @click="handleDownload(scope.row)"
                  >{{ $t('下载') }}</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-descriptions-item>
          <el-descriptions-item label="登记时间">
            <el-form-item prop="applyDate">
              <el-date-picker
                size="small"
                style="width: 200px"
                v-model="form.applyDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择登记时间">
              </el-date-picker>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="form.saiType == 'TPM' && form.tpmStatus == '已完成'" type="primary" @click="submitForm">保 存 TPM</el-button>
        <el-button v-if="form.saiType == 'TPM' && form.tpmStatus == '未完成'" type="primary" @click="handleSaveAndSubmit">提 交 TPM</el-button>
        <el-button v-if="form.saiType == 'SAI'" type="primary" @click="handleSaveAndSubmit" :disabled="submitDisabled">提 交 SAI</el-button>
        <el-button v-if="form.saiType == 'SAI'" @click="submitForm" :disabled="submitDisabled">保 存 SAI</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 延期对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="title" :visible.sync="delayOpen" width="25%" append-to-body>
      <el-form ref="delayForm" :model="delayForm" :rules="delayRules" label-width="136px">
        <el-form-item prop="estimateFinishDate" label="预计完成时间">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            v-model="delayForm.estimateFinishDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择预计完成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="isRecorded" label="是否录入开项系统">
          <el-radio v-model="delayForm.isRecorded" label="1" @change="handleIsRecordedChange">是</el-radio>
          <el-radio v-model="delayForm.isRecorded" label="0" @change="handleIsRecordedChange">否</el-radio>
        </el-form-item>
        <el-form-item prop="recordNo" label="开项编号">
          <el-input v-model="delayForm.recordNo" placeholder="请输入开项编号" :disabled="recordNoDisabled"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDelayForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog  :close-on-click-modal="false" :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"
        :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-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <form ref="downloadFileForm" :action="upload.downloadAction" target="FORMSUBMIT">
          <input name="type" :value="upload.type" hidden />
        </form>
        <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>
    <!-- SAI开项管理流转详情对话框 -->
    <eoeg-sai-apply-detail v-if="saiApplyVisible" ref="saiApplyDetail" @refreshDataList="getList"></eoeg-sai-apply-detail>
    <!-- 流程图对话框 -->
    <process-img v-if="processImgVisible" ref="processImg" @refreshDataList="getList"></process-img>
    <!-- 附件对话框 -->
    <el-dialog  :close-on-click-modal="false" v-dialogDrag :title="doc.title" :visible.sync="doc.open" width="700px" append-to-body>
      <el-upload
        ref="doc"
        :limit="50"
        :headers="doc.headers"
        :action="doc.url + '?pType=' + doc.pType + '&pId=' + doc.pId"
        :disabled="doc.isUploading"
        :on-progress="handleFileDocProgress"
        :on-success="handleFileDocSuccess"
        :auto-upload="true"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          {{ $t('将文件拖到此处，或') }}
          <em>{{ $t('点击上传') }}</em>
        </div>
      </el-upload>
      <el-table :data="doc.commonfileList" border>
        <el-table-column :label="$t('文件名')" align="center" prop="fileName" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <a  class="link-type"  @click="handleDownload(scope.row)">
              <span>{{ scope.row.fileName }}</span>
            </a>
          </template>
        </el-table-column>
        <el-table-column :label="$t('大小(Kb)')" align="center" prop="fileSize" :show-overflow-tooltip="true" width="80" />
        <el-table-column :label="$t('上传人')" align="center" prop="creator" :show-overflow-tooltip="true" width="120"/>
        <el-table-column :label="$t('上传时间')" align="center" prop="createdate" :show-overflow-tooltip="true" width="120"/>
        <el-table-column :label="$t('操作')" align="center" width="120" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.fileName.endsWith('pdf')||scope.row.fileName.endsWith('xlsx')||scope.row.fileName.endsWith('md')
                 ||scope.row.fileName.endsWith('docx')||scope.row.fileName.endsWith('doc')||scope.row.fileName.endsWith('txt')
                 ||scope.row.fileName.endsWith('jpg')||scope.row.fileName.endsWith('png')||scope.row.fileName.endsWith('csv')
                 ||scope.row.fileName.endsWith('mp4')||scope.row.fileName.endsWith('svg')||scope.row.fileName.endsWith('dwg')
                 ||scope.row.fileName.endsWith('flv')||scope.row.fileName.endsWith('swf')||scope.row.fileName.endsWith('gif')
                 ||scope.row.fileName.endsWith('3gp')||scope.row.fileName.endsWith('mkv')||scope.row.fileName.endsWith('tif')"
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleSee(scope.row)"
            > {{ $t('预览') }}</el-button>
            <el-button
              v-if="scope.row.fileName.endsWith('ppt')||scope.row.fileName.endsWith('pptx') "
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleSeePPT(scope.row)"
            > {{ $t('ppt预览') }}</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-download"
              @click="handleDownload(scope.row)"
            >{{ $t('下载') }}</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteDoc(scope.row)"
            >{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="doc.open = false">{{ $t('返 回') }}</el-button>
      </div>
    </el-dialog>
    <!-- 统计至SAI检查台账对话框 -->
    <el-dialog  :close-on-click-modal="false" title="统计至SAI检查台账" :visible.sync="saiOpen" width="80%" append-to-body>
      <el-table v-loading="loading" :data="saiList" @selection-change="handleSelectionChange" :height="clientHeight" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="检查的装置/设施" align="center" prop="plantId" :show-overflow-tooltip="true"/>
        <el-table-column label="检查日期/时间" align="center" prop="inspectionDate">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.inspectionDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="识别出的安全问题" align="center" prop="dificiency" :show-overflow-tooltip="true"/>
        <el-table-column label="SAI级别" align="center" prop="saiLevel" :show-overflow-tooltip="true" width="100">
          <template slot-scope="scope">
            <el-select v-model="scope.row.saiLevel" placeholder="请选择">
              <el-option key="1" label="1" value="1"></el-option>
              <el-option key="2" label="2" value="2"></el-option>
              <el-option key="3" label="3" value="3"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="SAI类别" align="center" prop="category" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-select
              filterable
              clearable
              v-model="scope.row.category"
              placeholder="请选择SAI类别">
              <el-option
                v-for="dict in saiCategoryOptions2"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="采取或要采取的措施" align="center" prop="actions" :show-overflow-tooltip="true"/>
        <el-table-column label="用户" align="center" prop="userDeptId" :show-overflow-tooltip="true"/>
        <el-table-column label="数据来源" align="center" prop="source" :show-overflow-tooltip="true"/>
        <el-table-column label="检查人" align="center" prop="applicantName" :show-overflow-tooltip="true"/>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSaiForm">确 定</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" :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>
      <div style="padding: 30px; width: 100%; height: 100%;" >
        <el-carousel class="" ref="carousel"  arrow="always"  v-if="pptView"
                     height="700px"  trigger="click" :autoplay="false" indicator-position="outside">
          <el-carousel-item class="lun_img" v-for="item in imgs" v-bind:key="item" >
            <img :src="item" width="100%" height="100%" object-fit="cover" />
          </el-carousel-item>
        </el-carousel>
      </div>
    </el-dialog>
    <!-- SAI类型说明对话框 -->
    <el-dialog  :close-on-click-modal="false" title="SAI类型说明" :visible.sync="saiTypeInfo" width="400px" append-to-body>
      SAI类型说明（图片）
    </el-dialog>
  </div>
</template>

<script>
  import { saveAndSubmitApply, submitApply, listApply, getApply, delApply, addApply, updateApply, exportApply, importTemplate, getTeamAnalysis} from "@/api/production/eoegApply";
  import { addSai } from "@/api/production/eoegSai";
  import { treeselect, listDept } from "@/api/system/dept";
  import { getToken } from "@/utils/auth";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import EoegSaiApplyDetail from "@/views/approve/approveDetail/eoeg-sai-apply-detail";
  import ProcessImg from '@/views/approve/processImg/index';
  import { listStaffmgrByDeptAndTeam, getLoginStaffInfo } from "@/api/plant/staffmgr";
  import { allFileList, delCommonfile } from "@/api/common/commonfile";
  import { categoryList } from "@/api/production/eoegCategory";
  import { listFile } from "@/api/production/eoegSaiApproveFile";
  import { selectDevice } from "@/api/invoice/device";

  export default {
    name: "Apply",
    components: { Treeselect, EoegSaiApplyDetail, ProcessImg },
    data() {
      var validateRecordNo = (rule, value, callback) => {
        if (this.delayForm.isRecorded == '1') {
          if (this.delayForm.recordNo == null) {
            return callback(new Error('开项编号不能为空'));
          } else {
            return callback();
          }
        } else {
          return callback();
        }
      };
      var validateApplicantTeam = (rule, value, callback) => {
        if (!this.applicantTeamDisabled) {
          if (this.form.applicantTeam == null) {
            return callback(new Error('登记人班组不能为空'));
          } else {
            return callback();
          }
        } else {
          return callback();
        }
      };
      var validateUnsafeStatus = (rule, value, callback) => {
        if (this.unsafeChoice == '1') {
          if (this.form.unsafeStatus == null) {
            return callback(new Error('不安全状态不能为空'));
          } else {
            return callback();
          }
        } else {
          return callback();
        }
      };
      var validateUnsafeAction = (rule, value, callback) => {
        if (this.unsafeChoice == '2') {
          if (this.form.unsafeAction == null) {
            return callback(new Error('不安全行为不能为空'));
          } else {
            return callback();
          }
        } else {
          return callback();
        }
      };
      return {
        // SAI类型说明
        saiTypeInfo: false,
        submitDisabled: false,
        applyDateRange: [],
        estimateFinishDateRange: [],
        // SAI类别列表
        saiCategoryOptions: [],
        saiCategoryOptions2: [],
        fileList: [],
        // 统计至SAI检查台账的数据
        saiList: [],
        // 是显示用统计至SAI检查台账对话框
        saiOpen: false,
        // 是否禁用开项编号输入框
        recordNoDisabled: true,
        // 当前登录员工
        loginStaffInfo: {},
        //图片集合   打开关闭按钮 等等
        imgs:[],
        jpgList:[],
        ppt:false,
        pptView:false,
        loadingFlash:false,
        doc: {
          file: "",
          // 是否显示弹出层（报告附件）
          open: false,
          // 弹出层标题（报告附件）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 报告附件上传位置编号
          ids: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/production/eoegSaiFile/uploadFile",
          commonfileList: null,
          commonfileListApply: null,
          queryParams: {
            pId: null,
            pType: 'eoegSaiApply'
          },
          pType: 'eoegSaiApply',
          pId: null
        },
        // pdf文件参数
        pdf : {
          title: '',
          pdfUrl: '',
          numPages: null,
          open: false,
          pageNum: 1,
          pageTotalNum: 1,
          loadedRatio: 0,
        },
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: false,
        // 总条数
        total: 0,
        // SAI开项管理表格数据
        applyList: [],
        // 弹出层标题
        title: "",
        // 部门树选项
        deptOptions: undefined,
        clientHeight:300,
        // 是否显示弹出层
        open: false,
        // 是否显示延期弹出层
        delayOpen: false,
        // 用户导入参数
        upload: {
          //下载模板请求地址
          downloadAction: process.env.VUE_APP_BASE_API + '/common/template',
          //下载模板类型
          type: 'saiApply',
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/production/apply/importData"
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 20,
          saiApplyId: null,
          deptId: null,
          applyStatus: null,
          apNo: null,
          processId: null,
          applicant: null,
          assessor: null,
          executor: null,
          inspectors: null,
          applicantDept: null,
          applicantTeam: null,
          description: null,
          unsafeStatus: null,
          unsafeAction: null,
          applyDate: null,
          taskId: null,
          handler: null,
          taskName: null,
          estimateFinishDate: null,
          actualFinishDate: null,
          isRecorded: null,
          recordNo: null,
          reaction: null,
          needVe: null,
          veItems: null,
          veResult: null,
          veItemOther: null,
          applyDateStart: null,
          applyDateEnd: null,
          estimateFinishDateStart: null,
          estimateFinishDateEnd: null,
        },
        // 表单参数
        form: {},
        // 延期表单参数
        delayForm: {},
        // 延期表单校验
        delayRules: {
          estimateFinishDate: [
            { required: true, message: this.$t('预计完成时间') + this.$t('不能为空'), trigger: "change" }
          ],
          isRecorded: [
            { required: true, message: this.$t('是否录入开项系统') + this.$t('不能为空'), trigger: "change" }
          ],
          recordNo: [
            { validator: validateRecordNo, trigger: 'change' }
          ],
        },
        // 新增/修改表单校验
        rules: {
          description: [
            { required: true, message: this.$t('问题描述') + this.$t('不能为空'), trigger: "change" }
          ],
          applicantDept: [
            { required: true, message: this.$t('登记人部门') + this.$t('不能为空'), trigger: "change" }
          ],
          applicantTeam: [
            { validator: validateApplicantTeam, trigger: 'change' }
          ],
          applicant: [
            { required: true, message: this.$t('登记人') + this.$t('不能为空'), trigger: "change" }
          ],
          applyDate: [
            { required: true, message: this.$t('记录日期') + this.$t('不能为空'), trigger: "change" }
          ],
          workArea: [
            { required: true, message: this.$t('片区') + this.$t('不能为空'), trigger: "change" }
          ],
          unsafeStatus: [
            { validator: validateUnsafeStatus, trigger: 'change' }
          ],
          unsafeAction: [
            { validator: validateUnsafeAction, trigger: 'change' }
          ],
          saiLevel: [
            { required: true, message: this.$t('SAI级别') + this.$t('不能为空'), trigger: "change" }
          ],
          category: [
            { required: true, message: this.$t('SAI类别') + this.$t('不能为空'), trigger: "change" }
          ],
        },
        // 申请状态字典
        applyStatusOptions: [],
        // 登记人班组字典
        applicantTeamOptions: [],
        // 登记人部门列表
        applicantDeptOptions: [],
        // 登记人列表
        applicantOptions: [],
        // 不安全状态字典
        unsafeStatusOptions: [],
        // 不安全行为字典
        unsafeActionOptions: [],
        // 是否显示SAI开项申请详情对话框
        saiApplyVisible: false,
        // 是否显示流程图对话框
        processImgVisible: null,
        // 不安全状态/行为选项
        unsafeChoice: '1',
        // 是否禁用不安全状态下拉框
        unsafeStatusDisabled: false,
        // 是否禁用不安全行为下拉框
        unsafeActionDisabled: true,
        // 是否禁用班组下拉框
        applicantTeamDisabled: false,
        workAreaList: [],
        countA: 0,
        countB: 0,
        countC: 0,
        countD: 0,
      };
    },
    watch: {
      // 根据名称筛选部门树
      deptName(val) {
        this.$refs.tree.filter(val);
      }
    },
    created() {
      //设置表格高度对应屏幕高度
      this.$nextTick(() => {
        this.clientHeight = document.body.clientHeight -250
      })
      this.getList();
      this.getTreeselect();
      // 加载申请状态字典
      this.getDicts("SAI_APPLY_STATUS").then(response => {
        this.applyStatusOptions = response.data;
      });
      // 加载登记人班组字典
      this.getDicts("TEAM_DIVIDE").then(response => {
        this.applicantTeamOptions = response.data;
      });
      // 加载登记人部门列表
      this.getApplicantDeptOptions();
      // 加载登记人列表
      this.listStaffmgrByDeptAndTeam('38', null);
      // 加载不安全状态字典
      this.getDicts("SAI_UNSAFE_STATUS").then(response => {
        this.unsafeStatusOptions = response.data;
      });
      // 加载不安全行为字典
      this.getDicts("SAI_UNSAFE_ACTION").then(response => {
        this.unsafeActionOptions = response.data;
      });
      // 加载当前登录员工信息
      this.getLoginStaffInfo();
      this.getCategoryList();
      this.getWorkAreaList();
      this.getTeamTable();
    },
    methods: {
      getTeamTable() {
        getTeamAnalysis().then(response => {
          let data = response.data;
          for (let i = 0; i < data.length; i++) {
            let applicantTeam = data[i].applicantTeam;
            let teamCount = data[i].teamCount;
            if (applicantTeam == 'A') {
              if (teamCount != '') {
                this.countA = teamCount;
              }
            } else if (applicantTeam == 'B') {
              if (teamCount != '') {
                this.countB = teamCount;
              }
            } else if (applicantTeam == 'C') {
              if (teamCount != '') {
                this.countC = teamCount;
              }
            } else if (applicantTeam == 'D') {
              if (teamCount != '') {
                this.countD = teamCount;
              }
            }
          }
        });
      },
      getWorkAreaList() {
        selectDevice().then(response => {
          let data = response.data;
          for (let i = 0; i < data.length; i++) {
            this.workAreaList.push(data[i]);
          }
        });
      },
      // 处理SAI级别下拉框选中事件
      handleSaiLevelChange() {
        this.saiCategoryOptions2 = [];
        let saiLevel = this.form.saiLevel;
        let saiCategoryOptionsTemp = [];
        for (let i = 0; i < this.saiCategoryOptions.length; i++) {
          if (saiLevel == 1 && this.saiCategoryOptions[i].dictLabel.indexOf("-1-") != -1) {
            let saiCategoryOption = {
              dictValue: this.saiCategoryOptions[i].dictValue,
              dictLabel: this.saiCategoryOptions[i].dictLabel,
            };
            saiCategoryOptionsTemp.push(saiCategoryOption);
          }
          if (saiLevel == 2 && this.saiCategoryOptions[i].dictLabel.indexOf("-2-") != -1) {
            let saiCategoryOption = {
              dictValue: this.saiCategoryOptions[i].dictValue,
              dictLabel: this.saiCategoryOptions[i].dictLabel,
            };
            saiCategoryOptionsTemp.push(saiCategoryOption);
          }
          if (saiLevel == 3 && this.saiCategoryOptions[i].dictLabel.indexOf("-3-") != -1) {
            let saiCategoryOption = {
              dictValue: this.saiCategoryOptions[i].dictValue,
              dictLabel: this.saiCategoryOptions[i].dictLabel,
            };
            saiCategoryOptionsTemp.push(saiCategoryOption);
          }
        }
        this.saiCategoryOptions2 = saiCategoryOptionsTemp;
      },
      // 处理SAI类别下拉框选中事件
      handleSaiCategoryChange() {
        for (let i = 0; i < this.saiCategoryOptions.length; i++) {
          if (this.form.category == this.saiCategoryOptions[i].dictValue) {
            if (this.saiCategoryOptions[i].dictLabel.indexOf("-1-") != -1) {
              this.form.saiLevel = 1;
            }
            if (this.saiCategoryOptions[i].dictLabel.indexOf("-2-") != -1) {
              this.form.saiLevel = 2;
            }
            if (this.saiCategoryOptions[i].dictLabel.indexOf("-3-") != -1) {
              this.form.saiLevel = 3;
            }
          }
        }
      },
      // SAI类别字典翻译
      saiCategoryFormat(row, column) {
        if (row.category == null || row.category == '') {
          return "/";
        } else {
          return this.selectDictLabel(this.saiCategoryOptions, row.category);
        }
      },
      /** 获取SAI类别列表数据 */
      getCategoryList() {
        categoryList().then(response => {
          let data = response.data;
          for (let i = 0; i < data.length; i++) {
            if (data[i].saiCategoryName != null && data[i].saiCategoryName != "") {
              this.saiCategoryOptions.push({
                dictLabel: data[i].saiCategoryName + "(" + data[i].saiCategoryDescription + ")",
                dictValue: data[i].saiCategoryId
              });
              this.saiCategoryOptions2.push({
                dictLabel: data[i].saiCategoryName + "(" + data[i].saiCategoryDescription + ")",
                dictValue: data[i].saiCategoryId
              });
            }
          }
        });
      },
      /** 是否录入开项系统单选按钮值改变事件 */
      handleIsRecordedChange() {
        if (this.delayForm.isRecorded == '1') {
          this.recordNoDisabled = false;
        } else if (this.delayForm.isRecorded == '0') {
          this.recordNoDisabled = true;
          this.delayForm.recordNo = null;
        }
      },
      /** 文件下载处理 */
      handleDownload(row) {
        var name = row.fileName;
        var url = row.fileUrl;
        var suffix = url.substring(url.lastIndexOf("."), url.length);
        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()
      },
      /** 报告附件按钮操作 */
      handleDoc(row) {
        this.doc.id = row.saiApplyId;
        this.doc.title = "附件";
        this.doc.open = true;
        this.doc.queryParams.pId = row.saiApplyId
        this.doc.pId = row.saiApplyId
        this.getFileList()
        this.$nextTick(() => {
          this.$refs.doc.clearFiles()
        })
      },
      getFileList() {
        allFileList(this.doc.queryParams).then(response => {
          this.doc.commonfileList = response;
        });
      },
      /** 附件上传中处理 */
      handleFileDocProgress(event, file, fileList) {
        this.doc.file = file;
        this.doc.isUploading = true;
      },
      // /** 附件上传成功处理 */
      // handleFileDocSuccess(response, file, fileList) {
      //   this.doc.isUploading = false;
      //   this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true });
      //   this.getFileList()
      // },
      //附件上传成功处理
      handleFileDocSuccess(response, file, fileList) {
        this.doc.isUploading = false;
        this.fileList = fileList
        if (response.code == 200){
          this.$alert(this.$t('导入成功'), this.$t('导入结果'), { dangerouslyUseHTMLString: true });
        }else {
          this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true });
        }
      },
      handleRemove (file, fileList) {
        this.fileList = fileList
      },
      /** 删除按钮操作 */
      handleDeleteDoc(row) {
        const ids = row.id || this.ids;
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: "warning"
        }).then(function() {
          return delCommonfile(ids);
        }).then(() => {
          this.getFileList();
          this.msgSuccess(this.$t('删除成功'));
        })
      },
      //文件预览
      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)
        }
      },
      handleSeePPT (row){
        //ppt预览
        this.loadingFlash=true
        this.pdf.open =true
        this.pdf.title = row.fileName
        this.pdf.pdfUrl = row.fileUrl
        this.pptView=true
        this.ppt=false
        const formatDate =new FormData();
        formatDate.append("filepath",row.fileUrl)

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

        //查看接受的全局方法的返回结果 console.log(res)
        //利用.then方法接受Promise对象

        res.then((result)=>{
          //关闭加载中
          this.loadingFlash=false

          //成功时直接给地址
          this.videoList = result.data.imagePathList
          //将返回的地址集合遍历添加到绑定的数组中
          this.imgs=[]
          for (var key=0;key<this.videoList.length;key++) {
            this.imgs.push( process.env.VUE_APP_BASE_API+  this.videoList[key]  );
          }
        }).catch(result => {

          //请求失败，关闭loading，pdf地址直接为为空，不显示
          this.pdf.pdfUrl =""
          this.loadingFlash = false;
        })
      },
      handleSee (row){
        //office预览
        this.loadingFlash=true
        this.pdf.open =true
        this.pdf.title = row.fileName
        this.pdf.pdfUrl =""

        this.pptView=false
        this.ppt=true
        //如果是PDF等直接可以打开的就不调接口，否则调用接口
        if(row.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.fileUrl)

          //调用文件预览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
            }
            // 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;

          })
        }


      },
      /** 加载当前登录员工信息 */
      getLoginStaffInfo() {
        getLoginStaffInfo().then(response => {
          let staff = response.data;
          if (staff != null) {
            this.loginStaffInfo = response.data;
            this.form.applicantDept = staff.unit;
            if (staff.unit == '38') {
              this.form.applicantTeam = staff.team;
            }
            this.form.applicant = staff.userId;
          }
        });
      },
      /** 加载登记人部门列表 */
      getApplicantDeptOptions() {
        this.applicantDeptOptions.push({ dictLabel: "CEP/E", dictValue: '38' });
        this.applicantDeptOptions.push({ dictLabel: "CTA/B", dictValue: '12' });
        this.applicantDeptOptions.push({ dictLabel: "CTM/B", dictValue: '14' });
      },
      /** 部门/班组值改变事件 */
      handleDeptOrTeamChange() {
        this.applicantOptions = [];
        this.form.applicant = null;
        let applicantDept = this.form.applicantDept;
        if (applicantDept != '38') {
          this.applicantTeamDisabled = true;
          this.form.applicantTeam = null;
        } else {
          this.applicantTeamDisabled = false;
        }
        let applicantTeam = this.form.applicantTeam;
        // 加载登记人列表
        this.listStaffmgrByDeptAndTeam(applicantDept, null);
      },
      /** 加载登记人列表 */
      listStaffmgrByDeptAndTeam(applicantDept, applicantTeam) {
        listStaffmgrByDeptAndTeam({
          deptId: applicantDept,
          team: applicantTeam
        }).then(response => {
          let staffList = response.rows;
          this.applicantOptions = [];
          for (let i = 0; i < staffList.length; i++) {
            let staffOption = {
              dictLabel: staffList[i].name,
              dictValue: staffList[i].userId
            }
            this.applicantOptions.push(staffOption);
          }
        });
      },
      /** 不安全行为/状态单选按钮值改变事件 */
      handleUnsafeChoiceChange() {
        if (this.unsafeChoice == '1') {
          this.form.unsafeAction = null;
          this.unsafeStatusDisabled = false;
          this.unsafeActionDisabled = true;
        } else if (this.unsafeChoice == '2') {
          this.form.unsafeStatus = null;
          this.unsafeStatusDisabled = true;
          this.unsafeActionDisabled = false;
        }
      },
      /** 流程图 */
      processImg (processId) {
        this.processImgVisible = true;
        this.$nextTick(() => {
          this.$refs.processImg.init(processId);
        })
      },
      /** 处理延期操作 */
      handleDelay(row) {
        this.reset();
        const saiApplyId = row.saiApplyId || this.ids
        getApply(saiApplyId).then(response => {
          this.delayForm = response.data;
          if (this.delayForm.isRecorded != null) {
            this.delayForm.isRecorded = this.delayForm.isRecorded.toString();
          }
          this.delayOpen = true;
          this.title = "SAI开项申请延期";
        });
      },
      /** 处理/详情操作 */
      handleDetail(row) {
        this.saiApplyVisible = true;
        this.$nextTick(() => {
          this.$refs.saiApplyDetail.init(row.saiApplyId, row.taskId, row.processId, row.taskName);
        });
      },
      /** 提交申请操作 */
      handleSubmit(row) {
        this.$confirm('是否确认提交申请?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return submitApply(row.saiApplyId);
        }).then(() => {
          this.getList();
          this.msgSuccess("提交申请成功");
        })
      },
      // 申请状态字典翻译
      applyStatusFormat(row, column) {
        return this.selectDictLabel(this.applyStatusOptions, row.applyStatus);
      },
      // 班组字典翻译
      teamFormat(row, column) {
        return this.selectDictLabel(this.applicantTeamOptions, row.applicantTeam);
      },
      /** 查询SAI开项管理列表 */
      getList() {
        this.loading = true;
        getLoginStaffInfo().then(response => {
          let staff = response.data;
          if (staff != null) {
            this.loginStaffInfo = response.data;
          }
          this.queryParams.tab = 1;
          if (this.queryParams.workArea != null && this.queryParams.workArea != "") {
            this.queryParams.workArea = this.queryParams.workArea.join();
          } else {
            this.queryParams.workArea = "";
          }
          listApply(this.queryParams).then(response => {
            if (this.queryParams.workArea != null && this.queryParams.workArea != "") {
              this.queryParams.workArea = this.queryParams.workArea.split(",");
            }
            // let rows = response.rows;
            // this.applyList = [];
            // for (let i = 0; i < rows.length; i++) {
            //   // 当前用户为流程当前处理人（之一），申请流程未结束
            //   if (rows[i].handler.indexOf(this.loginStaffInfo.userId) != -1 && rows[i].applyStatus != 4 && rows[i].applyStatus != 5) {
            //     this.applyList.push(rows[i]);
            //   }
            // }
            this.applyList = response.rows;
            this.total = response.total;
            this.loading = false;
          });
        });
      },
      /** 查询部门下拉树结构 */
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data;
        });
      },
      // 取消按钮
      cancel() {
        this.delayOpen = false;
        this.saiOpen = false;
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          saiApplyId: null,
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          deptId: null,
          applyStatus: null,
          apNo: null,
          processId: null,
          applicant: null,
          assessor: null,
          executor: null,
          inspectors: null,
          applicantDept: null,
          applicantTeam: null,
          description: null,
          unsafeStatus: null,
          unsafeAction: null,
          applyDate: new Date(),
          taskId: null,
          handler: null,
          taskName: null,
          estimateFinishDate: null,
          actualFinishDate: null,
          isRecorded: null,
          recordNo: null,
          reaction: null,
          needVe: null,
          veItems: null,
          veResult: null,
          veItemOther: null,
          applyDateStart: null,
          applyDateEnd: null,
          estimateFinishDateStart: null,
          estimateFinishDateEnd: null,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        if (this.applyDateRange != null) {
          this.queryParams.applyDateStart = this.applyDateRange[0];
          this.queryParams.applyDateEnd = this.applyDateRange[1];
        } else {
          this.queryParams.applyDateStart = null;
          this.queryParams.applyDateEnd = null;
        }
        if (this.estimateFinishDateRange != null) {
          this.queryParams.estimateFinishDateStart = this.estimateFinishDateRange[0];
          this.queryParams.estimateFinishDateEnd = this.estimateFinishDateRange[1];
        } else {
          this.queryParams.estimateFinishDateStart = null;
          this.queryParams.estimateFinishDateEnd = null;
        }
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.saiApplyId)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.fileList = [];
        this.open = true;
        this.title = "新增 TPM / SAI";
        // 加载当前登录员工信息
        this.getLoginStaffInfo();
        this.applicantTeamDisabled = false;
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const saiApplyId = row.saiApplyId || this.ids
        listFile({
          approveId: saiApplyId
        }).then(response => {
          this.doc.commonfileListApply = response;
        });
        getApply(saiApplyId).then(response => {
          this.form = response.data;
          if (this.form.unsafeStatus != null && this.form.unsafeStatus != "") {
            this.form.unsafeStatus = this.form.unsafeStatus.toString();
          }
          if (this.form.unsafeAction != null && this.form.unsafeAction != "") {
            this.form.unsafeAction = this.form.unsafeAction.toString();
          }
          if (this.form.category != null && this.form.category != "") {
            this.form.category = Number(this.form.category);
          }
          this.fileList = [];
          if (this.form.files.length > 0) {
            console.log(this.form.files);
            for (let i = 0; i < this.form.files.length; i++) {
              let obj = {}
              obj.name = this.form.files[i].fileName
              obj.response = {};
              obj.response.msg = this.form.files[i].fileUrl
              this.fileList.push(obj)
            }
          }
          this.open = true;
          this.title = "修改SAI开项申请";
        });
      },
      /** 新增/修改保存按钮 */
      submitForm() {
        this.submitDisabled = true;
        this.form.files = []
        if (this.fileList.length > 0) {
          for (let i = 0; i < this.fileList.length; i++) {
            let obj = {}
            obj.fileName = this.fileList[i].name
            obj.fileUrl = this.fileList[i].response.msg
            this.form.files.push(obj)
          }
        }
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.saiApplyId != null) {
              updateApply(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.submitDisabled = false;
                this.getList();
              });
            } else {
              addApply(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.submitDisabled = false;
                this.getList();
              });
            }
          } else {
            this.submitDisabled = false;
          }
        });
      },
      /** 新增/修改提交按钮 */
      handleSaveAndSubmit() {
        this.submitDisabled = true;
        this.form.files = []
        if (this.fileList.length > 0) {
          for (let i = 0; i < this.fileList.length; i++) {
            let obj = {}
            obj.fileName = this.fileList[i].name
            obj.fileUrl = this.fileList[i].response.msg
            this.form.files.push(obj)
          }
        }
        this.$refs["form"].validate(valid => {
          if (valid) {
            saveAndSubmitApply(this.form).then(response => {
              this.msgSuccess("提交成功");
              this.submitDisabled = false;
              this.open = false;
              this.getList();
            });
          } else {
            this.submitDisabled = false;
          }
        });
      },
      /** 统计至SAI检查台账提交按钮 */
      submitSaiForm() {
        for (let i = 0; i < this.saiList.length; i++) {
          this.saiList[i].plantId = 103;
          this.saiList[i].userDept = 103;
          addSai(this.saiList[i]);
        }
        this.msgSuccess("提交成功");
        this.saiOpen = false;
      },
      /** 延期提交按钮 */
      submitDelayForm() {
        this.$refs["delayForm"].validate(valid => {
          if (valid) {
            updateApply(this.delayForm).then(response => {
              this.msgSuccess("延期成功");
              this.delayOpen = false;
              this.getList();
            });
          }
        });
      },
      /** 统计至SAI检查台账按钮操作 */
      handleAddSai(row) {
        const saiApplyIds = row.saiApplyId || this.ids;
        if(saiApplyIds.length != 0) {
          this.saiList = [];
          for (let i = 0; i < saiApplyIds.length; i ++) {
            getApply(saiApplyIds[i]).then(response => {
              let apply = response.data;
              let sai = {};
              sai.saiApplyId = apply.saiApplyId;
              sai.plantId = "CBP/C";
              sai.userDeptId = "CBP/C";
              sai.inspectionDate = apply.applyDate;
              sai.dificiency = apply.description;
              sai.actions = apply.reaction;
              sai.source = "装置";
              sai.deptId = 103;
              sai.saiLevel = apply.saiLevel;
              sai.category = Number(apply.category);
              sai.applicant = apply.applicant;
              sai.applicantName = apply.applicantName;
              this.saiList.push(sai);
            });
          }
          this.saiOpen = true;
        }
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const saiApplyIds = row.saiApplyId || this.ids;
        this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delApply(saiApplyIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出全部按钮操作 */
      handleExport() {
        this.queryParams.ids = null;
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有SAI开项管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportApply(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      },
      /** 导出选中数据按钮操作 */
      handleExportSelected() {
        if (this.ids.length==0){
          return this.$alert('请选择要导出的数据项！', "警告", {
            confirmButtonText: "确定",
            type: "warning"
          })
        }
        if (this.queryParams.workArea != null && this.queryParams.workArea != "") {
          this.queryParams.workArea = this.queryParams.workArea.join();
        } else {
          this.queryParams.workArea = "";
        }
        const queryParams = this.queryParams;
        queryParams.ids=this.ids;
        console.log(queryParams)
        this.$confirm('是否确认导出选中的SAI开项管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportApply(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "用户导入";
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        this.$refs['downloadFileForm'].submit()
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        if (response.data[0] != null) {
          this.$alert(this.$t('成功导入') + response.msg + this.$t('条数据') + "，" + this.$t('第') + response.data + this.$t('行数据出现错误导入失败')+"。", this.$t('导入结果'), { dangerouslyUseHTMLString: true });
        }else {
          this.$alert(this.$t('成功导入') + response.msg + this.$t('条数据'), this.$t('导入结果'), { dangerouslyUseHTMLString: true });
        }
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      }
    }
  };
</script>
