//创建仓单
<template>
  <div class="center">
    <el-row>
      <el-col :span="12">
        <h2 class="bg-left titleup">创建仓单</h2>
      </el-col>
      <el-col :span="12" class="bg-right">
        <el-button class="bg-bottom" type="primary" size="small" @click="cancel"><img width="6" height="10"
            style="vertical-align: bottom; margin-right: 3px" src="../../../public/img/lujing.png" alt="" />返回
        </el-button>
      </el-col>
    </el-row>
    <el-form :inline="true" ref="deptBudgetList" label-position="right" class="content2" :rules="rules"
      :model="deptBudgetList" label-width="120px">
      <div class="title1">申请信息</div>
      <!-- <ws-info-table class="el-table"> -->
      <el-form-item label="业务编号" prop="billNo" class="forlist">
        <el-col>
          <el-input v-model="deptBudgetList.billNo" placeholder="请输入任务编号" maxlength="20" size="small" disabled>
          </el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="名头" prop="renown" class="forlist">
        <el-input v-model="deptBudgetList.renown" placeholder="请输入名头" maxlength="20" size="small" >
          </el-input>
        <!-- <el-select v-model="deptBudgetList.renown" placeholder="请选择名头" @change="changeCompOptionList" filterable clearable>
          <el-option :label="item.compName" :key="index" :value="item.compId" v-for="(item,index) in compOptionList">
          </el-option>
        </el-select> -->
      </el-form-item>
      <el-form-item label="仓库名称" prop="warehouseName" class="forlist">
        <el-select v-model="deptBudgetList.warehouseName" filterable placeholder="请选择仓库" @change="changeWarehouse" clearable>
          <el-option v-for="(item,index) in warehouseList" :key='index' :label="item.warehouseName" :value="item.warehouseName">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="仓位号" prop="warehouseNo" class="forlist">
        <el-select v-model="deptBudgetList.warehouseNo" placeholder="请选择仓位号" @change="changeWarehouseNo" filterable clearable>
          <el-option :label="item.binNumber" :value="item.binNumber" v-for="(item,index) in cwNumberList" :key='index'>
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="仓库地址" prop="warehouseAddress" class="forlist">
        <el-input disabled v-model="deptBudgetList.warehouseAddress" placeholder="请输入仓库地址" size="small"></el-input>
      </el-form-item>
      <el-form-item prop="goodsName" label="货名">
        <el-select disabled v-model="deptBudgetList.goodsName" placeholder="自动获取，不可编辑" @change="dataFlush" filterable clearable>
          <el-option v-for="item in goodsList" :key="item.goodsName" :label="item.goodsName"
                  :value="item.goodsName" >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item prop="grade" label="品级">
        <el-select v-model="deptBudgetList.grade" placeholder="请选择品级" filterable clearable>
          <el-option label="一等" value="一等"></el-option>
          <el-option label="二等" value="二等"></el-option>
          <el-option label="三等" value="三等"></el-option>
          <el-option label="等外" value="等外"></el-option>
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="现有储量" prop="nowWeight" class="forlist">
        <el-input disabled v-model="deptBudgetList.nowWeight" placeholder="请输入现有储量" size="small"></el-input>
      </el-form-item>
      <el-form-item label="可用储量（吨）" prop="useWeight" class="forlist">
        <el-input disabled v-model="deptBudgetList.useWeight" placeholder="请输入可用储量" size="small"></el-input>
      </el-form-item> -->
      <el-form-item label="货源" prop="weight" class="forlist supplyofgoods">
        <el-input disabled v-model="goodstext" placeholder="" size="small" @input='inputChange'>
        </el-input>
        <el-button @click='selectgoods' type="primary">选择货源</el-button>
      </el-form-item>
      <el-form-item label="本单重量（吨）" prop="weight" class="forlist">
        <el-input v-model="deptBudgetList.weight" placeholder="输入本次仓单申请所需的重量" size="small" >
        </el-input>
      </el-form-item>
      <el-form-item label="折干重量（吨）" prop="weight" class="forlist">
        <el-input v-model="deptBudgetList.dryOutWeight" placeholder="输入折干重量" size="small" @input='inputChange'>
        </el-input>
      </el-form-item>
      <el-form-item label="单价（元/吨）" prop="unitPrice" class="forlist">
        <el-input v-model="deptBudgetList.unitPrice" placeholder="输入粮食单价" size="small" @input='inputChange'></el-input>
      </el-form-item>
      <el-form-item label="货值（元）" prop="totalValue" class="forlist">
        <el-input type='number' disabled v-model="deptBudgetList.totalValue" placeholder="自动计算，不可编辑" size="small"></el-input>
      </el-form-item>
      <el-form-item label="申请金额（元）" prop="interest" class="forlist">
        <el-input type='number' v-model="deptBudgetList.interest" placeholder="输入申请金额" size="small"></el-input>
      </el-form-item>
      <div>附件</div>
      <ws-upload ref="upload" :comp-id="compId" :appendix-ids="deptBudgetList.appendix" :size-limit="size"
        @onChange="onChange" accept=".jpg, .jpeg, .png, .pdf, .doc, .zip, .rar" />
      <div>外审部门</div>
      <el-form-item prop="bank" label="银行">
        <el-select v-model="deptBudgetList.bank" placeholder="请选择银行" @change="bankChange">
          <el-option :label="item.constValue" :value="item.constValue" v-for="(item,index) in bankList" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="第三方" span="1" prop="three" class="forlist">
        <el-select v-model="deptBudgetList.three" placeholder="无" @change="threeChange" filterable clearable>
          <el-option :label="item1.constValue" :value="item1.constValue" v-for="(item1,index) in threeList" :key="index"></el-option>
          <!-- <el-option label="第三方2" value="three2"></el-option> -->
        </el-select>
      </el-form-item>
      <div>
        <el-button @click='inoutput' type="primary" :disabled="!deptBudgetList.goodsName">出入库记录</el-button>
        <el-button @click='submit' type="primary">提交审核</el-button>
      </div>
      <!-- </ws-info-table> -->
    </el-form>

  </div>
</template>
<script>
  import {
    getcompList,
  } from '@/model/signIn/index'
  import {
    addList,
    getbillno,
    WarehouseReceiptBankList,
  } from '@/model/tradeServicesManagement/index'

  import {
    xiala
  } from '@/model/warehouse/index'
  import {
    getcomp
  } from '@/model/indexRx'
  import * as global from '@/global'
  import WsUpload from '@/components/WsUpload'
  export default {
    components: {
      WsUpload,
    },
    data() {
      return {
        deptBudgetList: {
          goodsName:'',
          goodsNameKey:'',
          useWeight:'',
          nowWeight:'',
          warehouseNo:'',
          warehouseName:'',
          renown:'',
          weight:'',
          interest:''
        },
        size: 10,
        compId: '',
        warehouseList: [],
        compOptionList: [],
        cwNumberList: [],
        goodsList: [],
        db:{},
        goodstext:'已选0辆车',
        rules: {
          // unitPrice: [
          //   { required: true, message: '单价不能为空！', trigger: 'blur' },
          //   { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          // ],
        },
        bankList:[],
        threeList:[],
      }
    },
    async activated() {
      this.compId = localStorage.getItem('ws-pf_compId')
      this.deptBudgetList.compId = this.compId
      this.deptBudgetList.renownId = this.compId
      this.deptBudgetList.renown=localStorage.getItem('ws-pf_compName')
      // 
      let i = localStorage.getItem('pageUp')
      this.getList()
      
      // getcomp({userMobilePhone:JSON.parse(localStorage.getItem('ws_login_getTenantInfoByUser')).loginInfo.userMobilePhone}).toPromise().then((res)=>{
        console.log(localStorage.getItem('ws-pf_compName'))
        this.deptBudgetList.renown=localStorage.getItem('ws-pf_compName')
      // })
      this.db=await global.default.openDB('warehouseReceipt')
      if(localStorage.getItem('warehouseReceiptdata')){
        this.deptBudgetList=JSON.parse(localStorage.getItem('warehouseReceiptdata'))
        var data=await global.default.getDataByKey(this.db,'signalChat',1)
        if(data){
          this.deptBudgetList.weight=''
          var weight = 0
          var pureWeight = 0
          if(data.modification&&data.modification.length>0){

            this.goodstext='已选'+data.modification.length+'辆车'
            for(let i=0;i<data.modification.length;i++){
              weight+=data.modification[i].netWeight
              pureWeight+=data.modification[i].pureWeight
            }
            this.deptBudgetList.goodsName = data.modification[0].goodsName
            this.dataFlush()
            this.deptBudgetList.weight = weight.toFixed(2)
            if(this.deptBudgetList.goodsName.indexOf('潮粮')!=-1){
              this.deptBudgetList.dryOutWeight = pureWeight.toFixed(2)
            }else{
              this.deptBudgetList.dryOutWeight = weight.toFixed(2)
            }
            if( this.deptBudgetList.unitPrice){
              this.inputChange()
            }
          }
        }
      }
      // console.log(this.deptBudgetList)
      
        
    },
    methods: {
      selectgoods(){
        localStorage.setItem('warehouseReceiptdata',JSON.stringify(this.deptBudgetList))
        this.$router.push({
          name: 'warehouseReceiptgoods',
          query: {
            baseId: this.deptBudgetList.baseId,
            positionId: this.deptBudgetList.warehouseNoId,
            warehouseName: this.deptBudgetList.warehouseName,
            warehouseType: this.deptBudgetList.warehouseType,
            warehouseNo:this.deptBudgetList.warehouseNo,
          }
        })
      },
      inputChange(e) {
        if (this.deptBudgetList.unitPrice && this.deptBudgetList.dryOutWeight) {
          this.deptBudgetList.totalValue = Number(this.deptBudgetList.unitPrice * this.deptBudgetList.dryOutWeight).toFixed(2)
          this.$set(this.deptBudgetList,'interest',this.deptBudgetList.totalValue)
        }
      },
      //银行改变
      bankChange(e){ 
           this.deptBudgetList.bank = e
      },
      //第三方
      threeChange(e){
             this.deptBudgetList.three = e
      },
      getList() {
        // this.deptBudgetList.grade = '二等'
        WarehouseReceiptBankList({constId:'BANK1'}).toPromise().then((response) => {
          this.bankList = response
        })
         WarehouseReceiptBankList({constId:'THREE1'}).toPromise().then((response) => {
          this.threeList = response
        })

        // 获取业务编号
        getbillno().toPromise().then((response) => {
          this.deptBudgetList.billNo =  localStorage.getItem('ws-pf_compDomainName')+response
        })
        this.getWarehouse()
      },
      getcompList() {
        //获取公司名头
        getcompList()
          .toPromise()
          .then((res) => {
            this.compOptionList = res
            // this.deptBudgetList.renown = res[0].compName
             this.changeCompOptionList(res[0].compId)
          })
          .catch((err) => {})
      },
      getWarehouse() {
        //获取仓库
        xiala({
            compId: this.compId,
            warehouseType:1
          }).toPromise()
          .then(response => {
            console.log(response,76)
            this.warehouseList = response
            if(!this.deptBudgetList.warehouseName){
              this.deptBudgetList.warehouseName = response[0].warehouseName
              this.deptBudgetList.warehouseType = response[0].warehouseType
              this.deptBudgetList.warehouseAddress = response[0].warehousePrivate + response[0].warehouseCity + response[0].warehouseArea + response[0].detailedAddress
                if(response[0].positionInfos){
                  this.deptBudgetList.warehouseNoId = response[0].positionInfos.length != 0 ? response[0].positionInfos[0].id : ''
                  this.cwNumberList = response[0].positionInfos
                  this.deptBudgetList.warehouseNo = response[0].positionInfos.length != 0 ? response[0].positionInfos[0].binNumber : ''
                  this.deptBudgetList.baseId = response[0].positionInfos.length != 0 ? response[0].positionInfos[0].baseId : ''
                }
                if(response[0].goodsNameInfos){
                  this.goodsList = []
                  for(let i = 0 ; i < response[0].goodsNameInfos.length ; i++){
                    if(response[0].goodsNameInfos[i].binNumber ==  this.deptBudgetList.warehouseNo ){
                      this.goodsList.push(response[0].goodsNameInfos[i])
                    }
                  }
                }
                
              this.deptBudgetList.warehouseId = response[0].id
            }
            if (!this.deptBudgetList.renown) this.deptBudgetList.renown = this.compOptionList[0].compName
            if (!this.deptBudgetList.renownId) this.deptBudgetList.renownId = this.compOptionList[0].compId
          })
      },
      //货名切换
      // changeGoodsName(val) {
      //   let _data = this.goodsList
      //   for (let i = 0; i < _data.length; i++) {
      //     if (_data[i].goodsName == val) {
      //       this.deptBudgetList.goodsNameKey = _data[i].goodsNameKey
      //       this.deptBudgetList.goodsName = _data[i].goodsName
      //       this.deptBudgetList.nowWeight = _data[i].storage
      //       this.deptBudgetList.useWeight =  _data[i].useStorage                                       
      //     }
      //   }
      // },
      dataFlush(){
        for (let i = 0; i < this.warehouseList.length; i++) {
          if (this.warehouseList[i].warehouseName == this.deptBudgetList.warehouseName) {
            let tmpGoodsName = this.warehouseList[i].goodsNameInfos;
            for(let j = 0;j<tmpGoodsName.length;j++){
              if(tmpGoodsName[j].binNumber == this.deptBudgetList.warehouseNo){
                if(tmpGoodsName[j].goodsName == this.deptBudgetList.goodsName){
                  this.deptBudgetList.useWeight = tmpGoodsName[j].useStorage;
                  this.deptBudgetList.nowWeight = tmpGoodsName[j].storage;
                }
              }
            }                                   
          }
        }
      },
      //银行切换
      changeBank(val) {
        this.deptBudgetList.bankId = 'changebankId'
      },
      //第三方切换
      changeThree(val) {
        this.deptBudgetList.threeId = 'changethreeId'
      },
      //仓位号切换
      changeWarehouseNo(val) {
        debugger
        let _data = this.cwNumberList
        for (let i = 0; i < _data.length; i++) {
          if (_data[i].binNumber == val) {
            this.deptBudgetList.warehouseNoId = _data[i].id
            this.deptBudgetList.warehouseNo = _data[i].binNumber
            this.deptBudgetList.baseId = _data.baseId
          }
        }
        this.goodsList = []
        for(let j = 0 ; j < this.warehouseList.length ; j++){
          if(this.deptBudgetList.warehouseName == this.warehouseList[j].warehouseName){
            for(let _num = 0 ; _num < this.warehouseList[j].goodsNameInfos.length; _num++ ){
              if( this.deptBudgetList.warehouseNo == this.warehouseList[j].goodsNameInfos[_num].binNumber){
                this.goodsList.push(this.warehouseList[j].goodsNameInfos[_num])
              }
            }
          }
        }
       
      },
      // 名头切换
      changeCompOptionList(val) {
        let _data = this.compOptionList
        for (let i = 0; i < _data.length; i++) {
          if (_data[i].compId == val) {
            this.deptBudgetList.renownId = _data[i].compId
            this.deptBudgetList.renown = _data[i].compName
            this.compId = val
            this.getWarehouse()
          }
        }
      },
      //仓库切换
      async changeWarehouse(val) {
        
        let _data = this.warehouseList
        
        for (let i = 0; i < _data.length; i++) {
          if (_data[i].warehouseName == val) {          
            var data=await global.default.getDataByKey(this.db,'signalChat',1)
            if(data){
              if(data.modification&&data.modification.length>0){
                global.default.deleteDB(this.db,'signalChat',1)
                this.deptBudgetList.weight = ''
                this.deptBudgetList.dryOutWeight = ''
              }
            }
            
            this.goodstext='已选0辆车'
            this.deptBudgetList.warehouseName = _data[i].warehouseName
            this.cwNumberList = _data[i].positionInfos.length != 0 ? _data[i].positionInfos : []
            this.deptBudgetList.warehouseNo = _data[i].positionInfos.length != 0 ? _data[i].positionInfos[0].binNumber : ''
            this.deptBudgetList.warehouseAddress = _data[i].warehousePrivate + _data[i].warehouseCity + _data[i].warehouseArea + _data[i].detailedAddress
            // this.goodsList = _data[i].goodsNameInfos.length != 0 ? _data[i].goodsNameInfos : []
            
            this.deptBudgetList.warehouseId = _data[i].id
            this.deptBudgetList.warehouseType = _data[i].warehouseType
            this.deptBudgetList.warehouseNoId = _data[i].positionInfos.length != 0 ? _data[i].positionInfos[0].id : ''
            this.deptBudgetList.baseId = _data[i].positionInfos.length != 0 ? _data[i].positionInfos[0].baseId : ''
          }
        }
        console.log('切换后仓库数据', this.deptBudgetList.warehouseId)
        
        this.changeWarehouseNo(this.deptBudgetList.warehouseId)
      },
      inoutput() {
        this.$router.push({
          name: 'inOutRecord',
          query: {
            baseId: this.deptBudgetList.baseId,
            positionId: this.deptBudgetList.warehouseNoId,
            warehouseName: this.deptBudgetList.warehouseName,
            warehouseNo:this.deptBudgetList.warehouseNo,
            nowWeight:this.deptBudgetList.nowWeight
          }
        })
      },
      validate() {
        function _Validate(min, max, saveNum, type, inputVal) {
          let _val1 = inputVal
          let _pointVal1 = _val1.toString().split('.')[1]
          if (_pointVal1 == undefined) _pointVal1 = 0
          if (typeof(_pointVal1) == 'string') _pointVal1 = _pointVal1.length
          if (Number(_val1) <= Number(max) && Number(_val1) >= Number(min) && _pointVal1 <= saveNum) {
            return false
          }
          return true
        }
        if (!this.deptBudgetList.weight) {
            this.$message.error('本单重量不能为空！');
          return false
        }
        if (!this.deptBudgetList.unitPrice || _Validate(1, 20000, 3, '', this.deptBudgetList
            .unitPrice)) {
          if (!this.deptBudgetList.unitPrice) {
            this.$message.error('单价不能为空！');
          } else {
            this.$message.error('单价输入错误,1-20000之间,最多保留3位小数！');
          }
          return false
        }
        if (!this.deptBudgetList.totalValue) {
          this.$message.error('总价值不能为空！');
          return false
        }
        // if (!this.deptBudgetList.applicationProportion || _Validate(10, 100, 2, '', this.deptBudgetList
        //     .applicationProportion)) {
        //   if (!this.deptBudgetList.applicationProportion) {
        //     this.$message.error('申请比例不能为空！');
        //   } else {
        //     this.$message.error('申请比例输入错误,10-100之间,最多保留2位小数！');
        //   }
        //   return false
        // }
        if (!this.deptBudgetList.interest || _Validate(1, 1000000000, 2, '', this.deptBudgetList
            .interest)) {
          if (!this.deptBudgetList.interest) {
            this.$message.error('申请金额不能为空！');
          } else {
            this.$message.error('申请金额输入错误,1-10亿之间,最多保留2位小数！');
          }
          return false
        }
        if (!this.deptBudgetList.appendix) {
          console.log(this.deptBudgetList.appendix)
          this.$message.error('附件不能为空！');
          return false
        } else if (this.deptBudgetList.appendix.split(',').length > 30) {
          this.$message.error('附件数量需小于30！');
          return false
        }
        if (!this.deptBudgetList.bank) {
          this.$message.error('银行不能为空！');
          return false
        }
        // if (!this.deptBudgetList.three) {
        //   this.$message.error('第三方不能为空！')
        //   return false
        // }
        return true
      },
      async submit() {
        var data=await global.default.getDataByKey(this.db,'signalChat',1)
        if(data){
          if(data.modification){
            this.deptBudgetList.warehouseInOutInfoList=data.modification
          }
        }
        
        let isValidate = false
        console.log(this.validate())
        isValidate = this.validate()
        console.log(isValidate)
        if (isValidate) {
          this.$confirm(`确定提交审核？`, {
            cancelButtonText: '取消',
            confirmButtonText: '确定',
            type: 'warning',
          }).then(() => {
            addList(this.deptBudgetList).toPromise().then((response) => {
              // this.tableData = response.records
              localStorage.removeItem('pageUp')
              localStorage.removeItem('warehouseReceiptdata')
              this.$message.success('提交成功')
              global.default.deleteDB(this.db,'signalChat',1)
              this.$router.push({
                path: 'warehouseReceiptRegulation'
              })
            }).catch((req) => {
              // this.tableData = response.records
              this.$message.error('提交失败')
            })
          })
        }
      },
      onChange() {
        this.$refs.upload
          .handleSaveBill()
          .then(async response => {
            this.deptBudgetList.appendix = response
          })
          .catch(res => {
            EventBus.$emit('error', (JSON.parse(res) || {}).message)
            this.$refs.upload.clearFiles()
          })
      },
      cancel() {
        localStorage.removeItem('pageUp')
        localStorage.removeItem('pageUp')
        localStorage.removeItem('warehouseReceiptdata')
        global.default.deleteDB(this.db,'signalChat',1)
        this.$router.push({
          path: 'warehouseReceiptRegulation'
        })
      },
    },
  }
</script>
<style lang="scss" scoped>
  /deep/.el-form-item__content {
    width: 400px;
  }

  /deep/.el-select {
    width: 100%;
  }

  .el-form {
    overflow: scroll;
    height: 94vh;
  }

  .bg-left {
    padding-left: 30px;
  }

  .bg-bottom {
    margin: 15px 0px;
  }

  .titleup {
    position: relative;
  }

  .titleup::before {
    content: '';
    display: inline-block;
    width: 5px;
    height: 30px;
    background: #5473e8;
    position: absolute;
    left: 0;
  }

  .bg-right {
    padding-right: 10px;
    text-align: right;
  }

  .center {
    background: #f6f7fc;
  }

  .content2 {
    background: white;
    // padding:0 200px;
    // text-align: center;
    padding-left: 40px;
  }


  .title1 {
    font-size: 20px;
    font-weight: 600;
    margin: 20px 0;
  }
  .supplyofgoods .el-input{
    width:75%;
  }
</style>
