<!--实验室安全制度-->
<template>
  <div class="app-container safe-book" id="safe-book">
    <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="请选择制度分类" clearable size="small">
          <el-option
            v-for="item in safeType"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          >
          </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="请输入制度标题"
          clearable
          maxLength="30"
          size="small"
        />
      </el-form-item>
      <el-form-item style="float: right;">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['laboratory:safe_book:add']"
        >新增</el-button>
      </el-form-item>
      <el-form-item>
        <p class="inquire-button-one" @click="handleQuery">查询</p>
        <p class="reset-button-one" @click="resetQuery">重置</p>
      </el-form-item>
    </el-form>

    <el-table 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.dictValue == scope.row.type">{{item.dictLabel}}</p>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="left" prop="createTime"  width="280"/>
      <el-table-column label="查看次数" align="left" prop="scanCount" width="190"/>
      <el-table-column label="二维码" align="left" width="140">
        <template slot-scope="scope">
          <div @click="dialogQrCodeOn(scope.row.qrCodeUrl)">
            <vue-qr style="height:50px;width:50px;cursor:pointer;" :text="scope.row.qrCodeUrl" :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="button-box">
            <p class="table-min-button"
               style="margin-right:10px;"
               @click="handleUpdate(scope.row)"
               v-hasPermiAnd="['laboratory:safe_book:edit','laboratory:safe_book:query']"
            >编辑</p>
            <p class="table-min-button"
               @click="handleDelete(scope.row)"
               v-hasPermi="['laboratory:safe_book:remove']"
            >删除</p>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination :page-sizes="[20, 30, 40, 50]"
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改实验室安全制度对话框 -->
    <el-dialog :title="title" class="safe-book-el-dialog" :visible.sync="open" width="1000px" append-to-body>
      <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="请选择制度分类">
            <el-option
              v-for="item in safeType"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            >
            </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;">
          <!--<editor v-model="form.content" :min-height="192"/>-->
          <!--<wangEditor v-model="form.content" @change="change" :min-height="192"/>-->
          <!--<wangEditor :content="form.content" @change="change" :min-height="192"/>-->
          <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/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="form.content" class="pdf-max-box">
          <pdf
            ref="pdf"
            :src="form.content"
            v-for="i in numPages"
            :key="i"
            :page="i"
          >
          </pdf>
        </div>
        <!--
        <el-form-item label="二维码地址" prop="qrCodeUrl">
          <el-input v-model="form.qrCodeUrl" placeholder="请输入二维码地址" />
        </el-form-item>
        <el-form-item label="查看次数" prop="scanCount">
          <el-input v-model="form.scanCount" placeholder="请输入查看次数" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </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="二维码" class="qr-codeUrl-dialog" :visible.sync="dialogQrCodeType" width="300px" append-to-body>
      <vue-qr style="display: block;height:200px;width:200px;cursor:pointer;margin:0 auto;" :text="dialogQrCodeUrl" :size="200"></vue-qr>
    </el-dialog>
  </div>
</template>

<script>
import { listSafe_book, getSafe_book, delSafe_book, addSafe_book, updateSafe_book } from "@/api/laboratory/safe_book";
import { getToken } from "@/utils/auth";
import pdf from 'vue-pdf'
import vueQr from 'vue-qr'
export default {
  components:{
    pdf,
    vueQr
  },
  name: "Safe_book",
  data() {
    return {
      tableButtonType:this.hasPermiDom(['laboratory:safe_book:edit','laboratory:safe_book:query','laboratory:safe_book:remove']),
      uploadImgUrl: window.location.href.split('://')[0]+'://' + process.env.VUE_APP_BASE_API + "/base/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 实验室安全制度表格数据
      safe_bookList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize:20,
        type: null,
        name: null,
        code: null,
        content: null,
        qrCodeUrl: null,
        scanCount: null,
        userId: null,
        deptId: null,
        deptName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      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 总页数
      //二维码展示数据
      dialogQrCodeType:false,
      dialogQrCodeUrl:"",
    };
  },
  created() {
    this.getList();
    this.getDicts("safe_type").then(response => {
      this.safeType = response.data;
    });
  },
  methods: {
    dialogQrCodeOn(url){
      this.dialogQrCodeUrl = url;
      this.dialogQrCodeType = true;
    },
    //上传
    handleAvatarSuccess(res, file) {
      this.form.content = window.location.href.split('://')[0]+'://' +process.env.VUE_APP_BASE_API + '/' + res.data.url;
      this.form.realcontent =res.data.url;
      this.getNumPages();
      this.$forceUpdate()
    },
    beforeAvatarUpload(file) {
      let type = false;
      console.log('file',file);
      if (file.type == 'application/pdf') {
        type = true;
      }else{
        this.$message.error('只能上传pdf格式文件');
        type = false;
      }
      return type;
    },
    change(val) {
      this.$set(this.form,'content',val);
      // this.form.content = val;
      console.log(val)
    },
    /** 查询实验室安全制度列表 */
    getList() {
      this.loading = true;
      if(this.dateRange&&this.dateRange.length>0)
      {
        this.queryParams.beginTime=this.dateRange[0]
        this.queryParams.endTime=this.dateRange[1]
      }
      else
      {
        this.queryParams.beginTime=null;
        this.queryParams.endTime=null
      }
      listSafe_book(this.queryParams).then( response => {
        this.safe_bookList =  response.rows;
        this.total =  response.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.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 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
      getSafe_book(id).then( response => {
        this.form =  response.data;
        this.form.content = window.location.href.split('://')[0]+'://' + response.data.content.split('://')[1];
        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 => {
        this.form.content=this.form.realcontent;
        if (valid) {
          // this.form.content = escape(this.form.content);
          if (this.form.id != null) {
            updateSafe_book(this.form).then( response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.reset();
              this.getList();
            });
          } else {
            addSafe_book(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 delSafe_book(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 {
    display: flex !important;
    flex-direction: column;
    box-shadow: 0 0 8px 2px rgba(0, 0, 0, 0.1);
    padding:20px!important;
    .button-box{
      margin:0 auto;
      width:190px;
      display: flex;
    }
  }
</style>
