<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item :label="$t('产品类别')" prop="productcategory">
        <el-select v-model="queryParams.productcategory" :placeholder="$t('请选择') + $t('产品类别')" clearable size="small" @change="handleQuery">
          <el-option
            v-for="dict in productcategoryOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('中文名称')" prop="cnName">
        <el-input
          v-model="queryParams.cnName"
          :placeholder="$t('请输入')+$t('中文名称')"
          clearable
          size="small"
          @input="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('是否三致物')" prop="cmr" label-width="80">
        <el-select v-model="cmrs" @change="handleQuery" :placeholder="$t('请选择')+$t('是否三致物')" clearable multiple size="small">
          <el-option
            v-for="dict in cmrOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('出版日期')" prop="issueTimeYear">
        <el-date-picker clearable size="small" style="width: 200px"
                        v-model="queryParams.issueTimeYear"
                        @change="handleQuery"
                        type="year"
                        value-format="yyyy"
                        :placeholder="$t('请选择') + $t('出版日期') + $t('年份')"
                        @input="handleQuery">
        </el-date-picker>
      </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="['ehs:msds: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="['ehs:msds: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="['ehs:msds: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="['ehs:msds: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="['ehs:msds:export']"
        >{{ $t('导出') }}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="msdsList" @selection-change="handleSelectionChange" :height="clientHeight" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ITEM" align="center" prop="item" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('产品类别')" align="center" prop="productcategory" :formatter="productcategoryFormat" />
      <el-table-column :label="$t('英文名称')" align="center" prop="enName" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('中文名称')" align="center" prop="cnName" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('CAS号')" align="center" prop="casNo" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('危险警句')" align="center" prop="hazardPhrases" width="300">
        <template slot-scope="scope">
          <span>{{ scope.row.hazardPhrases }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('是否三致物')" align="center" prop="cmr" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.cmr === null">Not</span>
          <span v-else>
            <span v-if="scope.row.cmrc === true" style="color: red">C</span>
            <span v-if="scope.row.cmrc === false">C</span>
            <span v-if="scope.row.cmrm === true" style="color: red">M</span>
            <span v-if="scope.row.cmrm === false">M</span>
            <span v-if="scope.row.cmrr === true" style="color: red">R</span>
            <span v-if="scope.row.cmrr === false">R</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('GHS符号')" align="center" width="410" prop="ghsPictogram">
        <template slot-scope="scope">
          <div style="display: flex">
            <div class="ghs" v-if="scope.row.irritating === true">
              <img src="@/assets/image/msds/irritating.jpg" class="ghsPictogram">
            </div>
            <div class="ghs" v-if="scope.row.oxidizing === true">
              <img src="@/assets/image/msds/oxidizing.jpg" class="ghsPictogram">
            </div>
            <div class="ghs" v-if="scope.row.toxicity === true">
              <img src="@/assets/image/msds/toxicity.jpg" class="ghsPictogram">
            </div>
            <div class="ghs" v-if="scope.row.corrosive === true">
              <img src="@/assets/image/msds/corrosive.jpg" class="ghsPictogram">
            </div>
            <div class="ghs" v-if="scope.row.healthHazard === true">
              <img src="@/assets/image/msds/healthHazard.jpg" class="ghsPictogram">
            </div>
            <div class="ghs" v-if="scope.row.aquaticEnvironment === true">
              <img src="@/assets/image/msds/aquaticEnvironment.jpg" class="ghsPictogram">
            </div>
            <div class="ghs" v-if="scope.row.gasPressure === true">
              <img src="@/assets/image/msds/gasPressure.jpg" class="ghsPictogram">
            </div>
            <div class="ghs" v-if="scope.row.flammability === true">
              <img src="@/assets/image/msds/flammability.jpg" class="ghsPictogram">
            </div>
            <div class="ghs" v-if="scope.row.sensitization === true">
              <img src="@/assets/image/msds/sensitization.jpg" class="ghsPictogram">
            </div>
            <div class="ghs" v-if="scope.row.toxicitySkeleton === true">
              <img src="@/assets/image/msds/toxicitySkeleton.jpg" class="ghsPictogram">
            </div>
            <div class="ghs" v-if="scope.row.explosive === true">
              <img src="@/assets/image/msds/explosive.jpg" class="ghsPictogram">
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('保存量')" align="center" prop="holdup" width="100" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('工作区域')" align="center" prop="workArea" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('形态')" align="center" prop="form" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('爆炸极限')+'(v%)'" align="center" prop="explosionLimit" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('熔点')+'(℃)'" align="center" prop="meltingPoint" width="100" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('沸点')+'(℃)'" align="center" prop="boilingPoint" width="100" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('密度/分子量')" align="center" prop="density" width="100" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('组成及纯度')+'(w/w)'" align="center" prop="purity" width="350" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('归属单位')" align="center" prop="responsibleCompany" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('出版日期')" align="center" prop="issueTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.issueTime, '{y}-{m}-{d}') }}</span>
          <span v-if="scope.row.issuetimeTwo !== null"><br/>{{ parseTime(scope.row.issuetimeTwo, '{y}-{m}-{d}') }}</span>
          <span v-if="scope.row.issuetimeThree !== null"><br/>{{ parseTime(scope.row.issuetimeThree, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('版次')" align="center" prop="version" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('回顾人')" align="center" prop="reviewerName" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('回顾日期')" align="center" prop="reviewdate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reviewdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('回顾状态')" align="center" prop="reviewState" :formatter="reviewStateFormat"/>
      <el-table-column :label="$t('下次回顾日期')" align="center" prop="nextReviewdate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.nextReviewdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('操作')" align="center" fixed="right" width="180" 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="['ehs:msds:edit']"
          >{{ $t('修改') }}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ehs:msds:remove']"
          >{{ $t('删除') }}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleDoc(scope.row)"
            v-hasPermi="['ehs:msds:edit']"
          >{{ $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"
    />

    <!-- 添加或修改MSDS管理对话框 -->
    <el-dialog  :close-on-click-modal="false" v-dialogDrag :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="ITEM" prop="item">
              <el-input v-model="form.item" :placeholder="$t('请输入') + 'ITEM'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('产品类别')" prop="productcategory">
              <el-select v-model="form.productcategory" :placeholder="$t('请选择') + $t('产品类别')">
                <el-option
                  v-for="dict in productcategoryOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('英文名称')" prop="enName">
              <el-input v-model="form.enName" :placeholder="$t('请输入') + $t('英文名称')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('中文名称')" prop="cnName">
              <el-input v-model="form.cnName" :placeholder="$t('请输入') + $t('中文名称')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('CAS号')" prop="casNo">
              <el-input v-model="form.casNo" :placeholder="$t('请输入') + $t('CAS号')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('危险警句')" prop="hazardPhrases">
              <el-select v-model="hazardPhrasess" multiple filterable :placeholder="$t('请选择') + $t('危险警句')">
                <el-option
                  v-for="dict in hazardPhrasesOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('是否三致物')" prop="cmr">
              <el-select v-model="form.cmr" multiple :placeholder="$t('请选择') + $t('是否三致物')">
                <el-option
                  v-for="dict in cmrOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('GHS符号')" prop="ghsPictogram">
              <el-select v-model="ghsPictograms" multiple :placeholder="$t('请选择') + $t('GHS符号')">
                <el-option
                  v-for="dict in ghsPictogramOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('保存量')" prop="holdup">
              <el-input v-model="form.holdup" :placeholder="$t('请输入') + $t('保存量')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('工作区域')" prop="workArea">
              <el-select v-model="workAreas" multiple :placeholder="$t('请选择') + $t('工作区域')">
                <el-option
                  v-for="dict in workAreaOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('形态')" prop="form">
              <el-input v-model="form.form" :placeholder="$t('请输入') + $t('形态')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('爆炸极限') + '(v%)'" prop="explosionLimit">
              <el-input v-model="form.explosionLimit" :placeholder="$t('请输入') + $t('爆炸极限')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('熔点') + '(℃)'" prop="meltingPoint">
              <el-input v-model="form.meltingPoint" :placeholder="$t('请输入') + $t('熔点')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('沸点') + '(℃)'" prop="boilingPoint">
              <el-input v-model="form.boilingPoint" :placeholder="$t('请输入') + $t('沸点')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('密度/分子量')" prop="density">
              <el-input v-model="form.density" :placeholder="$t('请输入') + $t('密度/分子量')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('组成及纯度') + '(w/w)'" prop="purity">
              <el-input type="textarea" v-model="form.purity" :placeholder="$t('请输入') + $t('组成及纯度')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('归属单位')" prop="responsibleCompany">
              <el-input v-model="form.responsibleCompany" :placeholder="$t('请输入') + $t('归属单位')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('出版日期') + '1'" prop="issueTime">
              <el-date-picker clearable size="small" style="width: 200px"
                              v-model="form.issueTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              :placeholder="$t('请选择') + $t('出版日期') + '1'">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('版次')" prop="version">
              <el-input v-model="form.version" :placeholder="$t('请输入') + $t('版次')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('回顾人')" prop="reviewer">
              <el-select v-model="form.reviewer" filterable :placeholder="$t('请选择') + $t('回顾人')">
                <el-option
                  v-for="dict in stffmgrOptions"
                  :key="dict.staffid"
                  :label="dict.name"
                  :value="dict.staffid">
                  <span style="float: left">{{ dict.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.staffid }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('回顾日期')" prop="reviewdate">
              <el-date-picker clearable size="small" style="width: 200px"
                              v-model="form.reviewdate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              :placeholder="$t('请选择') + $t('回顾日期')">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('回顾状态')" prop="reviewState">
              <el-select v-model="form.reviewState" :placeholder="$t('请选择') + $t('回顾状态')">
                <el-option
                  v-for="dict in reviewStateOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('下次回顾日期')" prop="nextReviewdate">
              <el-date-picker clearable size="small" style="width: 200px"
                              v-model="form.nextReviewdate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              :placeholder="$t('请选择') + $t('下次回顾日期')">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('备注')" prop="remarks">
              <el-input v-model="form.remarks" :placeholder="$t('请输入') + $t('备注')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('归属部门')" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" :placeholder="$t('请选择') + $t('归属部门')" />
            </el-form-item>
          </el-col>
        </el-row>
        <!--<el-form-item label="出版日期2" prop="issuetimeTwo">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.issuetimeTwo"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择出版日期2">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="出版日期3" prop="issuetimeThree">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.issuetimeThree"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择出版日期3">
          </el-date-picker>
        </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  :close-on-click-modal="false" 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 + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          {{ $t('将文件拖到此处，或') }}
          <em>{{ $t('点击上传') }}</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <!--<el-checkbox v-model="upload.updateSupport" />{{ $t('是否更新已经存在的用户数据') }}-->
          <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  :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" width="150" 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
              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>
      <el-dialog  :close-on-click-modal="false" 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>
  </div>
</template>

<script>
  import { listMsds, getMsds, delMsds, addMsds, updateMsds, exportMsds, importTemplate} from "@/api/ehs/msds";
  import { treeselect } from "@/api/system/dept";
  import {allFileList, delCommonfile} from "@/api/common/commonfile";
  import { getToken } from "@/utils/auth";
  import { listStaffmgr } from "@/api/plant/staffmgr";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";


  export default {
    name: "Msds",
    components: { Treeselect },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: false,
        // 总条数
        total: 0,
        // MSDS管理表格数据
        msdsList: [],
        // 弹出层标题
        title: "",
        // 部门树选项
        deptOptions: undefined,
        clientHeight:300,
        // 是否显示弹出层
        open: false,
        //表格数组
        hazardPhrasess: [],
        workAreas: [],
        ghsPictograms: [],
        // GHS符号字典
        stffmgrOptions: undefined,
        // 产品类别字典
        productcategoryOptions: [],
        // 危险警句字典
        hazardPhrasesOptions: [],
        // 是否三致物字典
        cmrOptions: [],
        // GHS符号字典
        ghsPictogramOptions: [],
        // 工作区域字典
        workAreaOptions: [],
        // 回顾状态字典
        reviewStateOptions: [],
        // 用户导入参数
        upload: {
          downloadAction: process.env.VUE_APP_BASE_API + '/common/template',
          //下载模板类型
          type: "msds",
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/ehs/msds/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: 'msds'
          },
          pType: 'msds',
          pId: null
        },
        pdf : {
          title: '',
          pdfUrl: '',
          numPages: null,
          open: false,
          pageNum: 1,
          pageTotalNum: 1,
          loadedRatio: 0,
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 20,
          enName: null,
          cnName: null,
          casNo: null,
          hazardPhrases: null,
          cmr: null,
          cmrs: null,
          ghsPictogram: null,
          holdup: null,
          workArea: null,
          form: null,
          explosionLimit: null,
          meltingPoint: null,
          boilingPoint: null,
          density: null,
          purity: null,
          responsibleCompany: null,
          issueTime: null,
          issueTimeYear: null,
          version: null,
          reviewer: null,
          reviewdate: null,
          reviewState: null,
          nextReviewdate: null
        },
        // 表单参数
        form: {},
        //筛选多选
        cmrs: [],
        // 表单校验
        rules: {
          item: [
            { required: true, message: "ITEM" + this.$t('不能为空'), trigger: "blur" }
          ],
          productcategory: [
            { required: true, message: this.$t('产品类别') + this.$t('不能为空'), trigger: "change" }
          ],
          enName: [
            { required: true, message: this.$t('英文名称') + this.$t('不能为空'), trigger: "blur" }
          ],
          cnName: [
            { required: true, message: this.$t('中文名称') + this.$t('不能为空'), trigger: "blur" }
          ],
          casNo: [
            { required: true, message: this.$t('CAS号') + this.$t('不能为空'), trigger: "blur" }
          ],
          holdup: [
            { required: true, message: this.$t('保存量') + this.$t('不能为空'), trigger: "blur" }
          ],
          form: [
            { required: true, message: this.$t('形态') + this.$t('不能为空'), trigger: "blur" }
          ],
          explosionLimit: [
            { required: true, message: this.$t('爆炸极限') + this.$t('不能为空'), trigger: "blur" }
          ],
          meltingPoint: [
            { required: true, message: this.$t('熔点') + this.$t('不能为空'), trigger: "blur" }
          ],
          boilingPoint: [
            { required: true, message: this.$t('沸点') + this.$t('不能为空'), trigger: "blur" }
          ],
          density: [
            { required: true, message: this.$t('密度/分子量') + this.$t('不能为空'), trigger: "blur" }
          ],
          purity: [
            { required: true, message: this.$t('组成及纯度') + this.$t('不能为空'), trigger: "blur" }
          ],
          responsibleCompany: [
            { required: true, message: this.$t('归属单位') + this.$t('不能为空'), trigger: "blur" }
          ],
          issueTime: [
            { required: true, message: this.$t('出版日期') + this.$t('不能为空'), trigger: "blur" }
          ],
          version: [
            { required: true, message: this.$t('版次') + this.$t('不能为空'), trigger: "blur" }
          ],
          reviewer: [
            { required: true, message: this.$t('回顾人') + this.$t('不能为空'), trigger: "blur" }
          ],
          reviewdate: [
            { required: true, message: this.$t('回顾日期') + this.$t('不能为空'), trigger: "blur" }
          ],
          reviewState: [
            { required: true, message: this.$t('回顾状态') + this.$t('不能为空'), trigger: "change" }
          ],
          nextReviewdate: [
            { 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.getStaffmar();
      //设置表格高度对应屏幕高度
      this.$nextTick(() => {
        this.clientHeight = document.body.clientHeight -250
      })
      this.getTreeselect();
      this.getDicts("PRODUCT_CATEGORY").then(response => {
        this.productcategoryOptions = response.data;
      });
      this.getDicts("HAZARD_PHRASES").then(response => {
        this.hazardPhrasesOptions = response.data;
      });
      this.getDicts("CMR").then(response => {
        this.cmrOptions = response.data;
      });
      this.getDicts("GHS_PICTOGRAM").then(response => {
        this.ghsPictogramOptions = response.data;
      });
      this.getDicts("WORK_AREA").then(response => {
        this.workAreaOptions = response.data;
      });
      this.getDicts("REVIEW_STATE").then(response => {
        this.reviewStateOptions = response.data;
      });
    },
    methods: {
      /** 查询MSDS管理列表 */
      getList() {
        let _this=this;
        this.loading = true;
        this.queryParams.cmrs = this.cmrs.join()
        listMsds(this.queryParams).then(response => {
          this.msdsList = response.rows;
          this.msdsList.forEach(function (value,key,arr) {
            var parentName = null;

            var workAreaid = null;
            var workAreaName = null;
            let hazardPhrasesid = null;
            let hazardPhrasesName = null;

            if (value.workArea != null) {
              workAreaid = value.workArea.split(',');
              workAreaid.forEach(function (value, key, arr) {
                if (key != 0) {
                  workAreaName = workAreaName + "," + _this.selectDictLabel(_this.workAreaOptions, value);
                }else if (key == 0) {
                  workAreaName = _this.selectDictLabel(_this.workAreaOptions, value);
                }
              })
            }
            if (value.hazardPhrases != null) {
              hazardPhrasesid = value.hazardPhrases.split(',');
              hazardPhrasesid.forEach(function (value, key, arr) {
                if (key != 0) {
                  hazardPhrasesName = hazardPhrasesName + "\n" + _this.selectDictLabel(_this.hazardPhrasesOptions, value);
                }else if (key == 0) {
                  hazardPhrasesName = _this.selectDictLabel(_this.hazardPhrasesOptions, value);
                }
              })
            }

            _this.msdsList[key].workAreaid = value.workArea;
            _this.msdsList[key].workArea = workAreaName;
            _this.msdsList[key].hazardPhrasesid = value.hazardPhrases;
            _this.msdsList[key].hazardPhrases = hazardPhrasesName;

            /** GHS符号判断 **/
            var ghsPictogram = null;
            if (value.ghsPictogram != null) {
              ghsPictogram = value.ghsPictogram.split(',');
              ghsPictogram.forEach(function (value) {
                if (value === '10') {
                  _this.msdsList[key].irritating = true
                }if (value === '12') {
                  _this.msdsList[key].toxicity = true
                }if (value === '14') {
                  _this.msdsList[key].corrosive = true
                }if (value === '16') {
                  _this.msdsList[key].healthHazard = true
                }if (value === '18') {
                  _this.msdsList[key].aquaticEnvironment = true
                }if (value === '20') {
                  _this.msdsList[key].gasPressure = true
                }if (value === '22') {
                  _this.msdsList[key].flammability = true
                }if (value === '24') {
                  _this.msdsList[key].sensitization = true
                }if (value === '26') {
                  _this.msdsList[key].oxidizing = true
                }if (value === '28') {
                  _this.msdsList[key].toxicitySkeleton = true
                }if (value === '30') {
                  _this.msdsList[key].explosive = true
                }
              })
            }
            /** CMR判断 **/
            var cmr = null;
            if (value.cmr != null) {
              cmr = value.cmr.split(',');
              cmr.forEach(function (value) {
                if (value === '1') {
                  _this.msdsList[key].cmrc = true
                }if (value === '2') {
                  _this.msdsList[key].cmrm = true
                }if (value === '3') {
                  _this.msdsList[key].cmrr = true
                }
              })
            }
          })
          this.total = response.total;
          this.loading = false;
        });
      },
      //获取人员表
      getStaffmar() {
        listStaffmgr(this.staffmgrQueryParams).then(response => {
          this.stffmgrOptions = response.rows;
          this.getList();
        });
      },
      //遍历人员表
      forEachStaffmar(id) {
        let stffmgrName = "";
        this.stffmgrOptions.forEach(function (item) {
          if (item.staffid === id) {
            stffmgrName = item.name
          }
        });
        return stffmgrName
      },

      /** 查询部门下拉树结构 */
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data;
        });
      },
      // 产品类别字典翻译
      productcategoryFormat(row, column) {
        return this.selectDictLabel(this.productcategoryOptions, row.productcategory);
      },
      // 危险警句字典翻译
      hazardPhrasesFormat(row, column) {
        return this.selectDictLabel(this.hazardPhrasesOptions, row.hazardPhrases);
      },
      // 是否三致物字典翻译
      cmrFormat(row, column) {
        return this.selectDictLabel(this.cmrOptions, row.cmr);
      },
      // GHS符号字典翻译
      ghsPictogramFormat(row, column) {
        return this.selectDictLabel(this.ghsPictogramOptions, row.ghsPictogram);
      },
      // 工作区域字典翻译
      workAreaFormat(row, column) {
        return this.selectDictLabel(this.workAreaOptions, row.workArea);
      },
      // 回顾状态字典翻译
      reviewStateFormat(row, column) {
        return this.selectDictLabel(this.reviewStateOptions, row.reviewState);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          item: null,
          productcategory: null,
          enName: null,
          cnName: null,
          casNo: null,
          deptId: null,
          delFlag: null,
          hazardPhrases: null,
          remarks: null,
          cmr: null,
          ghsPictogram: null,
          createrCode: null,
          holdup: null,
          createdate: null,
          updaterCode: null,
          workArea: null,
          updatedate: null,
          form: null,
          explosionLimit: null,
          meltingPoint: null,
          boilingPoint: null,
          density: null,
          purity: null,
          responsibleCompany: null,
          issueTime: null,
          issuetimeTwo: null,
          issuetimeThree: null,
          version: null,
          reviewer: null,
          reviewdate: null,
          reviewState: null,
          nextReviewdate: null,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.cmrs = []
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.hazardPhrasess = [];
        this.ghsPictograms = [];
        this.workAreas = [];
        this.open = true;
        this.title = this.$t('添加')+this.$t('MSDS管理');
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getMsds(id).then(response => {
          this.form = response.data;
          if (this.form.ghsPictogram != null) {
            this.ghsPictograms = this.form.ghsPictogram.split(',');
          }else{
            this.ghsPictograms = [];
          }

          if (this.form.hazardPhrases != null) {
            this.hazardPhrasess = this.form.hazardPhrases.split(',');
          }else{
            this.hazardPhrasess = [];
          }

          if (this.form.cmr != null) {
            this.form.cmr = this.form.cmr.split(',');
          }else{
            this.form.cmr = [];
          }

          if (this.form.workArea != null) {
            this.workAreas = this.form.workArea.split(',');
          }else {
            this.workAreas = [];
          }
          this.open = true;
          this.title = this.$t('修改')+this.$t('MSDS管理');
        });

      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            var ha = null;
            if (this.hazardPhrasess != null) {
              this.hazardPhrasess.forEach(function (value,key,arr) {
                if (key != 0) {
                  ha = ha + "," + value;
                }else if (key == 0) {
                  ha = value;
                }
              })
              this.form.hazardPhrases = ha;
            }

            var wo = null;
            if (this.workAreas != null) {
              this.workAreas.forEach(function (value,key,arr) {
                if (key != 0) {
                  wo = wo + "," + value;
                }else if (key == 0) {
                  wo = value;
                }
              })
              this.form.workArea = wo;
            }

            var cmr = null;
            if (this.form.cmr != null) {
              this.form.cmr.forEach(function (value,key,arr) {
                if (key != 0) {
                  cmr = cmr + "," + value;
                }else if (key == 0) {
                  cmr = value;
                }
              })
              this.form.cmr = cmr;
            }

            var ghs = null;
            if (this.ghsPictograms != null) {
              this.ghsPictograms.forEach(function (value,key,arr) {
                if (key != 0) {
                  ghs = ghs + "," + value;
                }else if (key == 0) {
                  ghs = value;
                }
              })
              this.form.ghsPictogram = ghs;
            }

            if (this.form.id != null) {
              updateMsds(this.form).then(response => {
                this.msgSuccess(this.$t('修改成功'));
                this.open = false;
                this.getList();
              });
            } else {
              addMsds(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 delMsds(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess(this.$t('删除成功'));
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm(this.$t('是否确认导出所有MSDS管理数据项?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: "warning"
        }).then(function() {
          return exportMsds(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();
      },
      /** 报告附件按钮操作 */
      handleDoc(row) {
        this.doc.id = row.id;
        this.doc.title = row.filename;
        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 => {
          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()
      },
      /** 删除按钮操作 */
      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('删除成功'));
        })
      },
      // 文件下载处理
      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
      },

    }
  };
</script>

<style scoped>
  .ghsPictogram {
    width: 70px !important;
    height: 112px !important;
  }

  .ghs {
    margin-left: 1px;
  }

  /deep/.el-table .cell {
    white-space: pre-line;
  }
</style>
