<!--安全准入办理-->
<template>
  <div class="app-container approval_handle">
    <div class="approval_handle-page" v-if="pageType == 1">
      <div class="top-click-img-box">
        <img src="@/assets/ZDimages/img_zrzgsq_bg.png" alt="">
        <p @click="pageClick(2)">安全准入申请</p>
      </div>
      <el-table v-loading="loading" border :data="approvalList" @selection-change="handleSelectionChange">
        <el-table-column label="申请实验室" align="left" prop="subjectName"/>
        <!--<el-table-column label="准入资格名称" align="left" prop="configureName"/>-->
        <el-table-column label="申请时间" align="left" prop="creatTime">
          <template slot-scope="scope">
            {{scope.row.creatTime}} {{scope.row.hi}}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="left" prop="auditStatus">
          <template slot-scope="scope">
            <p :class="scope.row.auditStatus == 0?'color_warn':(scope.row.auditStatus == 1?'color_FF4E00':(scope.row.auditStatus == 2?'color_14AE10':''))">{{scope.row.auditStatus == 0?'待审核':(scope.row.auditStatus == 1?'驳回':(scope.row.auditStatus == 2?'通过':''))}}</p>
          </template>
        </el-table-column>
        <el-table-column label="有效期" align="left" prop="validBeginTime">
          <template slot-scope="scope">
            {{scope.row.validBeginTime}}至{{scope.row.validEndTime}}
          </template>
        </el-table-column>
        <!--<el-table-column label="过期时间" align="left" prop="expirationDate" />-->
        <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="150">
          <template slot-scope="scope">
            <div class="button-box">
              <p class="table-min-button"
                 @click="pageClick('3',scope.row)"

                 v-hasPermi="['laboratory:apply:query']"
              >查看</p>
              <p class="table-min-button"
                 v-if="scope.row.auditStatus == 0 || scope.row.auditStatus == 1"
                 style="margin-left:10px;"
                 @click="handleDelete(scope.row)"
                 v-hasPermi="['laboratory:apply:remove']"
              >删除</p>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination :page-sizes="[20, 30, 40, 50]"
        v-show="total>0"
        :total="total"
        layout="total, prev, pager, next, sizes, jumper"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="newGetList"
      />
    </div>
    <add-page v-if="pageType == 2" :infoData="infoData" :infoType="infoType"></add-page>
    <info-page v-if="pageType == 3" :infoData="infoData"></info-page>
    <!--新增/修改-->
    <el-drawer
      class="approval_handle-drawer"
      :visible.sync="drawer"
      direction="rtl"
      ref="drawer"
      :with-header="false"
      :show-close="false"
      :before-close="handleClose">
      <el-form :model="drawerForm" ref="drawerForm" :rules="rules" :inline="true" class="approval_handle-drawer-form-box">
        <el-form-item label="学院" prop="deptId" label-width="50px" >
          <el-select v-model="drawerForm.deptId" placeholder="请选择学院" :disabled="disabledType" clearable size="small"
            @change="getBuildings(drawerForm.deptId)">
            <el-option
              v-for="dict in deptOptions"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="楼栋" prop="buildId">
          <el-select v-model="drawerForm.buildId" placeholder="请选择楼栋" :disabled="disabledType" clearable size="small"
            @change="getSubjectDictList(drawerForm.buildId)">
            <el-option
              v-for="dict in buildings"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实验室" prop="subjectId">
          <el-select v-model="drawerForm.subjectId" placeholder="请选择实验室" :disabled="disabledType" clearable size="small"
            @change="securityBySubjectId(drawerForm.subjectId)">
            <el-option
              v-for="item in subjects"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <div class="upload-box" v-for="(item,index) in drawerForm.approvalDetails" :key="index">
          <p>{{item.materialName}}</p>
          <el-upload
            class="avatar-uploader"
            :action="uploadImgUrl"
            accept="image/jpeg,image/gif,image/png"
            :show-file-list="false"
            :disabled="disabledImgType"
            :on-success="(response, file)=>handleAvatarSuccess(response,file,index)"
            :headers="headers"
            :before-upload="beforeAvatarUpload">
            <img v-if="item.materialUrl" :src="item.materialUrl" class="avatar">
            <i v-if="!item.materialUrl" class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
      </el-form>
      <div class="bottom-button-box">
        <p class="null-p"></p>
        <p class="reset-button-one" style="margin-right:20px;" @click="offDrawer">{{disabledImgType?'关闭':'取消'}}</p>
        <p class="inquire-button-one" v-if="!disabledImgType" @click="submitForm">提交</p>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { userAppRovallist, getApproval, delApproval, addApproval, updateApproval, securityBySubjectId, listapply, applyDelete } from "@/api/laboratory/approval";
import { done } from 'element-ui'
import { listDepartments,listbuildings } from "@/api/system/dept";
import {subjectDictList } from "@/api/laboratory/record";
import { getToken } from "@/utils/auth";
import addPage from "./addPage.vue"
import infoPage from "./infoPage.vue"

export default {
  name: "Approval",
  components: {
    addPage,
    infoPage
  },
  data() {
    return {
      //页面状态
      pageType:1,
      uploadImgUrl: this.uploadUrl(), // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 审批记录表格数据
      approvalList: [],
      // 证书类别
      subClassOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize:20,
        // joinUserId: null,
        // recordContent: null,
        // deptId: null,
        // deptName: null,
        // userId: null,
        // configureName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deptId:[
          {required: true, message: '请选择学院', trigger: 'blur'}
        ],
        buildId:[
          {required: true, message: '请选择楼栋', trigger: 'blur'}
        ],
        subjectId:[
          {required: true, message: '请选择实验室', trigger: 'blur'}
        ],
      },
      //  关联实验室弹窗开关
      drawer:false,
      disabledType:false,
      disabledImgType:false,
      drawerForm:{

      },
      recordContents: [
        {
          type: 0,
          value: "未通过",
        },
        {
          type: 1,
          value: "已办理",
        },
        {
          type: 2,
          value: "待审核",
        },
        {
          type: 3,
          value: "即将过期",
        },
        {
          type: 4,
          value: "已过期",
        },
      ],
      // 学院
      deptOptions:[],
      // 楼栋
      buildings:[],
      // 实验室
      subjects: [],
      // 所需资料
      approvalDetails: [],
      //详情传参数据
      infoData:{},
      infoType:false,
    };
  },
  created() {
    this.newGetList();
    // this.getDicts("subject_class").then(response => {
    //   this.subClassOptions = response.data;
    // })
    // this.getDeptList();
  },
  methods: {
    //页面切换
    pageClick(type,item){
      if(this.pageType != type){
        if(type == 1){
          this.newGetList();
          this.pageType = type
          this.infoData = "";
        }else if(type == 2){
          //新增
          JSON.stringify()
          this.pageType = type
          this.infoType = false;
        }else if(type == 3){
          //查看
          this.infoData = item;
          this.pageType = type
        }else if(type == 4){
          //编辑
          this.infoData = item;
          this.infoType = true;
          this.pageType = 2
        }
      }
    },
    /** 查询学院列表 */
    getDeptList() {
      listDepartments().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 根据学院查询楼栋列表  */
    getBuildings(id,type) {
      if(id) {
        this.subjects = [];
        this.$set(this.drawerForm, 'buildId', '')
        this.$set(this.drawerForm, 'subjectId', '')
        listbuildings(id).then(response => {
          this.buildings = response.data;
          if(!type){
            this.drawerForm.approvalDetails = [];
          }
        });
      }
    },
    /** 根据学院楼栋查询实验室列表  */
    getSubjectDictList (buildId,type) {
      this.$set(this.drawerForm, 'subjectId', '')
      subjectDictList({buildId: buildId}).then(response => {
        this.subjects = response.data;
        if(!type){
          this.drawerForm.approvalDetails = [];
        }
      });
    },
    /** 通过实验室 查询对应的安全准入规则 */
    securityBySubjectId(subjectId) {
      securityBySubjectId(subjectId).then(response => {
        // this.approvalList = response.data;
        if(response.data && response.data.materialNames){
          let materialNames = response.data.materialNames;
          this.drawerForm.approvalDetails =[];
          this.drawerForm.securityGroupId = response.data.id;
          const names = materialNames.split(",")
          names.forEach(v => {
           this.drawerForm.approvalDetails.push({materialName: v, materialUrl: ''})
          })
        }else {
          this.drawerForm.approvalDetails = [];
          this.$message.error("实验室暂无安全准入配置！");
        }
        this.$forceUpdate();
      });
    },
    //图片上传
    handleAvatarSuccess(res, file,index) {
      this.drawerForm.approvalDetails[index].materialUrl = res.data.url;
      this.$forceUpdate()
    },
    beforeAvatarUpload(file) {
      let type = false;
      console.log('file',file);
      if (file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/gif') {
        type = true;
      }else{
        this.$message.error('只能上传png/jpeg/gif格式图片');
        type = false;
      }
      return type;
    },
    //关联实验室弹窗
    drawerBoxOn(){
      this.resetTwo();
      this.drawerForm.recordContent = ""
      this.drawer = true;
      this.disabledType = false;
      this.disabledImgType = false;
    },
    //关闭弹窗
    offDrawer(){
      this.$refs.drawer.closeDrawer();
    },
    //弹窗关闭前回调
    handleClose(done) {
      this.$confirm('确认关闭吗？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    /** 查询审批记录列表（废弃） */
    getList() {
      this.loading = true;
      userAppRovallist(this.queryParams).then(response => {
        this.approvalList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询审批记录列表 */
    newGetList() {
      this.loading = true;
      listapply(this.queryParams).then(response => {
        this.approvalList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        joinUserId: null,
        recordContent: null,
        deptId: null,
        deptName: null,
        userId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    resetTwo(){
      this.drawerForm = {};
      this.buildings = [];
      this.subjects = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.newGetList();
    },
    /** 重置按钮操作 */
    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(type,row) {
      this.reset();
      const id = row.id
      getApproval(id).then(response => {
        if(response.data.deptId){
          this.getBuildings(response.data.deptId,true)
        }
        if(response.data.buildId){
          this.getSubjectDictList(response.data.buildId,true)
        }
        this.drawerForm = response.data;
        let list = response.data.approvalDetails;
        let newList = [];
        let listData = [];
        if(type==1){
          this.disabledType = true;
          this.disabledImgType = true;
          this.drawerForm.recordContent = "";
          this.drawer = true;
          this.$forceUpdate();
        }else{
          securityBySubjectId(response.data.subjectId).then(response => {
            if(response.data && response.data.materialNames){
              let materialNames = response.data.materialNames;
              this.drawerForm.approvalDetails =[];
              this.drawerForm.securityGroupId = response.data.id;
              const names = materialNames.split(",")
              names.forEach(v => {
                newList.push({materialName: v, materialUrl: ''})
              })
              this.disabledType = true;
              this.disabledImgType = false;
              for(let i=0;i<newList.length;i++){
                let num = 0;
                for(let o=0;o<list.length;o++){
                  if(newList[i].materialName == list[o].materialName){
                    listData.push(list[o]);
                    num++
                  }
                }
                if(num==0){
                  listData.push(newList[i]);
                }
              }
              this.drawerForm.approvalDetails = listData;
              this.drawer = true;
              this.$forceUpdate();
            }else {
              this.drawerForm.approvalDetails = [];
              this.$message.error("实验室暂无安全准入配置！");
            }
          });
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      let self = this;
      if(!self.drawerForm.approvalDetails[0]){
        this.$message.error("该实验室未配置安全准入规则,无法办理！");
        return
      }
      for (let i=0;i<self.drawerForm.approvalDetails.length;i++){
        if(self.drawerForm.approvalDetails[i].materialUrl == ""){
          this.$message.error("请上传相关凭证！");
          return
        }
      }
      this.$refs["drawerForm"].validate(valid => {
        if (valid) {
          if (this.drawerForm.id != null) {
            this.drawerForm.recordContent = "2";
            updateApproval(this.drawerForm).then(response => {
              this.msgSuccess("修改成功");
              this.drawer = false;
              this.newGetList();
            });
          } else{
            addApproval(this.drawerForm).then(response => {
              this.msgSuccess("新增成功");
              this.drawer = false;
              this.newGetList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let self = this;
      const ids = row.id || this.ids;
      this.$confirm('确认删除申请记录吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          self.delItem(row.id);
        }).then(() => {
          // this.newGetList();
          // this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    delItem(id){
      applyDelete(id).then(response => {
        this.newGetList();
        this.msgSuccess("删除成功");
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('laboratory/approval/export', {
        ...this.queryParams
      }, `laboratory_approval.xlsx`)
    }
  }
};
</script>

<style scoped lang="scss">
  .approval_handle {
    display: flex!important;
    flex-direction: column;
    .approval_handle-page{
      flex:1;
      display: flex!important;
      flex-direction: column;
      box-shadow: 0 0 8px 2px rgba(0, 0, 0, 0.1);
      padding:20px 20px 20px!important;
      border-radius:10px;
      .top-click-img-box{
        width:1536px;
        height:250px;
        margin:0 auto 20px;
        position: relative;
        img{
          width:1536px;
          height:250px;
        }
        p{
          margin:0;
          position: absolute;
          left:690px;
          bottom:24px;
          width:200px;
          height:50px;
          border-radius:10px;
          line-height:50px;
          font-size:18px;
          text-align: center;
          color:#fff;
          background: #0183FA;
          cursor: pointer;
        }
      }
      .form-box{
      }
      .button-box{
        width:200px;
        display: flex;
      }
    }

  }
</style>
