<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item :label="$t('MOC编号')" label-width="50" prop="mocNo">
        <el-input
          v-model="queryParams.mocNo"
          :placeholder="$t('请输入') + $t('MOC编号')"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('区域')" prop="area">
        <el-input
          v-model="queryParams.area"
          :placeholder="$t('请输入') + $t('区域')"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('标题')" prop="title">
        <el-input
          v-model="queryParams.title"
          :placeholder="$t('请输入') + $t('标题')"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('CTE工作号')" label-width="120" prop="cteNo">
        <el-input
          v-model="queryParams.cteNo"
          :placeholder="$t('请输入') + $t('CTE工作号')"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('实施情况')" prop="trueState" label-width="150">
        <el-select v-model="queryParams.trueState" :placeholder="$t('请选择') + $t('实施情况')" clearable size="small">
          <el-option
            v-for="dict in trueStateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('变更性质')" prop="changeNature" label-width="150">
        <el-select v-model="queryParams.changeNature" :placeholder="$t('请选择') + $t('变更性质')" clearable size="small">
          <el-option
            v-for="dict in changeNatureOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('搜索') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('重置') }}</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="['process:moc:add']"
        >{{ $t('新增') }}</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="['process:moc:edit']"
        >{{ $t('修改') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['process:moc:remove']"
        >{{ $t('删除') }}</el-button>
      </el-col>
        <el-col :span="1.5">
            <el-button
                    type="info"
                    icon="el-icon-upload2"
                    size="mini"
                    @click="handleImport"
                    v-hasPermi="['process:moc:edit']"
            >{{ $t('导入') }}</el-button>
        </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['process:moc:export']"
        >{{ $t('导出') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-s-data"
          size="mini"
          @click="handleData"
        >{{ $t('数据分析') }}</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="mocList" @selection-change="handleSelectionChange" :cell-style="tableCellStyle" :cell-class-name="tableCellClassName" :height="clientHeight" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="$t('MOC编号')" align="center" width="120" prop="mocNo" :show-overflow-tooltip="true"/>
      <!--<el-table-column :label="$t('装置编号')" align="center" width="120" prop="plantNumber" :show-overflow-tooltip="true"/>-->
      <el-table-column :label="$t('区域')" align="center" prop="area" :formatter="areaFormat" />
      <el-table-column :label="$t('标题')" align="center" width="320" prop="title" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('负责人')" align="center" prop="owner" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('申请时间')" align="center" prop="approveTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('完成时间')" align="center" prop="endtime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endtime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('实施情况')" align="center" prop="trueState" :formatter="trueStateFormat" />
      <el-table-column :label="$t('变更性质')" align="center" prop="changeNature" :formatter="changeNatureFormat" />
      <el-table-column :label="$t('到期时间')" align="center" prop="overTime" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.overTime !== 'N.A.'">{{ parseTime(scope.row.overTime, '{y}-{m}-{d}') }}</span>
          <span v-if="scope.row.overTime === 'N.A.'">{{ scope.row.overTime }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('临时MOC状态')" align="center" prop="temporaryState" :formatter="temporaryStateFormat" />
      <el-table-column :label="$t('备注')" align="center" prop="remarks" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('风险等级')" align="center" prop="riskLevel" :formatter="riskLevelFormat" />
      <el-table-column :label="$t('EHS审查')" align="center" width="130" prop="ehsCheck" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span> {{scope.row.ehsCheck}}</span>
          <el-button icon="el-icon-folder" style="color:#6e96fa" v-if="scope.row.ehsCheck !== null" @click="handleDoc(scope.row , 'moc-ehsCheck')"  circle></el-button>
        </template>
      </el-table-column>
      <el-table-column :label="$t('MOC培训')" align="center" width="130" prop="training" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span> {{scope.row.training}}</span>
          <el-button icon="el-icon-folder" style="color:#6e96fa;" v-if="scope.row.training !== null" @click="handleDoc(scope.row , 'moc-training')"  circle></el-button>
        </template>
      </el-table-column>
      <el-table-column label="PSSR" align="center" width="130" prop="pssr" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span> {{scope.row.pssr}}</span>
          <el-button icon="el-icon-folder" style="color:#6e96fa;" v-if="scope.row.pssr !== null" @click="handleDoc(scope.row , 'moc-pssr')"  circle></el-button>
        </template>
      </el-table-column>
      <el-table-column :label="$t('SOP更新')" align="center" prop="sopUpdate" :formatter="sopUpdateFormat" />
      <el-table-column :label="$t('PID更新')" align="center" prop="pidMaster" :formatter="pidMasterFormat" />

      <!--<el-table-column :label="$t('通知单')" align="center" prop="noticeLetter" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('工作单')" align="center" prop="workLetter" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('CTE工作号')" align="center" prop="cteNo" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('投资费用(RMB)')" align="center" prop="investCost" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('类别')" align="center" prop="category" :formatter="categoryFormat" />
      <el-table-column :label="$t('重要性')" align="center" prop="significance" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('分类')" align="center" width="120" prop="classification" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('仪表控制')" align="center" prop="dashControl" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('预计完成时间')" align="center" prop="estimateEndtime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.estimateEndtime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('EHS审查数据库')" align="center" prop="ehsDb" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('PSSR数据库')" align="center" prop="pssrDb" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('CAPEX计划')" align="center" prop="capex" :show-overflow-tooltip="true"/>-->
      <el-table-column :label="$t('操作')" align="center" fixed="right" width="120" 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="['process:moc:edit']"
          >{{ $t('修改') }}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['process:moc:remove']"
          >{{ $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"
    />

    <!-- 添加或修改MOC管理对话框 -->
    <el-dialog v-dialogDrag :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item :label="$t('装置名称')" prop="plantCode">
          <el-select v-model="form.plantCode" :placeholder="$t('请选择') + $t('装置名称')">
            <el-option
              v-for="dict in plantCodeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('MOC编号')" prop="mocNo">
          <el-input v-model="form.mocNo" :placeholder="$t('请输入') + $t('MOC编号')" />
        </el-form-item>
        <el-form-item :label="$t('区域')" prop="area">
          <el-select v-model="form.area" :placeholder="$t('请选择') + $t('区域')">
            <el-option
              v-for="dict in areaOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('标题')" prop="title">
          <el-input v-model="form.title" :placeholder="$t('请输入') + $t('标题')" />
        </el-form-item>
        <el-form-item :label="$t('负责人')" prop="owner">
          <el-input v-model="form.owner" :placeholder="$t('请输入') + $t('负责人')" />
        </el-form-item>
        <el-form-item :label="$t('申请时间')" prop="approveTime">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.approveTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          :placeholder="$t('请选择') + $t('申请时间')">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('完成时间')" prop="endtime">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.endtime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          :placeholder="$t('请选择') + $t('完成时间')">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('实施情况')" prop="trueState">
          <el-select v-model="form.trueState" :placeholder="$t('请选择') + $t('实施情况')" @change="changeTrueState($event)">
            <el-option
              v-for="dict in trueStateOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('变更性质')" prop="changeNature">
          <el-select v-model="form.changeNature" :placeholder="$t('请选择') + $t('变更性质')" @change="changeChangeNature($event)">
            <el-option
              v-for="dict in changeNatureOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('到期时间')" prop="overTime">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.overTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          :placeholder="$t('请选择') + $t('到期时间')">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('临时MOC状态')" prop="temporaryState">
          <el-select v-model="form.temporaryState" :placeholder="$t('请选择') + $t('临时MOC状态')">
            <el-option
              v-for="dict in temporaryStateOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('备注')" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" :placeholder="$t('请输入') + $t('备注')" />
        </el-form-item>
        <el-form-item :label="$t('风险等级')" prop="riskLevel">
          <el-select v-model="form.riskLevel" :placeholder="$t('请选择') + $t('风险等级')">
            <el-option
              v-for="dict in riskLevelOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('EHS审查')" prop="ehsCheck">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.ehsCheck"
                          type="date"
                          value-format="yyyy-MM-dd"
                          :placeholder="$t('请选择') + $t('EHS审查')">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('MOC培训')" prop="training">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.training"
                          type="date"
                          value-format="yyyy-MM-dd"
                          :placeholder="$t('请选择') + $t('MOC培训')"
                          :picker-options="trainingDatePicker">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="PSSR" prop="pssr">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.pssr"
                          type="date"
                          value-format="yyyy-MM-dd"
                          :placeholder="$t('请选择') + 'PSSR'"
                          :picker-options="pssrDatePicker">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('PID更新')" prop="pidMaster">
          <el-select v-model="form.pidMaster" :placeholder="$t('请选择') + $t('PID更新')">
            <el-option
              v-for="dict in pidMasterOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('SOP更新')" prop="sopUpdate">
          <el-select v-model="form.sopUpdate" :placeholder="$t('请选择') + $t('SOP更新')">
            <el-option
              v-for="dict in sopUpdateOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>

        <!--<el-form-item :label="$t('装置编号')" prop="plantNumber">
          <el-input v-model="form.plantNumber" :placeholder="$t('请输入') + $t('装置编号')" />
        </el-form-item>
        <el-form-item :label="$t('通知单')" prop="noticeLetter">
          <el-input v-model="form.noticeLetter" :placeholder="$t('请输入') + $t('通知单')" />
        </el-form-item>
        <el-form-item :label="$t('工作单')" prop="workLetter">
          <el-input v-model="form.workLetter" :placeholder="$t('请输入') + $t('工作单')" />
        </el-form-item>
        <el-form-item :label="$t('CTE工作号')" prop="cteNo">
          <el-input v-model="form.cteNo" :placeholder="$t('请输入') + $t('CTE工作号')" />
        </el-form-item>
        <el-form-item :label="$t('投资费用(RMB)')" prop="investCost">
          <el-input v-model="form.investCost" :placeholder="$t('请输入') + $t('投资费用(RMB)')" />
        </el-form-item>
        <el-form-item :label="$t('类别')" prop="category">
          <el-select v-model="form.category" :placeholder="$t('请选择') + $t('类别')">
            <el-option
              v-for="dict in categoryOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('重要性')" prop="significance">
          <el-input v-model="form.significance" :placeholder="$t('请输入') + $t('重要性')" />
        </el-form-item>
        <el-form-item :label="$t('分类')" prop="classification">
          <el-input v-model="form.classification" :placeholder="$t('请输入') + $t('分类')" />
        </el-form-item>
        <el-form-item :label="$t('仪表控制')" prop="dashControl">
          <el-input v-model="form.dashControl" :placeholder="$t('请输入') + $t('仪表控制')" />
        </el-form-item>
        <el-form-item :label="$t('预计完成时间')" prop="estimateEndtime">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.estimateEndtime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          :placeholder="$t('请选择') + $t('预计完成时间')">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('EHS审查数据库')" prop="ehsDb">
          <el-input v-model="form.ehsDb" :placeholder="$t('请输入') + $t('EHS审查数据库')" />
        </el-form-item>
        <el-form-item :label="$t('PSSR数据库')" prop="pssrDb">
          <el-input v-model="form.pssrDb" :placeholder="$t('请输入') + $t('PSSR数据库')" />
        </el-form-item>
        <el-form-item :label="$t('CAPEX计划')" prop="capex">
          <el-input v-model="form.capex" :placeholder="$t('请输入') + $t('CAPEX计划')" />
        </el-form-item>-->
        <el-form-item :label="$t('归属部门')" prop="deptId">
          <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" :placeholder="$t('请选择') + $t('归属部门')" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('确 定') }}</el-button>
        <el-button @click="cancel">{{ $t('取 消') }}</el-button>
      </div>
    </el-dialog>
      <!-- 用户导入对话框 -->
      <el-dialog v-dialogDrag :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">
                  {{ $t('将文件拖到此处，或') }}
                  <em>{{ $t('点击上传') }}</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">{{ $t('下载模板') }}</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">{{ $t('提示：仅允许导入“xls”或“xlsx”格式文件！') }}</div>
          </el-upload>
          <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitFileForm">{{ $t('确 定') }}</el-button>
              <el-button @click="upload.open = false">{{ $t('取 消') }}</el-button>
          </div>
      </el-dialog>
    <!-- 报告附件对话框 -->
    <el-dialog v-dialogDrag :title="doc.title" :visible.sync="doc.open" width="1000px" append-to-body >
      <el-upload v-hasPermi="['training:trainingrecords:file']"
                 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" width="220" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.fileName.endsWith('pdf')"
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleSee(scope.row)"
            >{{ $t('预览') }}</el-button>
            <el-button v-hasPermi="['training:trainingrecords:file']"  type="text" size="small" v-if="scope.row.isEdit" @click="save(scope.row)">{{ $t('保存') }}</el-button>
            <el-button type="text" size="small" v-if="scope.row.isEdit" @click="cancelFile(scope.row, scope.$index)">{{ $t('取消') }}</el-button>
<!--            <el-button v-hasPermi="['training:trainingrecords:file']" v-if="!scope.row.isEdit" @click="edit(scope.row)" icon="el-icon-edit" type="text" size="mini">编辑</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)"
              v-hasPermi="['training:trainingrecords:file']"
            >{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog v-dialogDrag :title="pdf.title" :visible.sync="pdf.open" width="1300px" 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 :src="pdf.pdfUrl" frameborder="0" width="100%" height="700px"></iframe>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <!--        <el-button type="primary" @click="submitFileForm">{{ $t('确 定') }}</el-button>-->
        <el-button @click="doc.open = false">{{ $t('返 回') }}</el-button>
      </div>
    </el-dialog>
    <el-drawer
      :title="$t('数据分析')"
      size="600px"
      :visible.sync="drawer"
      :direction="direction">
<!--      <el-row style="padding-left: 20px;">-->
<!--      <el-form :model="chartParams" :inline="true"  label-width="68px">-->
<!--        <el-form-item :label="$t('年份')" label-width="50" prop="year">-->
<!--          <el-select v-model="chartParams.year" placeholder="请选择年份" clearable size="small">-->
<!--            <el-option-->
<!--              v-for="item in yearOption"-->
<!--              :key="item"-->
<!--              :label="item"-->
<!--              :value="item"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item>-->
<!--          <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('搜索') }}</el-button>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--      </el-row>-->
      <el-row>
        <el-col>
          <el-card class="box-card" shadow="hover">
            <div slot="header" class="clearfix">
              <span>{{ $t('实施情况统计') }}</span>
            </div>
            <div class="text item">
              <true-state-data> </true-state-data>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-card class="box-card" shadow="hover">
            <div slot="header" class="clearfix">
              <span>{{ $t('申请统计') }}</span>
            </div>
            <div class="text item">
              <year-chart> </year-chart>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-card class="box-card" shadow="hover">
            <div slot="header" class="clearfix">
              <span>{{ $t('变更性质') +$t('空格')+ $t('统计') }}</span>
            </div>
            <div class="text item">
              <change-data> </change-data>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-card class="box-card" shadow="hover">
            <div slot="header" class="clearfix">
              <span>{{ $t('类别') +$t('空格')+ $t('统计') }}</span>
            </div>
            <div class="text item">
              <category-data> </category-data>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-card class="box-card" shadow="hover">
            <div slot="header" class="clearfix">
              <span>{{ $t('风险等级统计') }}</span>
            </div>
            <div class="text item">
              <risk-data></risk-data>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-drawer>
  </div>
</template>

<script>
import { listMoc, getMoc, delMoc, addMoc, updateMoc, exportMoc } from "@/api/process/moc";
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 YearChart from "./yearChart";
import TrueStateData from "./trueStateData";
import ChangeData from "./changeData";
import CategoryData from "./categoryData";
import RiskData from "./riskData";

import {addCommonfile, allFileList, delCommonfile, updateCommonfile} from "@/api/common/commonfile";

export default {
  name: "Moc",
  components: {RiskData, CategoryData, ChangeData, TrueStateData, YearChart, Treeselect},
  data() {
    return {
      drawer: false,
      direction: 'rtl',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // MOC管理表格数据
      mocList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      clientHeight:300,
      // 是否显示弹出层
      open: false,
      // 装置字典
      plantCodeOptions: [],
      // 类别字典
      categoryOptions: [],
      // 区域字典
      areaOptions: [],
      // PID MASTER更新字典
      pidMasterOptions: [],
      // 临时MOC状态字典
      temporaryStateOptions: [],
      // SOP更新字典
      sopUpdateOptions: [],
      // 实施情况字典
      trueStateOptions: [],
      // 变更性质字典
      changeNatureOptions: [],
      // 风险等级字典
      riskLevelOptions: [],
      //时间选择限制
      ehsCheckDate: '',
      trainingDatePicker: this.pickerOptionsTraining(),
      pssrDatePicker: this.pickerOptionsPssr(),
      // 用户导入参数
      upload: {
        //下载模板请求地址
        downloadAction: process.env.VUE_APP_BASE_API + '/common/template',
        //下载模板类型
        type: 'moc',
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/process/moc/importData"
      },
      // 报告附件参数
      doc: {
        file: "",
        // 是否显示弹出层（报告附件）
        open: false,
        // 弹出层标题（报告附件）
        title: "附件",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 报告附件上传位置编号
        ids: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/commonfile/uploadFile",
        commonfileList: null,
        queryParams: {
          pId: null,
          pType: 'moc'
        },
        pType: 'moc',
        pId: null,
        form: {}
      },
      pdf : {
        title: '',
        pdfUrl: '',
        numPages: null,
        open: false,
        pageNum: 1,
        pageTotalNum: 1,
        loadedRatio: 0,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        plantCode: null,
        mocNo: null,
        plantNumber: null,
        noticeLetter: null,
        workLetter: null,
        cteNo: null,
        investCost: null,
        category: null,
        significance: null,
        classification: null,
        area: null,
        dashControl: null,
        title: null,
        owner: null,
        approveTime: null,
        estimateEndtime: null,
        endtime: null,
        trueState: null,
        changeNature: null,
        overTime: null,
        riskLevel: null,
        training: null,
        pssr: null,
        ehsCheck: null,
        ehsDb: null,
        pidMaster: null,
        pssrDb: null,
        capex: null,
        remarks: null
      },
      chartParams: {
        year : 2021
      },
      yearOption: [2020,2021],
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      commonRules: {
        plantCode: [
          { required: true, message: this.$t('装置') + this.$t('不能为空'), trigger: "change" }
        ],
        trueState: [
          { required: true, message: this.$t('实施情况') + this.$t('不能为空'), trigger: "change" }
        ],
        deptId: [
          { required: true, message: this.$t('部门编号') + this.$t('不能为空'), trigger: "blur" }
        ]
      },
      chooseRules: {
        plantCode: [
          { required: true, message: this.$t('装置') + this.$t('不能为空'), trigger: "change" }
        ],
        mocNo: [
          { required: true, message: this.$t('MOC编号') + this.$t('不能为空'), trigger: "blur" }
        ],
        area: [
          { required: true, message: this.$t('区域') + this.$t('不能为空'), trigger: "change" }
        ],
        title: [
          { required: true, message: this.$t('标题') + this.$t('不能为空'), trigger: "blur" }
        ],
        owner: [
          { required: true, message: this.$t('负责人') + this.$t('不能为空'), trigger: "blur" }
        ],
        approveTime: [
          { required: true, message: this.$t('申请时间') + this.$t('不能为空'), trigger: "blur" }
        ],
        endtime: [
          { required: true, message: this.$t('完成时间') + this.$t('不能为空'), trigger: "blur" }
        ],
        trueState: [
          { required: true, message: this.$t('实施情况') + this.$t('不能为空'), trigger: "change" }
        ],
        overTime: [
          { required: true, message: this.$t('到期时间') + this.$t('不能为空'), trigger: "blur" }
        ],
        riskLevel: [
          { required: true, message: this.$t('风险等级') + this.$t('不能为空'), trigger: "change" }
        ],
        ehsCheck: [
          { required: true, message: this.$t('EHS审查') + this.$t('不能为空'), trigger: "blur" }
        ],
        pidMaster: [
          { required: true, message: this.$t('PID更新') + this.$t('不能为空'), trigger: "blur" }
        ],
        sopUpdate: [
          { required: true, message: this.$t('SOP更新') + this.$t('不能为空'), trigger: "blur" }
        ],
        deptId: [
          { required: true, message: this.$t('部门编号') + this.$t('不能为空'), trigger: "blur" }
        ]
      },
      temporaryRules: {
        overTime: [
          { required: true, message: this.$t('到期时间') + this.$t('不能为空'), trigger: "blur" }
        ],
        deptId: [
          { required: true, message: this.$t('部门编号') + this.$t('不能为空'), trigger: "blur" }
        ]
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
        this.$refs.tree.filter(val);
    }
   },
  created() {
    //设置表格高度对应屏幕高度
    this.$nextTick(() => {
        this.clientHeight = (document.body.clientHeight - 80) * 0.8
    })
    this.getList();
    this.getTreeselect();
    this.getDicts("PLANT_DIVIDE").then(response => {
      this.plantCodeOptions = response.data;
    });
    this.getDicts("MOC_CATEGORY").then(response => {
      this.categoryOptions = response.data;
    });
    this.getDicts("MOC_AREA").then(response => {
      this.areaOptions = response.data;
    });
    this.getDicts("YES_NO_EN").then(response => {
      this.pidMasterOptions = response.data;
    });
    this.getDicts("MOC_TEMPORARYSTATE").then(response => {
      this.temporaryStateOptions = response.data;
    });
    this.getDicts("YES_NO_EN").then(response => {
      this.sopUpdateOptions = response.data;
    });
    this.getDicts("MOC_STATE").then(response => {
      this.trueStateOptions = response.data;
    });
    this.getDicts("MOC_CHANGE").then(response => {
      this.changeNatureOptions = response.data;
    });
    this.getDicts("MOC_RISKLEVEL").then(response => {
      this.riskLevelOptions = response.data;
    });
  },
  methods: {
    /** 查询MOC管理列表 */
    getList() {
      this.loading = true;
      let _this = this
      listMoc(this.queryParams).then(response => {
        this.mocList = response.rows;
        this.mocList.forEach(function (value,key,arr) {
          if (value.overTime == null) {
            _this.mocList[key].overTime = "N.A."
          }
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    //根据分数显示颜色提示
    tableCellStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 3 && row.trueState == 10){
        return "color: rgba(45, 58, 79, 0.98) "
      }else if (columnIndex == 3 && row.trueState == 12){
        return "color: rgba(255, 26, 26, 0.98) "
      }else if (columnIndex == 3 && row.trueState == 14){
        return "color: rgba(95, 153, 248, 0.98) "
      }
    },
     /** 查询部门下拉树结构 */
     getTreeselect() {
          treeselect().then(response => {
              this.deptOptions = response.data;
          });
     },
    // 装置字典翻译
    plantCodeFormat(row, column) {
      return this.selectDictLabel(this.plantCodeOptions, row.plantCode);
    },
    // 类别字典翻译
    categoryFormat(row, column) {
      return this.selectDictLabel(this.categoryOptions, row.category);
    },
    // 实施情况字典翻译
    trueStateFormat(row, column) {
      return this.selectDictLabel(this.trueStateOptions, row.trueState);
    },
    // 变更性质字典翻译
    changeNatureFormat(row, column) {
      return this.selectDictLabel(this.changeNatureOptions, row.changeNature);
    },
    // 风险等级字典翻译
    riskLevelFormat(row, column) {
      return this.selectDictLabel(this.riskLevelOptions, row.riskLevel);
    },
    // 区域字典翻译
    areaFormat(row, column) {
      return this.selectDictLabel(this.areaOptions, row.area);
    },
    // PID MASTER更新字典翻译
    pidMasterFormat(row, column) {
      return this.selectDictLabel(this.pidMasterOptions, row.pidMaster);
    },
    // 临时MOC状态字典翻译
    temporaryStateFormat(row, column) {
      return this.selectDictLabel(this.temporaryStateOptions, row.temporaryState);
    },
    // SOP更新字典翻译
    sopUpdateFormat(row, column) {
      return this.selectDictLabel(this.sopUpdateOptions, row.sopUpdate);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        plantCode: null,
        mocNo: null,
        plantNumber: null,
        noticeLetter: null,
        workLetter: null,
        cteNo: null,
        investCost: null,
        category: null,
        significance: null,
        classification: null,
        area: null,
        dashControl: null,
        title: null,
        owner: null,
        approveTime: null,
        estimateEndtime: null,
        endtime: null,
        trueState: null,
        changeNature: null,
        overTime: null,
        riskLevel: null,
        training: null,
        pssr: null,
        ehsCheck: null,
        ehsDb: null,
        pidMaster: null,
        pssrDb: null,
        capex: null,
        delFlag: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        deptId: null,
        remarks: null,
        temporaryState: null,
        sopUpdate: null
      };
      this.resetForm("form");
    },
    // 限制时间范围
    pickerOptionsTraining() {
      const self = this
      return {
        disabledDate(time){
            return time.getTime() < new Date(self.form.ehsCheck).getTime()
        }
      }
    },
    pickerOptionsPssr() {
      const self = this
      return {
        disabledDate(time){
          if (self.form.training != null) {
            return time.getTime() < new Date(self.form.training).getTime()
          }else {
            return time.getTime() < new Date(self.form.ehsCheck).getTime()
          }
        }
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = this.$t('新增') + " " + this.$t('MOC管理');
    },
    //实施情况Finished变更
    changeTrueState(val) {
      if (val == 10) {
        this.rules = this.chooseRules
      }else {
        this.$refs['form'].clearValidate();
        this.rules = this.commonRules
      }
    },
    changeChangeNature(val) {
      if (val == 10) {
        this.rules = this.temporaryRules
      }else if (val = 12) {
        this.$refs['form'].clearValidate();
        this.form.temporaryState = "14";
        this.form.overTime = "";
        this.rules = this.commonRules
      }
    },
    //根据分数显示颜色提示
    tableCellClassName({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 13){
        return this.changeColor(row.isEhsCheck, row.ehsCheck)
      }
      if (columnIndex == 14){
        return this.changeColor(row.isTraining, row.training)
      }
      if (columnIndex == 15){
        return this.changeColor(row.isPssr, row.pssr)
      }
    },
    changeColor (value, dateValue) {
      if (value !== "1" && dateValue !== null){
        return 'cellMoc'
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.rules = this.commonRules
      const id = row.id || this.ids
      getMoc(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = this.$t('修改') + this.$t('MOC管理');
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.trueState == "10") {
            if (this.form.mocNo != null && this.form.plantNumber != null && this.form.category != null && this.form.significance != null && this.form.classification != null
              && this.form.area != null && this.form.title != null && this.form.owner != null && this.form.approveTime != null && this.form.estimateEndtime != null
              && this.form.endtime != null && this.form.changeNature != null && this.form.riskLevel != null && this.form.training != null && this.form.pssr != null) {
              if (this.form.id != null) {
                updateMoc(this.form).then(response => {
                  this.msgSuccess(this.$t('修改成功'));
                  this.open = false;
                  this.getList();
                });
              } else {
                addMoc(this.form).then(response => {
                  this.msgSuccess(this.$t('新增成功'));
                  this.open = false;
                  this.getList();
                });
              }
            } else {
              this.msgError(this.$t('存在必填项未填，实施情况修改Finished失败'));
            }
          }else {
            if (this.form.id != null) {
              updateMoc(this.form).then(response => {
                this.msgSuccess(this.$t('修改成功'));
                this.open = false;
                this.getList();
              });
            } else {
              addMoc(this.form).then(response => {
                this.msgSuccess(this.$t('新增成功'));
                this.open = false;
                this.getList();
              });
            }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: "warning"
        }).then(function() {
          return delMoc(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess(this.$t('删除成功'));
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm(this.$t('是否确认导出所有MOC管理数据项?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: "warning"
        }).then(function() {
          return exportMoc(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
      /** 导入按钮操作 */
      handleImport() {
          this.upload.title = this.$t('用户导入');
          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();
      },
      //数据分析
      handleData(){
        var now = new Date();
        var year = now.getFullYear(); //得到年份
        this.yearOption = [year-2 , year-1 ,year]
        this.drawer = true
      },
    /** 报告附件按钮操作 */
    handleDoc(row , fileType) {
      this.doc.pType = fileType
      this.doc.queryParams.pType = fileType
      this.doc.id = row.id;
      this.doc.title = row.title;
      this.doc.open = true;
      this.doc.queryParams.pId = row.id
      this.doc.pId = row.id
      this.getFileList()
      this.$nextTick(() => {
        this.$refs.doc.clearFiles()
      })
    },
    getFileList (){
      allFileList(this.doc.queryParams).then(response => {
        response.forEach(element => {
          element["isEdit"] = false
        });
        response.forEach(element => {
          element["isAdd"] = false
        });
        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()
    },
    // 文件下载处理
    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()
    },
    //pdf预览
    openPdf(){
        window.open(this.pdf.pdfUrl);//path是文件的全路径地址
      },
      handleSee (row){
        this.pdf.open =true
        this.pdf.title = row.fileName
        this.pdf.pdfUrl = process.env.VUE_APP_BASE_API +'/pdf/web/viewer.html?file=' + process.env.VUE_APP_BASE_API + row.fileUrl
      },
    // 取消
    cancelFile(row, index) {
      // 如果是新增的数据
      if (row.isAdd) {
        this.doc.commonfileList.splice(index, 1)
      } else {
        // 不是新增的数据  还原数据
        for (const i in row.oldRow) {
          row[i] = row.oldRow[i]
        }
        row.isEdit = false
      }
    },
    edit(row) {
      // 备份原始数据
      row['oldRow'] = JSON.parse(JSON.stringify(row));
      this.$nextTick(() => {
        row.isEdit = true;
      })
    },
    save(row) {
      row.isEdit = false;
      var that = this;
      that.loading = true;
      this.form = row;
      if (row.isAdd == true) {
        addCommonfile(this.form).then(response => {
          this.msgSuccess(this.$t('新增成功'));
          this.open = false;
          this.getList();
        });
      }else {
        updateCommonfile(this.form).then(response => {
          this.msgSuccess(this.$t('修改成功'));
          this.open = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    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('删除成功'));
      })
    },
  }
};
</script>
<style>
  .text {
    font-size: 14px;
  }
  .item {
    margin-bottom: 18px;
  }
  .clearfix {
    color: #1e1e1e;
  }
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 100%;
  }
  .el-drawer__body {
    overflow: auto;
  }
  .el-drawer__container ::-webkit-scrollbar {
    display: none;
  }
</style>
