<!--资格申请-添加-->
<template>
  <div class="addPage">
    <div class="addPage_title">
      <p>资格申请</p>
      <P>填写申请信息，内容提交后需要进行审核，通过审核才能够申请气瓶进行使用。如课题组申请，仅需一人进行填报即可。  </P>
      <p class="button-p reset-button-one" @click="backPage">返回</p>
    </div>
    <div class="addPage_b">
      <div class="addPage_b_t">
          <li>
            <img src="@/assets/ZDimages/icon_jbxx_xz.png"/>
            <p>填写基本信息</p>
          </li>
          <i></i>
          <li>
            <img v-if="pageType==1" src="@/assets/ZDimages/icon_xxrp_zc.png"/>
            <img v-if="pageType==2"  src="@/assets/ZDimages/icon_xxrp_xz.png"/>
            <p>选择气瓶</p>
          </li>
      </div>
      <!--申请1-->
      <div v-if="pageType==1">
        <el-form class="addPage_b_b" :model="form" ref="form" :rules="rules" label-position="right" label-width="100px">
          <el-form-item label="申请人" prop="applyCause" >
            <el-input  style="width: 300px" v-model="form.applyUser" disabled  maxlength="50" />
          </el-form-item>
          <el-form-item label="联系方式" prop="phone" >
            <el-input  style="width: 300px" v-model="form.phone"  placeholder="请输入联系方式" maxlength="50" />
          </el-form-item>
          <el-form-item label="实验地点" prop="subjectId">
            <el-select
              style="width:300px;"
              v-model="form.location"
              filterable
              remote
              clearable
              reserve-keyword
              @focus="selectFocus"
              @change="selectChange"
              placeholder="请选择实验地点"
              :remote-method="userSelectList"
              :loading="loading">
              <el-option
                v-for="item in laboratoryOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="使用期限" prop="dateRange" >
            <el-date-picker
              :clearable="false"
              v-model="form.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="gasUse" >
            <el-input  style="width: 300px" v-model="form.gasUse"  placeholder="请输入气体用途" maxlength="50" />
          </el-form-item>
          <el-form-item label="安全措施" prop="safetyPrecautions" >
            <el-input  style="width: 300px" v-model="form.safetyPrecautions"  placeholder="请输入安全措施" maxlength="50" />
          </el-form-item>
          <el-form-item label="用气申请表" prop="applyCertificate" >
            <el-upload
              class="certificate-avatar-uploader"
              :action="uploadImgUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :headers="headers"
              :before-upload="beforeAvatarUpload">
              <div style="display: flex;">
                <img v-if="form.applyCertificate" :src="form.applyCertificate" style="width: 80px;height: 80px;margin-right: 10px">
                <i v-if="!form.applyCertificate" class="el-icon-plus avatar-uploader-icon"></i>
              </div>
            </el-upload>
          </el-form-item>

        </el-form>
        <p class="inquire-button-one" style="width:400px;margin:36px 0 16px 38%;" @click="handleClick('','form','next')">下一步</p>
      </div>
      <!--申请2-->
      <div v-if="pageType==2" class="apply_tow">
        <el-form :model="queryParams" ref="queryForm" style="margin-top:20px;" :inline="true">
          <el-form-item label="关键字" prop="name">
            <el-input
              @submit.native.prevent
              v-model="queryParams.searchValue"
              placeholder="气体名称/气瓶厂家"
              clearable
              maxLength="30"
              size="small"
            />
          </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>
          <div class="selected" @click="handleClick('','','selected')">已选气瓶  {{totalNum}}</div>
        </el-form>
        <el-table border v-loading="loading" :data="tableData">
          <el-table-column label="气体名称" align="left" prop="airName"/>
          <el-table-column label="气体级别/规格" align="left" prop="configName"></el-table-column>
          <el-table-column label="气瓶厂家" align="left" prop="companyName"></el-table-column>
          <el-table-column label="气体组分" align="left" prop="airConstituents"></el-table-column>
          <el-table-column label="操作" align="left" prop="bottleNumber"  width="240">
            <template slot-scope="scope">
              <template>
                <el-input-number v-model="scope.row.bottleNumber" @change="numberFun()" :min="0"  size="mini"></el-input-number>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <pagination :page-sizes="[20, 30, 40, 50]"
          :total="total"
          layout="total, prev, pager, next, sizes, jumper"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getListGood"
        />
        <div class="sub_btn">
          <p class="reset-button-one" style="width:150px;margin-right: 30px" @click="handleClick('','','last')">返回上一步</p>
          <p class="inquire-button-one" style="width:150px;" @click="submitForm">提交申请</p>
        </div>
      </div>
    </div>
    <el-dialog  :visible.sync="dialogVisible">
      <el-table v-loading="loading" :data="form.listDetailVo" height="500">
        <el-table-column label="气体名称" align="left" prop="airName"/>
        <el-table-column label="气体级别/规格" align="left" prop="configName"></el-table-column>
        <el-table-column label="气瓶厂家" align="left" prop="companyName"></el-table-column>
        <el-table-column label="气体组分" align="left" prop="airConstituents"></el-table-column>
        <el-table-column label="数量" align="left" prop="bottleNumber"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import {
  getListGood,
  getLoginUser,
  qualificationApplyAdd,
  qualificationApplyDetail,
  subjectList,
  qualificationApplyAnew, getValidApply
} from '@/api/gasManage3_0/gasManage'

export default {
  name: "addPage",
  props:{
    pageData:{},
  },
  data() {
    // 时间的校验
    const validateTime = (rule, value, callback) => {
      console.log(value)
      if(value && value.length>0){
        this.form.startTime=value[0]
        this.form.endTime=value[1]
        callback();
      }else{
        this.form.startTime=null;
        this.form.endTime=null
        callback(new Error('请选择使用期限'))
      }
    }
    return {
      pageType:1,
      uploadImgUrl: this.uploadUrl(), // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 设置只能选择当前日期及之后的日期
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的
        }
      },
      loading:false,
      form:{
        deptId:'',
        applyUser:'',
        applyUserid:'',
        phone:'',
        location:'',
        subjectId:'',
        startTime:'',
        endTime:'',
        gasUse:'',
        safetyPrecautions:'',
        applyCertificate:'',
        dateRange:[],
        listDetailVo:[],
      },
      laboratoryOptions:[],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize:20,
        searchValue:'',
      },
      total:0,
      tableData:[],
      dialogVisible:false,
      totalNum:0,//所选气瓶总数
      status:0,//0添加1编辑
      // 表单校验
      rules: {
        phone: [
          { required: true, message: "请输入联系方式", trigger: "blur" },
          { required: true, message: "请输入联系方式", validator: this.spaceJudgment, trigger: "blur" },
          { pattern:/^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(16[0-9])|(17[0,3,5-8])|(18[0-9])|(147))+\d{8}$/, message: "请输入正确的联系方式", trigger: "blur" }
        ],
        subjectId: [
          { required: true, message: "请选择实验地点", trigger: "blur" }
        ],
        gasUse: [
          { required: true, message: "请输入气体用途", trigger: "blur" },
          { required: true, message: "请输入气体用途", validator: this.spaceJudgment, trigger: "blur" }
        ],
        safetyPrecautions: [
          { required: true, message: "请输入安全措施", trigger: "change" },
          { required: true, message: "请输入安全措施", validator: this.spaceJudgment, trigger: "blur" }
        ],
        applyCertificate: [
          { required: true, message: "请上传用气申请表", trigger: "change" }
        ],
        dateRange: [
          {required: true, validator: validateTime, trigger: 'blur' },
        ],
      },
    };
  },
  methods: {
    selectFocus(){
      if(!this.laboratoryOptions[0]){
        this.userSelectList("");
      }
    },
    handleClick(index,row,doType){
      let _this=this;
      if(doType=='next'){//下一步
        //非空校验
        this.$refs[row].validate((valid) => {
          if (valid) {
            _this.pageType=2;
          } else {
            return false;
          }
        });
      }else if(doType=='last'){//上一步
        _this.pageType=1;
      }else if(doType=='selected'){//已选气瓶
        _this.dialogVisible=true
      }
    },
    /** 获取当前用户信息 */
    getLoginUser() {
      let _this=this;
      getLoginUser().then( response => {
        let res=response.data
        _this.form.applyUser=res.nickName
        _this.form.applyUserid=res.userId
        _this.form.phone=res.phonenumber
        _this.form.deptId=res.deptId

      });
    },
    //懒加载实验室
    userSelectList(e){
      subjectList({name:e,deptId:this.form.deptId}).then(response => {
        this.laboratoryOptions = response.data;
      });
    },
    //实验室选择
    selectChange(e){
      let self = this;
      for(let i=0;i<self.laboratoryOptions.length;i++){
        if(self.laboratoryOptions[i].id == e){
          this.$set(this.form,"subject",self.laboratoryOptions[i]);
          this.$set(this.form,"location",self.laboratoryOptions[i].name);
        }
      }
      this.$set(this.form,"subjectId",e);
      //校验实验室的准入资格
      this.getValidApply();
    },
    //校验实验室的准入资格
    getValidApply(){
      let _this = this;
      let obj={
        userId:_this.form.applyUserid,
        subjectId:_this.form.subjectId
      }
      getValidApply(obj).then(res => {
        if(res.data.length<=0){
          this.$message.error('请先申请('+this.form.location+')实验室准入资格!');
          this.form.location='';
        }
      });
    },
    /** 获取气瓶列表 */
    getListGood() {
      let _this=this;
      getListGood(_this.queryParams).then( response => {
        let res=response.rows;

      console.log('status',this.status)
        if(this.status==0){//新增
          _this.tableData=res;
          _this.total=response.total
        }else if(this.status==1){//编辑
          _this.tableData=res;
          _this.total=response.total
          //渲染气瓶信息数据
          _this.tableData.forEach(function(item){
            _this.form.listDetailVo.forEach(function(item2){
              if(item.id==item2.airBottleConfigId){
                item.bottleNumber=item2.bottleNumber
                _this.totalNum+=item2.bottleNumber;
              }
            })

          })
        }
      });
    },
    /* 计算所选气瓶 */
    numberFun(){
      let _this=this;
      _this.totalNum=0;
      _this.form.listDetailVo=[];
      _this.tableData.forEach(function(item){
          if(item.bottleNumber){
              _this.totalNum+=item.bottleNumber;
              _this.form.listDetailVo.push(item);

              _this.form.listDetailVo.forEach(function(item){
                  item.gasLevel=item.parent
                  item.gasNorms=item.specValue
              })
          }
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getListGood();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.searchValue = "";
      this.handleQuery();
    },
    //上传
    handleAvatarSuccess(res, file) {
      console.log(res.data.url);
      this.form.applyCertificate = res.data.url;
      this.$forceUpdate()
    },
    beforeAvatarUpload(file) {
      let type = false;
      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;
    },
    /* 详情 */
    getInfo(id){
      let _this=this;
      qualificationApplyDetail({id:id}).then( response => {
        let res=response.data;
        if(response.code==200){
          let dateRange=[];
          _this.totalNum=0;
           dateRange.push(res.apply.startTime,res.apply.endTime)
          _this.form.id=res.apply.id;
          _this.form.applyUser=res.apply.applyUser;
          _this.form.phone=res.apply.phone;
          _this.form.location=res.apply.location;
          _this.form.subjectId=String(res.apply.subjectId);
          _this.form.startTime=res.apply.startTime;
          _this.form.endTime=res.apply.endTime;
          _this.form.gasUse=res.apply.gasUse;
          _this.form.applyCertificate=res.apply.applyCertificate;
          _this.form.safetyPrecautions=res.apply.safetyPrecautions;
          _this.form.dateRange=dateRange;
          _this.form.listDetailVo=res.airBottlelist;
          _this.getListGood()
        }
      });

    },
    //提交
    submitForm(){
      let _this = this;
      if(_this.form.listDetailVo.length>0){
        _this.loading = true;
        if(_this.status==0){//新增
          qualificationApplyAdd(_this.form).then(res => {
            this.msgSuccess(res.msg);
            _this.backPage();
          });
        }else if(_this.status==1){
          qualificationApplyAnew(_this.form).then(res => {
            this.msgSuccess(res.msg);
            _this.backPage();
          });
        }
      }else{
        _this.msgError('请先选择气瓶!')
      }

    },

    //返回
    backPage(){
      this.$parent.handleClick('','','back');
      this.$parent.getList();
    },

  },
  mounted() {

    this.status=this.pageData.status;
    if(this.status==1){
      this.getInfo(this.pageData.id)
    }else{
      this.getLoginUser()
      this.getListGood()
    }

  }

};
</script>

<style scoped lang="scss">
.addPage {
  flex:1;
  display: flex!important;
  flex-direction: column;
  box-shadow: 0 0 8px 2px rgba(0, 0, 0, 0.1);
  border-radius:10px;
  /*顶部*/
  .addPage_title{
    display: flex;
    align-items: center;
    border-bottom: 1px solid #E0E0E0;
    padding-top:20px;
    p:nth-child(1){
      line-height:60px;
      color: #0045AF;
      font-size:18px;
      margin:0 12px 0 20px;
    }
    p:nth-child(2){
      font-size: 14px;
      font-family: Source Han Sans CN;
      font-weight: 400;
      color: #999999;
      flex: 1;
    }
    p:nth-child(3){
      margin-right:20px;
    }
  }

  .addPage_b{
    flex: 1;
    display: flex!important;
    flex-direction: column;
    /*时间轴*/
    .addPage_b_t{
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 36px;
      >li{
        width: 120px;
        text-align: center;
        list-style-type: none;
        >img{
          width: 60px;
          height:60px;
        }
        >p{
          font-size: 16px;
          font-family: Microsoft YaHei;
          font-weight: 400;
          color: #333333;
          line-height: 16px;
        }
      }
      >i{
        display: inline-block;
        width: 250px;
        height: 2px;
        background: #E0E0E0;
        position: relative;
        top: -24px;
      }
    }
    .addPage_b_b{
      margin-top: 58px;
      margin-left: 36%;
    }
    /*申请二*/
    .apply_tow{
      padding: 0 20px;
      box-sizing: border-box;
      flex: 1;
      display: flex!important;
      flex-direction: column;
      .selected{
        display: inline-block;
        font-size: 14px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #0045AF;
        float: right;
        cursor: pointer;
      }
      .sub_btn{
        display: flex;
        justify-content: center;
        margin: 30px 0;
      }
    }
  }

}
</style>
