<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="创建日期" prop="createdate">
        <el-date-picker clearable size="small" style="width: 200px" v-model="queryParams.createdate" type="date"
                        value-format="yyyy-MM-dd" placeholder="选择创建日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="危害物质名称" prop="matterName">
        <el-input v-model="queryParams.matterName" placeholder="请输入危害物质名称" clearable size="small"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['ehs:matter:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['ehs:matter:edit']">修改
        </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:matter:remove']">删除
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">
              <el-button
                type="info"
                icon="el-icon-upload2"
                size="mini"
                @click="handleImport"
                v-hasPermi="['ehs:matter:edit']"
              >导入
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="['ehs:matter:export']"
              >导出
              </el-button>
            </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="matterList" @selection-change="handleSelectionChange" :height="clientHeight"
              border>
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="编号" align="center" prop="id" :show-overflow-tooltip="true"/>
      <el-table-column label="危害物质名称" align="center" prop="matterName" :show-overflow-tooltip="true"/>
      <el-table-column label="相关危害集合" align="center" prop="matterFeaturesName" :show-overflow-tooltip="true"/>
      <el-table-column label="相关防护措施集合" align="center" prop="matterProtectsName" :show-overflow-tooltip="true"/>
      <el-table-column label="备注" align="center" prop="remarks" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" fixed="right" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['ehs:matter:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['ehs:matter:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加或修改危害物质数据关联对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="危害物质名称" prop="matterName">
          <el-input v-model="form.matterName" placeholder="请输入危害物质名称" style="width: 200px;"/>
        </el-form-item>
        <el-form-item label="请选择相关危害">
          <table>
            <tr style="text-align: center;">
              <td style="width: 80px;">
                <el-image style="width: 70px;height: 70px;" :src="require('@/assets/image/toxicIcon.png')">
                </el-image>
              </td>
              <td style="width: 80px;">
                <el-image style="width: 70px;height: 70px;" :src="require('@/assets/image/flammableIcon.png')">
                </el-image>
              </td>
              <td style="width: 80px;">
                <el-image style="width: 70px;height: 70px;" :src="require('@/assets/image/oxidizingIcon.png')">
                </el-image>
              </td>
              <td style="width: 80px;">
                <el-image style="width: 70px;height: 70px;" :src="require('@/assets/image/explosiveIcon.png')">
                </el-image>
              </td>
              <td style="width: 80px;">
                <el-image style="width: 70px;height: 70px;" :src="require('@/assets/image/corrosiveIcon.png')">
                </el-image>
              </td>
              <td style="width: 80px;">
                <el-image style="width: 70px;height: 70px;"
                          :src="require('@/assets/image/irritantSensitizationToxicIcon.png')">
                </el-image>
              </td>
              <td style="width: 80px;">
                <el-image style="width: 70px;height: 70px;" :src="require('@/assets/image/healthHazardIcon.png')">
                </el-image>
              </td>
              <td style="width: 80px;">
                <el-image style="width: 70px;height: 70px;" :src="require('@/assets/image/compressedGasIcon.png')">
                </el-image>
              </td>
              <td style="width: 80px;">
                <el-image style="width: 70px;height: 70px;"
                          :src="require('@/assets/image/environmentalHazardIcon.png')">
                </el-image>
              </td>
            </tr>
            <tr style="text-align: center;">
              <td style="width: 50px;">毒性<br>
                <el-checkbox v-model="cIsToxic" true-label="1" false-label="0"/>
              </td>
              <td style="width: 50px;">易燃性<br>
                <el-checkbox v-model="cIsFlammable" true-label="1" false-label="0"/>
              </td>
              <td style="width: 50px;">氧化性<br>
                <el-checkbox v-model="cIsOxidizing" true-label="1" false-label="0"/>
              </td>
              <td style="width: 50px;">爆炸性<br>
                <el-checkbox v-model="cIsExplosive" true-label="1" false-label="0"/>
              </td>
              <td style="width: 50px;">腐蚀性<br>
                <el-checkbox v-model="cIsCorrosive" true-label="1" false-label="0"/>
              </td>
              <td style="width: 120px;">刺激性/致敏性/毒性<br>
                <el-checkbox v-model="cIsIrritantToxic" true-label="1" false-label="0"/>
              </td>
              <td style="width: 70px;">健康危害<br>
                <el-checkbox v-model="cIsHealthHazard" true-label="1" false-label="0"/>
              </td>
              <td style="width: 70px;">压力下气体<br>
                <el-checkbox v-model="cIsCompressedGas" true-label="1" false-label="0"/>
              </td>
              <td style="width: 90px;">危害水生环境<br>
                <el-checkbox v-model="cIsEnvironmentalHazard" true-label="1" false-label="0"/>
              </td>
            </tr>
          </table>
        </el-form-item>
        <el-form-item label="请选择相关防护用品">
          <table>
            <tr>
              <td>
                防护眼镜
              </td>
              <td>
                <el-select v-model="protectGlove" placeholder="请选择防护眼镜">
                  <el-option v-for="dict in protectGloves" :key="dict.id" :label="dict.conservatoryMeasureName"
                             :value="dict.id">
                  </el-option>
                </el-select>
              </td>
            </tr>
            <tr>
              <td>
                防护手套
              </td>
              <td>
                <el-select v-model="safeGoggle" placeholder="请选择防护手套">
                  <el-option v-for="dict in safeGoggles" :key="dict.id" :label="dict.conservatoryMeasureName"
                             :value="dict.id">
                  </el-option>
                </el-select>
              </td>
            </tr>
            <tr>
              <td>
                防护面罩
              </td>
              <td>
                <el-select v-model="resProtect" placeholder="请选择防护面罩">
                  <el-option v-for="dict in resProtects" :key="dict.id" :label="dict.conservatoryMeasureName"
                             :value="dict.id">
                  </el-option>
                </el-select>
              </td>
            </tr>
            <tr>
              <td>
                防护靴
              </td>
              <td>
                <el-select v-model="rubberBoot" placeholder="请选择防护靴">
                  <el-option v-for="dict in rubberBoots" :key="dict.id" :label="dict.conservatoryMeasureName"
                             :value="dict.id">
                  </el-option>
                </el-select>
              </td>
            </tr>
            <tr>
              <td>
                防护服
              </td>
              <td>
                <el-select v-model="protectSuit" placeholder="请选择防护服">
                  <el-option v-for="dict in protectSuits" :key="dict.id" :label="dict.conservatoryMeasureName"
                             :value="dict.id">
                  </el-option>
                </el-select>
              </td>
            </tr>
          </table>
        </el-form-item>
        <!-- <el-form-item label="相关危害集合" prop="matterFeatures">
          <el-input v-model="form.matterFeatures" placeholder="请输入相关危害集合" />
        </el-form-item>
        <el-form-item label="相关防护措施集合" prop="matterProtects">
          <el-input v-model="form.matterProtects" placeholder="请输入相关防护措施集合" />
        </el-form-item> -->
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注" style="width: 500px;"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                 :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport"/>
          是否更新已经存在的用户数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMatter,
  getMatter,
  delMatter,
  addMatter,
  updateMatter,
  exportMatter,
  importTemplate
} from "@/api/configuration/matter";
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 {
  getForType, getProtect
} from "@/api/configuration/protect";

export default {
  name: "Matter",
  components: {
    Treeselect
  },
  data() {
    return {
      protectGlove: null,
      protectGlovesParams: {
        protectType: '2',
      },
      protectGloves: [], //防护眼镜
      safeGoggle: null,
      safeGogglesParams: {
        protectType: '1',
      },
      safeGoggles: [], //防护手套
      resProtect: null,
      resProtectsParams: {
        protectType: '3',
      },
      resProtects: [], //防护面罩
      rubberBoot: null,
      rubberBootsParams: {
        protectType: '4',
      },
      rubberBoots: [], //防护靴
      protectSuit: null,
      protectSuitsParams: {
        protectType: '5',
      },
      protectSuits: [], //防护服
      cIsToxic: null,
      cIsFlammable: null,
      cIsOxidizing: null,
      cIsExplosive: null,
      cIsCorrosive: null,
      cIsIrritantToxic: null,
      cIsHealthHazard: null,
      cIsCompressedGas: null,
      cIsEnvironmentalHazard: null,
      matterFeatures: [],
      matterProtects: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 危害物质数据关联表格数据
      matterList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      clientHeight: 300,
      // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken()
        },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/ehs/matter/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        matterName: null,
        matterType: null,
        matterFeatures: null,
        matterProtects: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        matterName: [{
          required: true,
          message: "物料名称不能为空",
          trigger: "blur"
        }],
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    //设置表格高度对应屏幕高度
    this.$nextTick(() => {
      this.clientHeight = document.body.clientHeight - 250
    })
    this.getList();
    this.getTreeselect();
    this.getAllProtect();
  },
  methods: {
    /* 获取所有的防护措施 */
    getAllProtect() {
      getForType(this.protectGlovesParams).then(response => {
        this.protectGloves = response.data;
      });
      getForType(this.safeGogglesParams).then(response => {
        this.safeGoggles = response.data;
      });
      getForType(this.resProtectsParams).then(response => {
        this.resProtects = response.data;
      });
      getForType(this.rubberBootsParams).then(response => {
        this.rubberBoots = response.data;
      });
      getForType(this.protectSuitsParams).then(response => {
        this.protectSuits = response.data;
      });
    },
    /** 查询危害物质数据关联列表 */
    getList() {
      this.loading = true;
      listMatter(this.queryParams).then(response => {
        this.matterList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.matterList.forEach(ml => {
          ml.matterFeaturesName = '';
          ml.matterFeatures.split(',').forEach(mf => {
            ml.matterFeaturesName += this.getMatterFeatureName(parseInt(mf)) + '、';
          })
          if (ml.matterFeaturesName != '') {
            ml.matterFeaturesName = ml.matterFeaturesName.substring(0, ml.matterFeaturesName.length - 1)
          }
        })
        console.log(this.matterList)
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.cIsToxic = null;
      this.cIsFlammable = null;
      this.cIsOxidizing = null;
      this.cIsExplosive = null;
      this.cIsCorrosive = null;
      this.cIsIrritantToxic = null;
      this.cIsHealthHazard = null;
      this.cIsCompressedGas = null;
      this.cIsEnvironmentalHazard = null;
      this.protectGlove=null;
      this.rubberBoot=null;
      this.protectSuit=null;
      this.resProtect=null;
      this.safeGoggle=null;
      this.form = {
        id: null,
        delFlag: null,
        matterName: null,
        matterType: null,
        matterFeatures: null,
        matterProtects: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加危害物质数据关联";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMatter(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改危害物质数据关联";

        if (this.form.matterFeatures != null) {
          var mf = this.form.matterFeatures.split(",");
          mf.forEach(t => {
            if (t == 1) {
              this.cIsToxic = "1";
            }
            if (t == 2) {
              this.cIsFlammable = "1";
            }
            if (t == 3) {
              this.cIsOxidizing = "1";
            }
            if (t == 4) {
              this.cIsExplosive = "1";
            }
            if (t == 5) {
              this.cIsCorrosive = "1";
            }
            if (t == 6) {
              this.cIsIrritantToxic = "1";
            }
            if (t == 7) {
              this.cIsHealthHazard = "1";
            }
            if (t == 8) {
              this.cIsCompressedGas = "1";
            }
            if (t == 9) {
              this.cIsEnvironmentalHazard = "1";
            }
          })
        }
        if(this.form.matterProtects!=null){
          this.form.matterProtects.split(',').forEach(mp=>{
            this.protectGloves.forEach(item=>{
              if (mp==item.id){
                this.protectGlove=item.id
              }
            })
            this.safeGoggles.forEach(item=>{
              if (mp==item.id){
                this.safeGoggle=item.id
              }
            })
            this.resProtects.forEach(item=>{
              if (mp==item.id){
                this.resProtect=item.id
              }
            })
            this.rubberBoots.forEach(item=>{
              if (mp==item.id){
                this.rubberBoot=item.id
              }
            })
            this.protectSuits.forEach(item=>{
              if (mp==item.id){
                this.protectSuit=item.id
              }
            })
          })
        }
      });
    },
    //处理选择框
    handleCheck() {
      var a = 0;
      for (let i = 0; i < 9; i++) {
        if (i == 0 && this.cIsToxic != null) {
          this.matterFeatures[a] = "1";
          a++;
        }
        if (i == 1 && this.cIsFlammable != null) {
          this.matterFeatures[a] = "2";
          a++;
        }
        if (i == 2 && this.cIsOxidizing != null) {
          this.matterFeatures[a] = "3";
          a++;
        }
        if (i == 3 && this.cIsExplosive != null) {
          this.matterFeatures[a] = "4";
          a++;
        }
        if (i == 4 && this.cIsCorrosive != null) {
          this.matterFeatures[a] = "5";
          a++;
        }
        if (i == 5 && this.cIsIrritantToxic != null) {
          this.matterFeatures[a] = "6";
          a++;
        }
        if (i == 6 && this.cIsHealthHazard != null) {
          this.matterFeatures[a] = "7";
          a++;
        }
        if (i == 7 && this.cIsCompressedGas != null) {
          this.matterFeatures[a] = "8";
          a++;
        }
        if (i == 8 && this.cIsEnvironmentalHazard != null) {
          this.matterFeatures[a] = "9";
          a++;
        }
      }
      var b = 0;
      for (let i = 0; i < 5; i++) {
        if (i == 0 && this.protectGlove != null) {
          this.matterProtects[b] = this.protectGlove;
          b++;
        }
        if (i == 1 && this.safeGoggle != null) {
          this.matterProtects[b] = this.safeGoggle;
          b++;
        }
        if (i == 2 && this.resProtect != null) {
          this.matterProtects[b] = this.resProtect;
          b++;
        }
        if (i == 3 && this.rubberBoot != null) {
          this.matterProtects[b] = this.rubberBoot;
          b++;
        }
        if (i == 4 && this.protectSuit != null) {
          this.matterProtects[b] = this.protectSuit;
          b++;
        }
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.handleCheck();
      this.form.matterFeatures = this.matterFeatures.join(",");
      this.form.matterProtects = this.matterProtects.join(",");
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMatter(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMatter(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delMatter(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有危害物质数据关联数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportMatter(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {
        dangerouslyUseHTMLString: true
      });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    getMatterFeatureName(index) {
      switch (index) {
        case 1:
          return '毒性';
        case 2:
          return '易燃性';
        case 3:
          return '氧化性';
        case 4:
          return '爆炸性';
        case 5:
          return '腐蚀性';
        case 6:
          return '刺激性/致敏性/毒性';
        case 7:
          return '健康危害';
        case 8:
          return '压力下气体';
        case 9:
          return '危害水生环境';
      }
    }
  }
};
</script>
