<template>

  <div class="main-contain">
    <div class="position">
      <bread-crumb :crumbs='crumbs'></bread-crumb>
      <div style="float:right;">
      <el-button size="small"  @click="back()" class="filter-item"   >取 消</el-button>
      <el-button size="small"  type="primary" @click="submit()" class="filter-item" >保 存</el-button>
      </div>
    </div>
    <div class="app-container">

      <stock-in-dialog ref="dialog" :propForm="propForm"
                       :visibility="isVisibility"
                       v-on:dialog-comfirm="comfirm"
                       v-on:dialog-cancle="cancle"></stock-in-dialog>


      <div class="cell clearfix">
        <label class="title"><span class="name">入库时间</span> : </label>
        <el-date-picker v-model="warehousing_time"  prefix-icon="el-icon-date"  :editable="false" style="width: 196px;" type="date" placeholder="选择日期时间" align="right"  format="yyyy-MM-dd" value-format="yyyy-MM-dd" > </el-date-picker>
      </div>

      <div class="cell clearfix">
        <label class="title"><span class="name">厂商<span style="color: red;margin-left: -15px">*</span></span> : </label>

        <el-select  v-model="form.manufacturer" clearable  placeholder="请选择厂商" @change="changeManufacturer()" >
          <el-option
            v-for="(option, index) in manufacturer"
            :key="index"
            :label="option.manufacturer_name"
            :value="option.id">
          </el-option>
        </el-select>
      </div>

      <div class="cell clearfix">
        <label class="title"><span class="name">经销商</span> : </label>
        <el-select  v-model="form.dealer" clearable  placeholder="请选择经销商" >
          <el-option
            v-for="(option, index) in dealer"
            :key="index"
            :label="option.dealer_name"
            :value="option.id">
          </el-option>
        </el-select>
      </div>


            <el-form :rules="tableRules" :model="recordInfo" ref="tableForm">
              <el-table   id="oictable" :data="recordInfo.recordData" :class="signAndWeighBoxPatients" border style="width: 100%"
                        max-height="450" :header-cell-style="{ backgroundColor: 'rgb(245, 247, 250)'}"
              >

                <el-table-column  align="center" width="200">

                  <template slot="header" slot-scope="scope">
                    <span>商品类型<span style="color: red">*</span></span>
                  </template>

                  <template slot-scope="scope">
                    <el-form-item style="padding-top: 15px">
                      <el-input placeholder="请输入商品类型" v-model="scope.row.good_type_id"
                                :value="typeName(scope.row.good_type_id)"
                                @focus="showDialog(scope.$index, scope.row)"></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column align="center" width="200">
                  <template slot="header" slot-scope="scope">
                    <span>规格名称<span style="color: red">*</span></span>
                  </template>
                  <template slot-scope="scope">

                    <el-form-item style="padding-top: 15px">
                      <el-input placeholder="请输入规格名称" v-model="scope.row.good_id"
                                :value="specificationName(scope.row.good_id)"
                                @focus="showDialog(scope.$index, scope.row)"></el-input>
                    </el-form-item>

                  </template>
                </el-table-column>


                <el-table-column  align="center" width="150">
                  <template slot="header" slot-scope="scope">
                    <span>单价<span style="color: red">*</span></span>
                  </template>
                  <template slot-scope="scope">
                    <!--<el-input type="number" v-model="scope.row.price"  @blur="handleBlur(scope.$index, scope.row)"></el-input>-->
                    <el-form-item :prop="'recordData.' + scope.$index + '.price'" :rules='tableRules.price'
                                  style="padding-top: 17px">
                      <el-input placeholder="请输入单价"  type="number" v-model="scope.row.price"></el-input>
                    </el-form-item>


                  </template>
                </el-table-column>

                <el-table-column  align="center"  width="180">
                  <template slot="header" slot-scope="scope">
                    <span>入库数量<span style="color: red">*</span></span>
                  </template>
                  <template slot-scope="scope">
                    <!--{{scope.row.warehousing_count}}-->
                    <!--<el-input type="number" v-model="scope.row.warehousing_count"   @blur="handleBlur(scope.$index, scope.row)"></el-input>-->

                    <el-form-item :prop="'recordData.' + scope.$index + '.warehousing_count'"
                                  :rules='tableRules.warehousing_count' style="padding-top: 17px">
                      <el-input placeholder="请输入入库数量"  type="number" v-model="scope.row.warehousing_count"></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column label="总价" align="center" width="150">
                  <template slot-scope="scope">
                    {{calculate(scope.row.price*scope.row.warehousing_count)}}
                  </template>
                </el-table-column>

                <el-table-column align="center"  width="150">
                  <template slot="header" slot-scope="scope">
                    <span>批号<span style="color: red">*</span></span>
                  </template>
                  <template slot-scope="scope">
                    <!--<el-input  v-model="scope.row.numbers"></el-input>-->

                    <el-form-item :prop="'recordData.' + scope.$index + '.number'" :rules='tableRules.number'
                                  style="padding-top: 17px">
                      <el-input placeholder="请输入批号" v-model="scope.row.number"></el-input>
                    </el-form-item>

                  </template>
                </el-table-column>
                <el-table-column label="生产日期"  align="center" width="250">
                  <template slot-scope="scope">
                    <!--{{scope.row.product_date | parseTime("{y}-{m}-{d}")}}-->
                    <el-date-picker prefix-icon="el-icon-date" style="width: 145px" v-model="scope.row.product_date"
                                    type="date" placeholder="选择日期时间" format="yyyy-MM-dd"
                                    value-format="yyyy-MM-dd"></el-date-picker>

                  </template>
                </el-table-column>
                <el-table-column label="有效日期"  align="center" width="250">
                  <template slot-scope="scope">
                    <!--{{ scope.row.expiry_date | parseTime("{y}-{m}-{d}")}}-->
                    <el-date-picker prefix-icon="el-icon-date" style="width: 145px" v-model="scope.row.expiry_date"
                                    type="date" placeholder="选择日期时间" format="yyyy-MM-dd"
                                    value-format="yyyy-MM-dd"></el-date-picker>

                  </template>
                </el-table-column>
                <el-table-column label="备注"  align="center" width="150">
                  <template slot-scope="scope">
                    <el-input placeholder="请输入备注"   v-model="scope.row.remark"></el-input>
                  </template>
                </el-table-column>

                <el-table-column label="操作" align="center" fixed="right"  width="150">
                  <template slot-scope="scope" >
                    <el-tooltip class="item" effect="dark" content="新增" placement="top">

                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-circle-plus-outline"
                      @click="handleEdit(scope.$index, scope.row)">
                    </el-button>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="删除" placement="top">

                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="handleDelete(scope.$index, scope.row)">
                    </el-button>
                    </el-tooltip>

                  </template>
                </el-table-column>

              </el-table>
            </el-form>


    </div>
  </div>

</template>

<script>
  import stockInDialog from './Dialog/stockInDialog'
  import { uParseTime } from '@/utils/tools'

  import {
    deleteWarehouseInfo,
    GetAllConfig,
    GetAllGoodInfo,
    GetAllGoodInfoByID,
    GetAllGoodType,
    getWarehouseInfoByOrdeNumber,
    modifyWarehouseInfo,
    postWarehouse
  } from '@/api/stock'
  import BreadCrumb from '../components/bread-crumb'

  export default {
    components: { BreadCrumb, stockInDialog },
    name: 'stockIn',

    data() {
      var checkGoodId = (rule, value, callback) => {
        setTimeout(() => {
          if (value == '' || value == 0) {
            return callback(new Error('规格名称不能为空'))
          }
        }, 2000)
      }

      return {
        crumbs: [
          { path: false, name: '库存管理' },
          { path: false, name: '入库单' },
          { path: false, name: '新增入库单' }
        ],
        signAndWeighBoxPatients: 'sign-and-weigh-box-patients',
        warehousing_time: '',
        adminUserOptions: null,
        currentIndex: 0,

        recordInfo: {
          recordData: [],
          stock_in_code: '',
          current_index: ''

        },
        tableRules: {
          price: [
            { required: true, message: '单价不能为空', trigger: 'blur' }
          ],
          warehousing_count: [
            { required: true, message: '数量不能为空', trigge: 'blur' }
          ],
          number: [
            { required: true, message: '批号不能为空', trigge: 'blur' }
          ],
          good_id: [
            { validator: checkGoodId, trigger: 'blur' }
          ]

        },
        ruleForm: {
          manufacturer: [
            { required: true, message: '请选择厂商', trigger: 'change' }
          ]

        },
        type: this.$route.query.type,
        total: '',
        product_date: '',
        expiry_date: '',
        numbers: '',

        // prop
        isVisibility: false,
        propForm: {
          goodType: [],
          goodInfo: [],
          goodUnit: [],
          title: '入库',
          formValue: {
            good_type_id: '',
            good_id: '',
            number: '',
            product_date: '',
            expiry_date: '',
            warehousing_count: '',
            price: '',
            remark: '',
            dealer: '',
            manufacturer: ''

          },
          isCreated: 1

        },

        goodInfo: {
          loading: false,
          goodTypeData: [],
          type_code: ''
        },
        form: {
          manufacturer: '',
          dealer: ''
        },

        formValue: {
          good_type_id: '',
          good_id: '',
          number: '',
          product_date: '',
          expiry_date: '',
          warehousing_count: '',
          price: '',
          remark: '',
          dealer: '',
          manufacturer: ''

        },

        manufacturer: [],
        dealer: [],
        goodType: []
      }
    },
    methods: {
      handleSave: function() {
        if (this.recordInfo.recordData.length <= 0) {
          this.$message.error('请添加入库信息')
          return
        }
        sessionStorage.removeItem('warehousing_orders')
        this.$router.back(-1)
      }, handleCancle: function() {
        this.$confirm('是否放弃编辑返回上一页?', '放弃编辑', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          sessionStorage.removeItem('warehousing_orders')
          this.$router.back(-1)
        }).catch(() => {

        })
      }, handleCreate: function() {
        this.propForm.formValue = {}
        this.propForm.isCreated = 1
        this.isVisibility = true
      }, comfirm: function(val) {
        this.$refs.dialog.hide()
        if (val.selectedGoodInfo.length > 0) {
          for (let i = val.selectedGoodInfo.length - 1; ; i--) {
            if (i == 0) {
              this.recordInfo.recordData[this.currentIndex].good_type_id = val.goodTypeId
              this.recordInfo.recordData[this.currentIndex].good_id = val.selectedGoodInfo[i].id
            } else {
              const tempForm = {}
              tempForm['good_type_id'] = val.goodTypeId
              tempForm['good_id'] = val.selectedGoodInfo[i].id
              tempForm['number'] = ''
              tempForm['product_date'] = ''
              tempForm['expiry_date'] = ''
              tempForm['warehousing_count'] = ''
              tempForm['price'] = ''
              tempForm['remark'] = ''
              tempForm['dealer'] = ''
              tempForm['manufacturer'] = ''
              // this.recordInfo.recordData.add(tempForm,this.currentIndex + i)
              // this.recordInfo.recordData.push(tempForm)
              this.recordInfo.recordData.splice(this.currentIndex+1, 0, tempForm);
            }
          }
        }

        this.currentIndex = -1
      }, cancle: function() {
        this.$refs.dialog.hide()

      }, GetAllGoodType: function() {
        GetAllGoodType().then(response => {
          if (response.data.state == 0) {
            this.$message.error(response.data.msg)
            return false
          } else {
            for (let i = 0; i < response.data.data.goodType.length; i++) {
              this.propForm.goodType.push(response.data.data.goodType[i])
            }
          }
        })
      }, GetAllGoodInfo: function() {
        GetAllGoodInfo().then(response => {
          if (response.data.state == 0) {
            this.$message.error(response.data.msg)
            return false
          } else {
            for (let i = 0; i < response.data.data.goodInfo.length; i++) {
              this.propForm.goodInfo.push(response.data.data.goodInfo[i])
            }
          }
        })
      }, GetConfigInfo: function() {
        GetAllConfig().then(response => {
          if (response.data.state == 0) {
            this.$message.error(response.data.msg)
            return false
          } else {
            this.manufacturer = response.data.data.manufacturer
            this.dealer = response.data.data.dealer
            this.goodType = response.data.data.goodType
            this.goodInfo = response.data.data.goodInfo
          }
        })
      }, typeName: function(good_type_id) {
        let name = ''
        for (let i = 0; i < this.goodType.length; i++) {
          if (this.goodType[i].id == good_type_id) {
            name = this.goodType[i].type_name
          }
        }
        return name
      }, specificationName: function(good_info_id) {
        let name = ''
        for (let i = 0; i < this.goodInfo.length; i++) {
          if (this.goodInfo[i].id == good_info_id) {
            name = this.goodInfo[i].specification_name
          }
        }
        return name
      }, handleEdit: function(index, row) {
        const tempObj = {}
        tempObj['good_type_id'] = 0
        tempObj['good_id'] = 0
        tempObj['number'] = ''
        tempObj['product_date'] = ''
        tempObj['expiry_date'] = ''
        tempObj['warehousing_count'] = ''
        tempObj['price'] = ''
        tempObj['remark'] = ''
        tempObj['dealer'] = ''
        tempObj['manufacturer'] = ''
        this.recordInfo.recordData.push(tempObj)
      }, handleDelete: function(index, row) {
        if( this.recordInfo.recordData.length <= 1){
          this.$message.error('只有一条记录的时候无法删除')
          return
        }else{
          this.recordInfo.recordData.splice(index, 1)
        }
      }, calculate: function(val) {
        if (val == 0) {
          return ''
        }
        return Math.round(parseFloat(val) * 100) / 100
      }, GetWarehouseInfoByOrdeNumber: function() {
        const params = {
          'warehousing_order': sessionStorage.getItem('warehousing_orders')
        }
        this.recordInfo.recordData = []
        getWarehouseInfoByOrdeNumber(params).then(response => {
          if (response.data.state != 0) {
            for (let i = 0; i < response.data.data.info.length; i++) {
              this.recordInfo.recordData.push(response.data.data.info[i])
            }
          }
        })
      }, getTime(val, temp) {
        if (val != 0) {
          return uParseTime(val, temp)
        } else {
          return ''
        }
      }, showDialog(index, row) {
        this.currentIndex = index
        if (this.form.manufacturer == '' || this.form.manufacturer == 0) {
          this.$message.error('请先选择厂商')
          return
        } else {

          // this.isVisibility = true
          const params = {
            id: this.form.manufacturer
          }
          this.propForm.goodType = []
          GetAllGoodInfoByID(params).then(response => {
            if (response.data.state == 0) {
              this.$message.error(response.data.msg)
              return false
            } else {
              if (response.data.data.goodInfo.length == 0) {
                this.$message.error('该厂商没商品，请添加商品')
              } else {
                for (let i = 0; i < response.data.data.goodInfo.length; i++) {
                  this.propForm.goodType.push(response.data.data.goodInfo[i].GoodsType)
                }

                const obj = {}
                this.propForm.goodType = this.propForm.goodType.reduce((cur, next) => {
                  obj[next.id] ? '' : obj[next.id] = true && cur.push(next)
                  return cur
                }, []) // 设置cur默认类型为数组，并且初始值为空的数组
                this.$refs.dialog.show()

              }
            }
          })
        }
      }, getSummaries(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总价'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += ' 元'
          } else {
            sums[index] = 'N/A'
          }
        })

        return sums
      }, back() {
        this.$router.go(-1)
      }, submit() {
        this.$refs['tableForm'].validate((valid) => {
          if (valid) {
            if (this.form.manufacturer == 0) {
              this.$message.error('厂商不能为空')
              return
            }
            const array = this.recordInfo.recordData
            for (let i = 0; i < array.length; i++) {
              if (array[i].good_type_id == 0) {
                this.$message.error('商品类型不能为空')
                return
              }
              if (array[i].good_id == 0) {
                this.$message.error('规格名称不能为空')
                return
              }
            }

            const params = {
              'stockIn': this.recordInfo.recordData
            }
            postWarehouse(params, this.warehousing_time, this.form.manufacturer, this.form.dealer, this.type).then(response => {
              if (response.data.state == 0) {
                this.$message.error(response.data.msg)
                return false
              } else {

                this.$message.success('入库成功')

                this.$router.back(-1)
              }
            })
          } else {
            return false
          }
        })
      },changeManufacturer(){
        this.recordInfo.recordData = []
        const tempObj = {}
        tempObj['good_type_id'] = 0
        tempObj['good_id'] = 0
        tempObj['number'] = ''
        tempObj['product_date'] = ''
        tempObj['expiry_date'] = ''
        tempObj['warehousing_count'] = ''
        tempObj['price'] = ''
        tempObj['remark'] = ''
        tempObj['dealer'] = ''
        tempObj['manufacturer'] = ''
        this.recordInfo.recordData.push(tempObj)

      }
    },
    created() {
      var year = new Date().getFullYear()
      var month = new Date().getMonth() + 1
      var day = new Date().getDate()
      if (parseInt(month) < 10) {
        month = '0' + month
      }
      if (parseInt(day) < 10) {
        day = '0' + day
      }
      const endTime = year + '-' + month + '-' + day
      this.warehousing_time = endTime

      const tempObj = {}
      tempObj['good_type_id'] = 0
      tempObj['good_id'] = 0
      tempObj['number'] = ''
      tempObj['product_date'] = ''
      tempObj['expiry_date'] = ''
      tempObj['warehousing_count'] = ''
      tempObj['price'] = ''
      tempObj['remark'] = ''
      tempObj['dealer'] = ''
      tempObj['manufacturer'] = ''

      this.recordInfo.recordData.push(tempObj)
      this.GetConfigInfo()
      this.propForm.goodUnit = this.$store.getters.good_unit
    }

  }
</script>

<style>
  #oictable ::-webkit-scrollbar {
    height: 15px;
  }
</style>

<style rel="stylesheet/css" lang="scss" scoped>
  .information {
    border: 1px #dcdfe6 solid;
    padding: 30px 20px 30px 20px;

  .border {
    border-bottom: 1px #dcdfe6 solid;
    margin: 0px 0 20px 0;
  }

  }

  .edit_separater {
    border-top: 1px solid rgb(233, 233, 233);
    margin-top: 15px;
    margin-bottom: 15px;
  }

</style>

<style>
  .sign-and-weigh-box .sign-and-weigh-box-patients .cell {
    font-size: 12px;
  }

  .sign-and-weigh-box .sign-and-weigh-box-patients .current-row > td {
    background: #6fb5fa;
  }

</style>
s
