<!--资格申请-添加-->
<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">
      <!--申请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="useGasId" >
            <el-select class="min-width" placeholder="请选择使用气体" v-model="form.useGasId" filterable clearable  @change="useGasFun" style="width: 300px">
              <el-option
                v-for="(item,index) in useGasList"
                :key="item.id"
                :label="item.goodsName"
                :value="item.id">
              </el-option>
            </el-select>
          </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>
    </div>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import {
  bottleList,
  getLoginUser, googsListGoogs,
  subjectList,
  useAgsApplyAdd,
  useAgsApplyAnew,
  useAgsApplyDetail,
  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:'',
        useGasName:'',
        useGasId:'',
        gasUse:'',
        safetyPrecautions:'',
        applyCertificate:'',
        dateRange:[],
      },
      laboratoryOptions:[],
      useGasList:[],
      // 查询参数
      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" }
        ],
        useGasId: [
          { 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(){
      console.log("123");
      if(!this.laboratoryOptions[0]){
        this.userSelectList("");
      }
    },
    handleClick(index,row,doType){
      let _this=this;
      if(doType=='next'){//下一步
        //非空校验
        this.$refs[row].validate((valid) => {
          if (valid) {
            _this.submitForm();
          } 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

      });
    },
    /** 获取使用气体信息 */
    googsListGoogs() {
      let _this=this;
      googsListGoogs().then( response => {
        let res=response.rows
        _this.useGasList=res;

      });
    },
    useGasFun(){
     let _this=this;
      _this.useGasList.forEach(function(item){
        if(_this.form.useGasId==item.id){
          _this.form.useGasName=item.goodsName;
        }
      })
      console.log(_this.form.useGasId)
      console.log(_this.form.useGasName)
    },
    //懒加载实验室
    userSelectList(e){
      subjectList({name:e}).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='';
        }
      });
    },
    //上传
    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;
      useAgsApplyDetail({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.useGasId=res.apply.useGasId;
          _this.form.useGasName=res.apply.useGasName;
          _this.form.dateRange=dateRange;
        }
      });

    },
    //提交
    submitForm(){
      let _this = this;
      _this.loading = true;
      if(_this.status==0){//新增

        useAgsApplyAdd(_this.form).then(res => {
          this.msgSuccess(res.msg);
          _this.backPage();
        });
      }else if(_this.status==1){
        useAgsApplyAnew(_this.form).then(res => {
          this.msgSuccess(res.msg);
          _this.backPage();
        });
      }

    },

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

  },
  mounted() {
    this.getLoginUser()
    this.googsListGoogs()
    this.status=this.pageData.status;
    if(this.status==1){
      this.getInfo(this.pageData.id)
    }

  }

};
</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_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>
