<template>
  <div class="storage">
    <div class="btn-click">
      <span class="base-color" @click="saveClick()">保存</span>
      <span class="clear" @click="saveClick('clear')">取消</span>
    </div>
    <div class="storage-info">
      <div class="linetext">{{switchType === 'INBOUND' ? '入库单' : '出库单'}}：<span>系统自动生成</span></div>
      <div class="linetext">{{switchType === 'INBOUND' ? '卖家名称' : '买家名称'}}：
        <span><input type="text" v-model="enName" :placeholder="switchType === 'INBOUND' ? '请输入卖家名称' : '请输入买家名称'"></span>
      </div>
      <div class="linetext">录入人： <span v-text="user.logged">21324</span></div>
      <div class="linetext">录入时间： <span v-text="baseUtils.formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')">21324</span></div>
    </div>
    <ul class="list-unstyled">
      <li class="info-list clearfix" v-for="(item, index) in allObj">
        <span class="super"><em v-text="index + 1">1</em></span>
        <div class="linetext width50 fl">型号：
          <span>
            <input type="text" style="width:2rem;" v-model="item.cmpCode" @input="onCodeChange(index)">
          </span>
        </div>
        <div class="linetext width50 fl">品牌： <span v-text="item.brand">21324</span></div>
        <div class="linetext width50 fl">物料名称： <span v-text="item.pcmpcode">21324</span></div>
        <div class="linetext width50 fl">规格： <span v-text="item.spec">21324</span></div>
        <div class="linetext width50 fl">库存数： <span v-text="item.erpReserve">21324</span></div>
        <div class="linetext width50 fl"><em>*</em>{{switchType === 'INBOUND' ? '入库数' : '出库数'}}(PCS)： <span>
          <input type="text" style="width:1.1rem;" v-model="item.qty" @input="onAmountInput(item, index)">
        </span></div>
        <div class="linetext width50 fl">{{switchType === 'INBOUND' ? '采购单价' : '销售单价'}}({{currency === 'RMB' ? '¥': '$'}})：<span>
          <input type="text" style="width:1.2rem;" v-model="item.price" @blur="rMBPriceBlur(item, index)">
        </span></div>
        <div class="content-line" v-show="item.showSimilarCodeList && item.cmpCode">
          <ul class="similar">
            <li v-for="sCode in similarCode" @click.stop="setCode(sCode, index)">
              <span v-text="sCode.cmpCode"></span>
              <span v-text="sCode.brand"></span>
            </li>
          </ul>
        </div>
        <div class="look-btn">
          <span @click="addClick()" v-if="index === allObj.length - 1">新增</span>
          <span @click="addClick(index)" v-if="index !== 0">删除</span>
        </div>
      </li>
    </ul>
    <remind-box :title="remindText" :timeoutCount="timeoutCount"></remind-box>
  </div>
</template>
<script>
  import { RemindBox, PullUp, EmptyStatus } from '~components/mobile/common'
  export default {
    props: {
      switchType: {
        type: String,
        default: 'INBOUND'
      }
    },
    data () {
      return {
        remindText: '',
        timeoutCount:0,
        enName: '',
        allObj:[],
        storageObj: {
          cmpCode: '',
          brand: '',
          pcmpcode: '',
          spec: '',
          qty: '',
          price: '',
          erpReserve: '',
          showSimilarCodeList: false,
        },
        similarCode:[]
      }
    },
    components: {
      RemindBox
    },
    mounted () {
      let _this = this
      this.allObj.push(this.storageObj)
      document.body.onclick = function() {
        _this.allObj.forEach(val => {
          if(!val.productId) {
            val = {
              cmpCode: '',
              brand: '',
              pcmpcode: '',
              spec: '',
              qty: '',
              price: '',
              erpReserve: ''
            }
          }
          val.showSimilarCodeList = false
        })
      }
    },
    methods: {
      onRemind: function (str) {
        this.remindText = str
        this.timeoutCount++
      },
      setFilterType (type) {
        let bound = ''
        if(type === 'OTHER_INBOUND') {
          bound = '其他入库'
        } else if(type === 'OTHER_OUTBOUND'){
          bound = '其他出库'
        } else if (type === 'PURCHASE_INBOUND') {
          bound = '采购入库'
        } else if(type === 'SELL_OUTBOUND') {
          bound = '销售出库'
        } else {
          bound = '全部类型'
        }
        return bound
      },
      initData () {
        this.enName = ''
        this.allObj = []
        this.allObj.push({
          cmpCode: '',
          brand: '',
          pcmpcode: '',
          spec: '',
          qty: '',
          price: '',
          erpReserve: '',
          showSimilarCodeList: false,
        })
      },
      onCodeChange (type) {
        this.allObj[type].showSimilarCodeList = true
        this.allObj[type].cmpCode = this.allObj[type].cmpCode.trim()
        this.getSimilarCode(type)
      },
      getSimilarCode: function (type) {
        if (this.allObj[type].cmpCode) {
          this.$http.get('/trade/products/code/keyword', {params: {keyword: this.allObj[type].cmpCode}})
            .then(response => {
              if(response.data.length > 0){
                this.similarCode = response.data
              } else {
                this.similarCode = []
                this.allObj[type].cmpCode = ''
                this.allObj[type].brand = ''
                this.allObj[type].pcmpcode = ''
                this.allObj[type].spec = ''
                this.allObj[type].productId = ''
                this.allObj[type].erpReserve = ''
                this.onRemind('产品库中没有找到相应产品信息')
              }
              this.allObj[type].showSimilarCodeList = response.data.length > 0
            }).catch((err) => {
              this.similarCode = []
              this.allObj[type].cmpCode = ''
              this.allObj[type].brand = ''
              this.allObj[type].pcmpcode = ''
              this.allObj[type].spec = ''
              this.allObj[type].productId = ''
              this.allObj[type].erpReserve = ''
              this.onRemind('产品库中没有找到相应产品信息')
            })
        } else {
          this.allObj[type].showSimilarCodeList = false
        }
      },
      setCode (data, type) {
        this.allObj[type].cmpCode = data.cmpCode
        this.allObj[type].brand = data.pbranden
        this.allObj[type].pcmpcode = data.kind
        this.allObj[type].spec = data.spec
        this.allObj[type].productId = data.id
        this.allObj[type].erpReserve = data.erpReserve
        this.allObj[type].showSimilarCodeList = false
        if(data.erpReserve <= 0 && this.switchType === 'OUTBOUND') {
          this.onRemind('当前产品库存为0，不能出库！')
        }
      },
      addClick (type) {
        if(type) {
         this.allObj.splice(type, 1)
        } else {
          let _item = {
            cmpCode: '',
            brand: '',
            pcmpcode: '',
            spec: '',
            qty: '',
            price: '',
            erpReserve: '',
            showSimilarCodeList: false,
          }
          this.allObj.push(_item)
        }
      },
      onAmountInput: function (item, index) {
        if (!(/^[0-9]*$/).test(item.qty)) {
          let chineseIndex = -1
          for (let i = 0; i < item.qty.length; i++) {
            if (!(/^[0-9]*$/).test(item.qty.charAt(i))) {
              chineseIndex = i
              break
            }
          }
          this.allObj[index].qty = this.baseUtils.cutOutString(item.qty, chineseIndex)
        } else if (item.qty.length > 9) {
          this.onRemind ('数量不能高于10亿')
          this.allObj[index].qty = this.baseUtils.cutOutString(item.qty, 9)
        }
      },
      rMBPriceBlur(item) {
        if (item.price === '' || !item.price) { return false }
        if (!/^[0-9]+([.]{1}[0-9]{1,6})?$/.test(item.price)) {
          this.onRemind('单价只能输入数字带6位小数')
        } else if (Math.abs(item.price) === 0) {
          return false
        } else if (Math.abs(item.price) >= 10000) {
          item.price = 9999
          this.onRemind ('单价不能高于10000')
          return false
        }
        item.price = item.price.toString()
        let splits = item.price.split('.')
        if (splits[0].length >= 4) {
          splits[0] = splits[0].substr(0, 4)
          item.price = splits[0]
        }
        if (splits[1]) {
          item.price = splits[0] + '.' + splits[1]
        }
        if (splits[1] && splits[1].length > 6) {
          splits[1] = splits[1].substr(0, 7)
          let str = splits[1].substr(0, 6)
          if (splits[1][splits[1].length - 1] >= 5) {
            str = splits[1].substr(0, 6)
            str = Math.abs(str) + 1
          }
          item.price = splits[0] + '.' + Math.ceil(str)
        }
      },
      saveClick (type) {
        if(type === 'clear') {
          this.initData()
        }else {
          let arr = []
          let flag = 0;
          this.allObj.forEach(val => {
            if(val.productId) {
              if((val.erpReserve <= 0) && this.switchType === 'OUTBOUND'){
                flag = 1
              } else if((val.erpReserve < val.qty) && this.switchType === 'OUTBOUND') {
                flag = 2
              } else if(val.qty && Number(val.qty) <= 0) {
                flag = 3
              } else if(val.qty) {
                val.price ?
                  arr.push({price: Number(val.price), productId: val.productId, qty:Number(val.qty)}) :
                  arr.push({productId: val.productId, qty:Number(val.qty)})
              } else {
                flag = 4
              }
            }
          })
          if(flag === 1) {
            this.onRemind('产品库中库存数量为0将不能出库！')
            return;
          }
          if(flag === 2) {
            this.onRemind('出库量数量不能大于库存数！')
            return;
          }
          if(flag === 3) {
            this.onRemind('填写的数量不能小于0！')
            return;
          }
          if(flag === 4) {
            this.onRemind('请填写数量！')
            return;
          }
          if(arr.length <= 0) {
            this.onRemind('至少填写一条数据！')
            return;
          }
          this.$http.post(`/CommodityInOutbound/${this.switchType === 'INBOUND'? 'inBound': 'outBound'}/other?enName=${this.enName}`, arr)
            .then(response => {
              if(response.data.code === 1){
                this.onRemind('保存信息成功')
                this.initData()
              } else {
                this.onRemind(response.data)
              }
            })
            .catch(err => {
              this.onRemind('保存信息失败')
            })
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  $base-color: #3f84f6;
  $title-color: #ffa200;
  $red-color: #ff0000;
  .storage{
    position: relative;
    margin-bottom:.3rem;
    .btn-click{
      padding: 0.24rem 0.24rem;
      position: fixed;
      bottom: 1rem;
      left: 0;
      right: 0;
      z-index:100;
      text-align: center;
      background: #f1f3f6;
      span{
        display:inline-block;
        width:30%;
        height: .6rem;
        line-height: .6rem;
        margin: 0 .1rem;
        border-radius:.05rem;
        &.clear{
          color:#fafbfc;
          background: #b5b5b5;
        }
        &.base-color{
          color:#fff;
          background: $base-color;
        }
      }
    }
    .storage-info{
      padding: 0.24rem 0.24rem;
      background: #fff;
      margin-bottom:.2rem;
    }
    .content-line{
      position: absolute;
      border: 1px solid #7e7e7e;
      border-radius: .05rem;
      left: .3rem;
      top: 32%;
      background: #fff;
      width: 6.5rem;
      max-height: 2.5rem;
      overflow-y: auto;
      z-index: 12;
      .similar {
        li {
          height: .5rem;
          line-height: .5rem;
          font-size: .26rem;
          color: #999;
          padding-left: .19rem;
          &:focus, &:active, &:hover {
            background: #999;
            color: #fff;
          }
          span{
            display: inline-block;
            width: 50%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
    }
    .look-btn{
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      border-top: 1px solid #d3d3d3;
      text-align: center;
      span{
        display:inline-block;
        width:50%;
        text-align: center;
        line-height: .8rem;
      }
    }
    .linetext{
      color:#666;
      line-height: .6rem;
      overflow: hidden;
      -o-text-overflow: ellipsis;
      text-overflow: ellipsis;
      white-space: nowrap;
      input{
        height: .5rem;
        font-size: .24rem;
        border-radius: .04rem;
        border: 1px solid #d2d2d2;
        padding: 0 .1rem;
      }
      em{
        color:$red-color;
      }
      span{
        color:#333;
        &.base-color{
          color:$base-color;
        }
      }
    }
    > ul{
      margin-bottom:1rem;
    }
    .info-list{
      position:relative;
      padding: 0.3rem 0.24rem 1rem;
      background: #fff;
      margin-bottom:.2rem;
      .width50{
        display:inline-block;
        width: 48%;
        margin-left: .1rem;
      }
      >span{
        display:inline-block;
        position:absolute;
        left:0;
        top:0;
        padding: 0 .1rem;
        background: $title-color;
        border-radius: 0 .5rem .5rem 0;
        line-height: .3rem;
        height:.3rem;
        color:#fff;
        font-size: .24rem;
      }
    }
  }
</style>
