<!--实验室安全制度-->
<template>
  <div class="app-container safe-book" id="safe-book">
    <div class="page-container ">
      <div class="page-form-title-box">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
          <el-form-item label="" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择制度分类" @clear="clearType" size="small">
              <el-option
                v-for="item in safeType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="dateRange">
            <el-date-picker
              :clearable="false"
              v-model="dateRange"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="创建时间"
              end-placeholder="创建时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入制度标题"
              maxLength="30"
              size="small"
            />
          </el-form-item>
          <p class="page-submit-common-style-button"
             style="float: right;"
             @click="handleAdd"
             v-hasPermiRouter="['lab:safeBook:add']"
          >新增</p>
          <el-form-item>
            <p class="page-inquire-common-style-button" @click="handleQuery">查询</p>
            <p class="page-reset-common-style-button" @click="resetQuery">重置</p>
          </el-form-item>
        </el-form>
      </div>
      <div class="page-content-box">
        <el-table class="table-box" v-loading="loading" border :data="safe_bookList" @selection-change="handleSelectionChange">
          <el-table-column label="序号" type="index" align="center" width="50"/>
          <el-table-column label="标题" align="left" prop="name" />
          <el-table-column label="分类" align="left" prop="type" width="180">
            <template slot-scope="scope">
              <p v-for="item in safeType" v-if="item.value == scope.row.type">{{item.label}}</p>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="left" prop="createTime"  width="280"/>
          <el-table-column label="查看次数" align="left" prop="scanCount" width="100"/>
          <el-table-column label="二维码" align="left" width="100">
            <template slot-scope="scope">
              <div @click="dialogQrCodeOn(scope.row)">
                <vue-qr style="height:23px;width:23px;cursor:pointer;" :text="identification+'?code='+scope.row.id+'&type=2'" :size="200"></vue-qr>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160" v-if="tableButtonType">
            <template slot-scope="scope">
              <div class="table-button-box">
                <p class="table-button-null"></p>
                <p class="table-button-p"
                   @click="handleUpdate(scope.row)"
                   v-hasPermiRouter="['lab:safeBook:add','lab:safeBook:edit']"
                >编辑</p>
                <p class="table-button-p"
                   @click="handleDelete(scope.row)"
                   v-hasPermiRouter="['lab:safeBook:del']"
                >删除</p>
                <p class="table-button-null"></p>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination :page-sizes="[20, 30, 40, 50]"
                    v-show="total>0"
                    :total="total"
                    :page.sync="queryParams.page"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList"
        />
      </div>
    </div>
    <!-- 添加或修改实验室安全制度对话框 -->
    <el-dialog :title="title" class="safe-book-el-dialog" :visible.sync="open" width="1000px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="name" style="width:498px;">
          <el-input v-model="form.name" placeholder="请输入标题" maxLength="30"/>
        </el-form-item>
        <el-form-item label="制度分类" prop="type" >
          <el-select v-model="form.type" placeholder="请选择制度分类" style="width:418px;">
            <el-option
              v-for="item in safeType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="编号" prop="code" style="width:498px;">
          <el-input v-model="form.code" placeholder="请输入编号" maxLength="10"/>
        </el-form-item>
        <el-form-item label="上传PDF" prop="content" v-if="open" style="margin-bottom:0;">
          <el-upload
            class="pdf-up-data"
            :action="uploadImgUrl"
            :show-file-list="false"
            accept="pdf"
            :on-success="handleAvatarSuccess"
            :headers="headers"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.content" src="@/assets/ZDimages/safetyEducationExam/pdf.png" style="margin-top:6px;" class="avatar">
            <i style="line-height: 30px;width: 32px;text-align: center;border: 1px solid #999;border-radius: 4px;font-size: 10px;"
               v-if="!form.content" class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <div v-if="pdfContent" class="pdf-max-box">
          <pdf
            ref="pdf"
            :src="pdfContent"
            v-for="i in numPages"
            :key="i"
            :page="i"
          >
          </pdf>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer dialog-footer-box">
        <p class="dialog-footer-button-null"></p >
        <p class="dialog-footer-button-info" @click="cancel">取消</p >
        <p class="dialog-footer-button-primary" @click="submitForm">提交</p >
        <p class="dialog-footer-button-null"></p >
      </div>
    </el-dialog>
    <!-- 二维码展示 -->
    <qr-code-dialog ref="qrCodeDialog" :qrCodeDialogData="qrCodeDialogData"></qr-code-dialog>
  </div>
</template>

<script>
  import qrCodeDialog from "@/components/qrCodeDialog/index.vue"
  import {
  laboratorySafeBookList,
  laboratorySafeBook,
  laboratorySafeBookAdd,
  laboratorySafeBookEdit,
  laboratorySafeBookDel
} from "@/api/safetyEducationExam/index";
import { getToken } from "@/utils/auth";
import pdf from 'vue-pdf'
import vueQr from 'vue-qr'
export default {
  components:{
    pdf,
    vueQr,
    qrCodeDialog
  },
  name: "Safe_book",
  data() {
    return {
      tableButtonType:this.hasPermiDom(['lab:safeBook:add','lab:safeBook:edit','lab:safeBook:del']),
      uploadImgUrl: this.uploadUrl(), // 上传的图片服务器地址
      headers: {
        Authorization:getToken(),
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 实验室安全制度表格数据
      safe_bookList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        page: 1,
        pageSize:20,
        type: null,
        name: null,
        code: null,
        content: null,
        qrCodeUrl: null,
        scanCount: null,
        userId: null,
        deptId: null,
        deptName: null,
      },
      // 表单参数
      form: {},
      //上传完展示用地址
      pdfContent:"",
      // 表单校验
      rules: {
        name:[
          {required: true, message: '请输入标题', trigger: 'blur'},
          { required: true, message: "请输入标题", validator: this.spaceJudgment, trigger: "blur" }
        ],
        type:[
          {required: true, message: '请选择制度分类', trigger: 'blur'}
        ],
        code:[
          {required: true, message: '请输入编号', trigger: 'blur'}
        ],
        content:[
          {required: true, message: '请上传PDF', trigger: 'blur'}
        ],
      },
      safeType:[],
      // 日期范围
      dateRange: [],
      //pdf相关
      numPages: null, // pdf 总页数
      //二维码展示数据
      qrCodeDialogData:{},
      //二维码规则 服务器域名,需与微信后台开发配置内一致.
      identification: localStorage.getItem('codeOnlineAdd'),
    };
  },
  created() {
    this.getList();
    this.getDicts("safe_type").then(response => {
      this.safeType = response.data;
    });
  },
  methods: {
    clearType(){
      this.$set(this.queryParams,'type',null);
    },
    //展示二维码
    dialogQrCodeOn(row){
      this.$set(this,'qrCodeDialogData',{
        download:true,
        type:'2',                                                     //二维码类型 用于区分二维码功能类型
        parameter:row.id,                                             //二维码参数
        name:row.name,                                                //二维码名称用于下载时命名
        codeName:row.name,                                            //二维码图片下名称展示(非必传)
      });
      this.$refs['qrCodeDialog'].initialize();
    },
    //上传
    handleAvatarSuccess(res, file) {
      this.pdfContent = localStorage.getItem('fileBrowseEnvironment')+res.data.url;
      this.form.content = res.data.url;
      this.form.realContent = localStorage.getItem('fileBrowseEnvironmentExtranet')+res.data.url;
      this.getNumPages();
      this.$forceUpdate()
    },
    beforeAvatarUpload(file) {
      let type = false;
      let num = 0;
      for(let i=0;i<file.name.length;i++){
        if(file.name[i] == '.'){
          num++
        }
      }
      if(num != 1){
        this.msgError('文件名称不能包含 " . "')
        return false
      }
      if (file.type == 'application/pdf') {
        type = true;
      }else{
        this.msgError('只能上传pdf格式文件');
        type = false;
      }
      return type;
    },
    change(val) {
      this.$set(this.form,'content',val);
      // this.form.content = val;
    },
    /** 查询实验室安全制度列表 */
    getList() {
      this.loading = true;
      if(this.dateRange&&this.dateRange.length>0)
      {
        this.queryParams.startTime=this.dateRange[0]+'T00:00:00';
        this.queryParams.endTime=this.dateRange[1]+'T23:59:59';
      }
      else
      {
        this.queryParams.startTime=null;
        this.queryParams.endTime=null
      }
      laboratorySafeBookList(this.queryParams).then( response => {
        this.safe_bookList =  response.data.records;
        this.total =  response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        name: null,
        code: null,
        content: null,
        realContent: null,
        qrCodeUrl: null,
        scanCount: null,
        userId: null,
        createBy: null,
        updateBy: null,
        deptId: null,
        deptName: null,
        createTime: null,
        updateTime: null,
        remark: null
      };
      this.pdfContent = "";
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRange=[];
      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
      laboratorySafeBook(id).then( response => {
        this.form =  response.data;
        this.pdfContent = localStorage.getItem('fileBrowseEnvironment')+response.data.content;
        this.getNumPages();
        this.open = true;
        this.title = "修改实验室安全制度";
      });
    },
    getNumPages() {
      let loadingTask = pdf.createLoadingTask(this.form.content)
      loadingTask.promise.then(pdf => {
        this.numPages = pdf.numPages
      }).catch(err => {
        console.error('pdf 加载失败', err);
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // this.form.content = escape(this.form.content);
          if (this.form.id != null) {
            laboratorySafeBookEdit(this.form).then( response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.reset();
              this.getList();
            });
          } else {
            laboratorySafeBookAdd(this.form).then( response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.reset();
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除该安全制度?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return laboratorySafeBookDel({id:ids});
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('laboratory/safe_book/export', {
        ...this.queryParams
      }, `laboratory_safe_book.xlsx`)
    }
  }
};
</script>

<style scoped lang="scss">
  #safe-book {
    .button-box{
      margin:0 auto;
      width:190px;
      display: flex;
    }
  }
  .safe-book-el-dialog .pdf-max-box {
    height: 400px;
    overflow-y: scroll;
  }
</style>
