<!--安全准入办理-->
<template>
  <div class="page-container approval_handle_addPage">
    <div class="page-top-title-box">
      <p class="page-top-title-name-p">准入申请</p>
      <p class="page-top-title-out-p" @click="backPage">返回</p>
      <p class="page-top-title-submit-p" v-if="minType == 1" style="width:230px;" @click="typeClick">我已选择实验室，上传准入材料</p>
      <p class="page-top-title-submit-p" v-if="minType == 2" style="width:230px;" @click="upDataButton">
        准入材料上传完毕，提交申请</p>
    </div>
    <div class="addPage-max-box scrollbar-box">
      <el-form :model="form" ref="form" :rules="rules" label-position="left" label-width="100px">
        <div class="addPage-type-one" style="text-align: center" v-if="minType == 1">
          <p class="addPage-type-one-title">实验室安全准入是进入实验室所需的必要手续，为保障您能够顺利申请准入资格，请在申请前请认真阅读以下内容。</p>
          <div style="text-align: left;margin-left:36%">
            <p class="addPage-type-one-title-min">1、您在申请前请提前了解所申请实验室的准入材料并提前准备相应材料；</p>
            <p class="addPage-type-one-title-min">2、为保障您的安全，请在申请准入前认真学习相关实验室知识；</p>
            <p class="addPage-type-one-title-min">3、如您提供的材料涉嫌造假，将会剥夺您的准入申请资格；</p>
            <el-form-item label="申请实验室" prop="subjectId">
              <el-select
                style="width:300px;"
                v-model="form.subjectId"
                filterable
                remote
                reserve-keyword
                @change="selectChange"
                placeholder="请输入实验室关键词"
                :remote-method="userSelectList"
                :loading="loading">
                <el-option
                  v-for="item in laboratoryOptions"
                  :key="item.subId"
                  :label="item.subName"
                  :value="item.subId">
                </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: 300px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                :picker-options="pickerOptions0"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="申请备注" prop="applyCause">
              <el-input type="textarea" style="width: 300px" v-model="form.applyCause" resize="none"
                        placeholder="请输入申请备注" maxlength="50"/>
            </el-form-item>
          </div>
        </div>
        <!--学生-->
        <div class="addPage-type-two" v-if="minType == 2&&subjectData.sysUser.userType == '2'">
          <el-form class="item-max-box" :model="queryParams" ref="queryParams" :rules="rules" label-width="80px">
            <div class="item-title-box">
              <p>*</p>
              <p style="margin-right:10px;">身份卡</p>
              <p>(关联学生信息材料)</p>
            </div>
            <el-row>
              <el-col :span="6">
                <el-form-item label="申请人" prop="userName">
                  <el-input v-model="queryParams.userName" disabled placeholder="未绑定信息" clearable
                            style="width:220px;"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系方式" prop="mobile">
                  <el-input v-model="queryParams.mobile" disabled placeholder="未绑定联系方式" clearable
                            style="width:220px;"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="学号" prop="account">
                  <el-input v-model="queryParams.account" disabled placeholder="未绑定学号" clearable
                            style="width:220px;"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="物理卡号" prop="cardNumSimple">
                  <el-input v-model="queryParams.cardNumSimple" disabled placeholder="未绑定物理卡号" clearable
                            style="width:220px;"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="班级" prop="gradeName">
                  <el-input v-model="queryParams.gradeName" disabled maxlength="10" placeholder="未绑定班级" clearable
                            style="width:220px;"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="导师" prop="tutorUserId" class="form-item">
                  <el-select
                    style="width:220px;"
                    disabled
                    v-model="queryParams.tutorUserId"
                    filterable
                    remote
                    clearable
                    reserve-keyword
                    placeholder="未绑定导师"
                    :remote-method="systemUserSelectUser"
                    :loading="loading">
                    <el-option
                      v-for="item in optionsUser"
                      :key="item.userId"
                      :label="item.userName"
                      :value="item.userId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div v-for="(item,index) in subjectData.listStudent" :key="index">
            <div class="item-max-box" v-if="item.materialType==2&&item.relationType==2">
              <div class="item-title-box">
                <p>*</p>
                <p>安全考试证书</p>
                <p>(已同步证书信息)：</p>
              </div>
              <img v-if="item.materialType==2&&item.relationType==2&&subjectData.userCertificate"
                   @click="fullScreenViewClick(subjectData.userCertificate)"
                   class="item-img-box" :src="subjectData.userCertificate">
              <p v-if="item.materialType==2&&item.relationType==2&&!subjectData.userCertificate"
                 style="margin-left:40px;color:#999;font-size:14px;line-height:40px;">暂无证书</p>
            </div>
            <div class="item-max-box" v-if="item.materialType==1">
              <div class="item-title-box">
                <p>*</p>
                <p>{{item.materialName}}：</p>
                <p></p>
              </div>
              <p class="item-title-text">{{item.materialDescribe}}</p>
              <el-form-item label="" prop="userIds" label-width="0">
                <div class="item-input-box">
                  <input type="text" v-model="form.proveImg" disabled :placeholder="item.materialName">
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadImgUrl"
                    :show-file-list="false"
                    accept=".jpeg,.jpg,.gif,.png,.pdf,.docx"
                    :on-success="(res)=>handleAvatarSuccess(res,item)"
                    :headers="headers"
                    :before-upload="(file)=>beforeAvatarUpload(file,item)">
                    <p
                      style="line-height:40px;text-align: center;background-color: #0183FA;color:#fff;width:80px;border-radius:6px;">
                      上传</p>
                  </el-upload>
                </div>


                <!--                <div style="color: #999;padding-left: 12px;">此处为准入条件中的材料备注</div>-->

                <div class="item-input-for-box">
                  <!--循环-->
                  <div class="item-input-for-big" v-for="(minItem,minIndex) in item.upList" :key="minIndex">
                    <div class="item-input-for-min">
                      <p>{{minItem.name}}</p>
                      <!--                      <a class="file_list_look" :href="minItem.url" target="_blank">查看</a>-->
                      <i style="font-style:normal;" @click="fullScreenFileLookClick(minItem)">查看</i>
                      <i style="font-style:normal;" @click="delUpData(item,minIndex)">删除</i>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
    </div>
    <fullScreenView :fullScreenViewProps="fullScreenViewProps" ref="fullScreenView"></fullScreenView>
    <fullScreenFileLook ref="fullScreenFileLook"></fullScreenFileLook>
  </div>
</template>

<script>
  let Base64 = require('js-base64').Base64
  import { mapGetters } from 'vuex'
  //                          V3
  import { materialApply, laboratoryApplyMaterialAdd, laboratoryApplyMaterialUpdate } from '@/api/secureAccess/index'
  import { laboratorySubRelInfoGetRelListByPower, systemUserSelectUser } from '@/api/commonality/permission'
  import { getToken } from '@/utils/auth'
  import fullScreenView from "@/components/fullScreenView/fullScreenView.vue";
  import fullScreenFileLook from "@/components/fullScreenFileLook/fullScreenFileLook.vue";

  export default {
    name: 'addPage',
    components: {
      fullScreenView,
      fullScreenFileLook
    },
    props: {
      infoData: {},
      infoType: {}
    },
    data() {
      return {
        uploadImgUrl: this.uploadUrl(), // 上传的图片服务器地址
        headers: {
          Authorization: getToken()
        },
        // 设置只能选择当前日期及之后的日期
        pickerOptions0: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7//如果没有后面的-8.64e7就是不可以选择今天的
          }
        },
        loading: false,
        minType: 1,
        laboratoryOptions: [],
        form: {
          validTime: 12,
          subjectId: '',
          subjectName: '',
          validBegin_time: '',//开始时间
          validEnd_time: '',//结束时间
          applyCause: ''//备注
        },
        dateRange: [],
        // 表单校验
        rules: {
          validTime: [
            { required: true, message: '请选择资格有效期', trigger: 'blur' }
          ],
          subjectId: [
            { required: true, message: '请选择实验室', trigger: 'blur' }
          ],
          chName: [
            { required: true, message: '请输入标题', trigger: 'blur' },
            { required: true, message: '请输入标题', validator: this.spaceJudgment, trigger: 'blur' }
          ],
          code: [
            { required: true, message: '请输入编号', trigger: 'blur' },
            { required: true, message: '请输入编号', validator: this.spaceJudgment, trigger: 'blur' }
          ],
          content: [
            { required: true, message: '请编辑详情', trigger: 'change' },
            { required: true, message: '请编辑详情', validator: this.spaceJudgment, trigger: 'blur' }
          ],
          /*   applyCause: [
               { required: true, message: "请输入备注", trigger: "blur" }
             ],*/
          dateRange: [
            { type: '', required: true, message: '请选择申请期限', trigger: '  ' }
          ],
          /*身份卡信息校验*/
          userName: [
            { required: true, message: '请先行编辑个人信息', trigger: 'change' },
            { required: true, message: '请先行编辑个人信息', validator: this.spaceJudgment, trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '请先行绑定联系方式', trigger: 'change' },
            { required: true, message: '请先行绑定联系方式', validator: this.spaceJudgment, trigger: 'blur' }
          ],
          account: [
            { required: true, message: '请先行绑定学号', trigger: 'change' },
            { required: true, message: '请先行绑定学号', validator: this.spaceJudgment, trigger: 'blur' }
          ],
          cardNumSimple: [
            { required: true, message: '请联系导师绑定物理卡号', trigger: 'change' },
            { required: true, message: '请联系导师绑定物理卡号', validator: this.spaceJudgment, trigger: 'blur' }
          ],
          tutorUserId: [
            { required: true, message: '请先行绑定导师', trigger: 'change' },
            { required: true, message: '请先行绑定导师', validator: this.spaceJudgment, trigger: 'blur' }
          ],
          gradeName: [
            { required: true, message: '请输入班级', trigger: 'change' },
            { required: true, message: '请输入班级', validator: this.spaceJudgment, trigger: 'blur' }
          ]

        },
        subject: {},
        //实验室准入条件
        subjectData: {},
        upDataName: '',
        queryParams: {},

        optionsUser: [],
        remark: '1',
        //图片浏览
        fullScreenViewProps:[],
      }
    },
    computed: {
      ...mapGetters([
        'name'
      ])
    },
    created() {
      if (this.infoType) {
        this.$set(this,'remark','');
        this.$set(this.form,'subjectId',this.infoData.labSecurityApply.subId);
        this.$set(this,'dateRange',[
          this.parseTime(this.infoData.labSecurityApply.validBeginTime,"{y}-{m}-{d}"),
          this.parseTime(this.infoData.labSecurityApply.validEndTime,"{y}-{m}-{d}")
        ]);
        this.getApproval()
      }
    },
    methods: {
      //图片浏览
      fullScreenViewClick(url){
        this.$set(this,'fullScreenViewProps',[url]);
        this.$refs['fullScreenView'].initialize();
      },
      //文件浏览
      fullScreenFileLookClick(item){
        //判断类型
        let type = '';
        if(item.url.split('.')[1] == 'docx'){
          type = 'docx'
        }else if(item.url.split('.')[1] == 'xlsx'){
          type = 'excel'
        }else if(item.url.split('.')[1] == 'pdf'){
          type = 'pdf'
        }else if(item.url.split('.')[1] == 'png' || item.url.split('.')[1] == 'jpg' || item.url.split('.')[1] == 'gif'){
          type = 'img'
        }
        //整合地址
        let url = localStorage.getItem('fileBrowseEnvironment')+item.url;
        // 判断图片还是文件
        if(type == 'img'){
          this.$set(this,'fullScreenViewProps',[url]);
          this.$refs['fullScreenView'].initialize();
        }else if(type == 'docx' || type == 'excel' || type == 'pdf'){
          this.$refs['fullScreenFileLook'].initialize(item.name,url,type);
        }
      },
      /** 导师-懒加载 */
      systemUserSelectUser(query) {
        if (query !== '' && query) {
          let obj = {
            userName: query,
            userType: '1'
          }
          systemUserSelectUser(obj).then(response => {
            this.optionsUser = response.data
          })
        } else {
          this.optionsUser = []
        }
      },
      laboratoryApplyMaterialUpdate(obj) {
        laboratoryApplyMaterialUpdate(obj).then(response => {
          this.msgSuccess('提交成功')
          this.$parent.pageClick(1)
        })
      },
      laboratoryApplyMaterialAdd(obj) {
        laboratoryApplyMaterialAdd(obj).then(response => {
          this.msgSuccess('提交成功')
          this.$parent.pageClick(1)
        })
      },
      //提交按钮
      upDataButton() {
        let self = this
        this.$refs['queryParams'].validate(valid => {
          if (valid) {
            if (this.dateRange && this.dateRange.length > 0) {
              this.form.validBegin_time = this.dateRange[0]+'T00:00:00'
              this.form.validEnd_time = this.dateRange[1]+'T23:59:59'
            } else {
              this.form.validBegin_time = null
              this.form.validEnd_time = null
            }
            let sysUser = {
              userName: this.queryParams.userName,
              mobile: this.queryParams.mobile,
              account: this.queryParams.account,
              cardNumSimple: this.queryParams.cardNumSimple,
              tutorUserId: this.queryParams.tutorUserId,
              grade: this.queryParams.gradeName,
              tutorUserName: this.queryParams.tutorUserName,
              userId: this.queryParams.userId
            }
            let obj = {
              subAdminId: this.subjectData.fzrSysUser.userId,
              userNumber: this.subjectData.sysUser.account,//学号/工号
              userMajor: this.subjectData.sysUser.majorName,//专业名称
              userMajorId: this.subjectData.sysUser.major,//专业ID
              deptId: this.subject.deptId, //NULL部门id
              deptName: this.subject.deptName, //NULL部门名称
              subId: this.subject.subId, //NULL实验室id
              subName: this.subject.subName, //NULL实验室名称
              auditStatus: '0', //NULL审核状态 0待审核 1驳回 2通过
              //validLength:this.form.validTime, //NULL有效期 月份时长
              relList: [],//上传资料
              sysUserModel: sysUser,//身份卡用户信息
              validBeginTime: this.form.validBegin_time,//申请期限开始时间
              validEndTime: this.form.validEnd_time,//申请期限结束时间
              applyCause: this.form.applyCause//申请备注

            }
            if (this.subjectData.sysUser.userType == '2') {
              for (let i = 0; i < self.subjectData.listStudent.length; i++) {
                if (self.subjectData.listStudent[i].materialType == 1) {
                  if (!self.subjectData.listStudent[i].upList[0]) {
                    this.msgError(self.subjectData.listStudent[i].materialName + '未上传')
                    return
                  } else {
                    let upData = {
                      materialId: self.subjectData.listStudent[i].materialId,
                      dataName: self.subjectData.listStudent[i].materialName,
                      dataDescribe: self.subjectData.listStudent[i].materialDescribe,
                      dataUrl: ''
                    }
                    for (let o = 0; o < self.subjectData.listStudent[i].upList.length; o++) {
                      upData.dataUrl = upData.dataUrl + self.subjectData.listStudent[i].upList[o].name + ';' + self.subjectData.listStudent[i].upList[o].url + ','
                    }
                    obj.relList.push(upData)
                  }
                }
              }
            }
            this.$confirm('是否确认提交?', "", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(function() {
              if (self.infoType) {
                obj.applyId = self.infoData.labSecurityApply.applyId
                self.laboratoryApplyMaterialUpdate(obj)
              } else {
                self.laboratoryApplyMaterialAdd(obj)
              }
            }).then(() => {}).catch(() => {});
          }
        })

      },
      //删除对应资料
      delUpData(item, index) {
        item.upList.splice(index, 1)
        this.$forceUpdate()
      },
      //查看对应资料
      lookUpData(item, index) {
        this.$refs.preview.showViewer = true

        // this.$forceUpdate()
      },

      //上传相关
      handleAvatarSuccess(res, item) {
        let obj = {
          name: this.queryParams.userName + item.materialName + '.' + this.upDataName.split('.')[this.upDataName.split('.').length - 1],
          url: res.data.url
        }
        item.upList.push(obj)
        this.$forceUpdate()
      },
      beforeAvatarUpload(file, item) {
        let num = 0;
        for(let i=0;i<file.name.length;i++){
          if(file.name[i] == '.'){
            num++
          }
        }
        if(num != 1){
          this.msgError('文件名称不能包含 " . "')
          return false
        }
        let suffix = file.name.split('.')[file.name.split('.').length - 1]
        let suffixName = file.name.split('.')[file.name.split('.').length - 2]
        let fileTypeArr = item.fileType.split(',')
        let strArr = []
        fileTypeArr.forEach(function(item) {
          if (item == '1') {
            strArr.push('pdf')
          } else if (item == '2') {
            strArr.push('docx')
          } else if (item == '3') {
            strArr.push('png', 'jpg', 'gif')
          }
        })
        if (item.upList.length > 4) {
          this.msgError('已到达上传数量上限')
          return false
        }
        //判断文件名中是否有逗号和分号
        if (suffixName.indexOf(',') == -1 && suffixName.indexOf(';') == -1) {
        } else {
          this.msgError('文件名里包含逗号或分号，请修改后重新上传！')
          return false
        }
        if (strArr.indexOf(suffix) == -1) {
          this.msgError('请上传' + strArr.join(',') + '格式文件')
          return false
        }
        //学生名称+文件名称
        if (file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/jpg' || file.type == 'image/gif' || file.type == 'application/pdf' || file.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
          this.upDataName = file.name
          // type = true
        } else {
          this.msgError('只能上传png/jpeg/jpg/gif/docx格式')
          return false
        }
        return true
      },
      //实验室选择
      selectChange(e) {
        let self = this
        for (let i = 0; i < self.laboratoryOptions.length; i++) {
          if (self.laboratoryOptions[i].subId == e) {
            this.$set(this, 'subject', self.laboratoryOptions[i])
          }
        }
        this.$set(this.form, 'subjectId', e)
      },
      //获取当前实验室准入配置
      getApproval() {
        let self = this
        let obj = {
          subId: this.form.subjectId,
          remark: this.remark,
          startTime: this.dateRange[0] + 'T00:00:00',
          endTime: this.dateRange[1] + 'T23:59:59'
        }
        materialApply(obj).then(response => {
          if (response.data.sysUser.userType == '2') {
            if (!response.data.listStudent[0]) {
              this.msgError('该实验室未设置准入条件')
              return
            }
            if (response.data.listStudent) {
              for (let i = 0; i < response.data.listStudent.length; i++) {
                if (response.data.listStudent[i].materialType == 1) {
                  response.data.listStudent[i].upList = []
                }
              }
            }
            this.$set(this, 'subjectData', response.data)
            this.$set(this, 'queryParams', response.data.sysUser)
            //选择框禁用判定
            if (this.queryParams.tutorUserId) {
              this.$set(this.queryParams, 'tutorUserId', this.queryParams.tutorUserId)
              this.systemUserSelectUser(this.queryParams.tutorUserName)
            }
            this.minType = 2
            if (this.infoType) {
              this.form.validTime = this.infoData.labSecurityApply.validLength
              for (let i = 0; i < self.infoData.listTemp.length; i++) {
                if (self.infoData.listTemp[i].materialType == 1) {
                  if (self.subjectData.sysUser.userType == '2') {
                    for (let o = 0; o < self.subjectData.listStudent.length; o++) {
                      if (self.subjectData.listStudent[o].materialType == 1 && self.subjectData.listStudent[o].id == self.infoData.listTemp[i].id) {
                        self.subjectData.listStudent[o].upList = JSON.parse(JSON.stringify(self.infoData.listTemp[i].upList))
                      }
                    }
                  }
                }
              }
            }
          } else {
            this.msgError('您不是学生,无法申请准入')
          }
        })
      },
      //状态切换
      typeClick() {
        if (!this.form.subjectId) {
          this.msgError('请选择实验室')
          return
        }
        if (this.dateRange.length <= 0) {
          this.msgError('请选择申请期限')
          return
        }
        this.getApproval()
      },
      //返回
      backPage() {
        this.$parent.pageClick(1)
      },
      //懒加载
      userSelectList(e) {
        laboratorySubRelInfoGetRelListByPower({ subName: e }).then(response => {
          this.laboratoryOptions = response.data
        })
      }
    }
  }
</script>

<style scoped lang="scss">
  .approval_handle_addPage {
    .top-title-box {
      display: flex;
      border-bottom: 1px solid #E0E0E0;
      padding-top: 20px;
      p:nth-child(1) {
        flex: 1;
        line-height: 60px;
        color: #0045AF;
        font-size: 18px;
        margin: 0 0 0 40px;
      }
      p:nth-child(2) {
        margin-right: 20px;
      }
    }
    .addPage-max-box {
      flex: 1;
      padding: 20px 20px 20px !important;
      .addPage-type-one {
        .addPage-type-one-title {
          font-size: 16px;
          font-weight: 700;
          line-height: 18px;
          margin: 26px 38px;
        }
        .addPage-type-one-title-min {
          font-size: 14px;
          line-height: 16px;
          margin: 20px 62px 20px 0;
          color: #666666;
        }
      }
      .addPage-type-two {
        p {
          margin: 0;
        }
        .item-max-box {
          margin-left: 58px;
          .item-title-box {
            display: flex;
            p {
              font-size: 16px;
              line-height: 80px;
            }
            p:nth-child(1) {
              color: red;
              margin-right: 10px;
            }
            p:nth-child(2) {
              color: #333;
              font-weight: 700;
            }
            p:nth-child(3) {
              color: #999;
              font-weight: 700;
            }
          }
          .item-user-box {
            display: flex;
            margin-left: 15px;
            div {
              display: flex;
              margin-right: 60px;
              p {
                font-size: 14px;
              }
              p:nth-child(1) {
                color: #999;
              }
              p:nth-child(2) {
                color: #666;
              }
            }
          }
          .item-title-text {
            margin-left: 15px;
            font-size: 14px;
            line-height: 20px;
            color: #999;
          }
          .item-input-box {
            display: flex;
            margin: 20px 0 0 15px;
            input {
              width: 390px;
              height: 40px;
              padding: 0 20px;
              margin-right: 20px;
            }
          }
          .item-input-for-box {
            margin: 20px 0 0 5px;
            .item-input-for-big {
              display: inline-block;
              border-radius: 6px;
              background: rgba(1, 131, 250, 0.2);
              margin: 0 10px 10px;
              .item-input-for-min {
                display: flex;
                p {
                  flex: 1;
                  padding: 0 20px;
                  margin: 0;
                  line-height: 30px;
                  color: #0183FA;
                }
                i {
                  line-height: 30px;
                  color: #0183FA;
                  margin-right: 8px;
                  cursor: pointer;
                }
                a {
                  line-height: 30px;
                  color: #0183FA;
                  margin-right: 8px;
                  cursor: pointer;
                }
                img {
                  width: 16px;
                  height: 16px;
                  margin: 7px 7px;
                  cursor: pointer;
                }
              }
            }
          }
          .item-img-box {
            width: 240px;
            margin-left: 15px;
            cursor: pointer;
          }
        }
      }
    }
  }

  /*点击查看图片预览*/
  /*  .my-img {
      width: 10px;
      height: 10px;
      visibility: hidden;
    }*/
</style>
