<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">

    <sales-return-dialog :propForm="propForm"
                         :visibility="isVisibility"
                         v-on:dialog-comfirm="comfirm"
                         v-on:dialog-cancle="cancle"></sales-return-dialog>

    <div class="cell clearfix">
        <label class="title"><span class="name">出库时间</span> : </label>
          <el-date-picker v-model="warehouse_out_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> : </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 :data="recordInfo.recordData" :class="signAndWeighBoxPatients" style="width: 100%" border
                    max-height="450" :header-cell-style="{ backgroundColor: 'rgb(245, 247, 250)'}"
          >

            <el-table-column min-width="35" align="center">

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

              <template slot-scope="scope" >
                <!--<span @click="showDialog(scope.$index, scope.row)" v-if="scope.row.good_type_id == 0" style="color:#c5c8cf">请输入类型</span>-->
                <!--<span @click="showDialog(scope.$index, scope.row)" v-if="scope.row.good_type_id != 0">{{typeName(scope.row.good_type_id)}}</span>-->

                <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 min-width="35" align="center">
              <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  min-width="23" align="center">
              <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  min-width="23" align="center">
              <template slot="header" slot-scope="scope">
                <span>出库数量<span style="color: red">*</span></span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'recordData.' + scope.$index + '.count'" :rules='tableRules.count' style="padding-top: 17px">
                  <el-input placeholder="请输入出库数量" type="number"  v-model="scope.row.count" ></el-input>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column label="总价" min-width="20" align="center">
              <template slot-scope="scope">
                {{calculate(scope.row.price*scope.row.count)}}
              </template>
            </el-table-column>
            <el-table-column label="备注" min-width="20" align="center">
              <template slot-scope="scope">
                <el-input  v-model="scope.row.remark"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" min-width="20">
              <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 { uParseTime } from '@/utils/tools'
  import {
    getSalesReturnConfig,
    postWarehouseOut
  } from '@/api/stock'
  import SalesReturnDialog from './Dialog/salesReturnDialog'
  import BreadCrumb from '../components/bread-crumb'

  export default {
    components: { BreadCrumb, SalesReturnDialog },
    name: 'salesReturnOrderAdd',

    data() {
      return {
        crumbs: [
          { path: false, name: '库存管理' },
          { path: '/stock/out', name: '出库单' },
          { path: '/stock/out/add', name: '新增出库单' }
        ],
        type: this.$route.query.type,
        signAndWeighBoxPatients: 'sign-and-weigh-box-patients',
        warehouse_out_time: '',
        currentIndex: 0,
        recordInfo: {
          recordData: []
        },
        tableRules: {
          price: [
            { required: true, message: '单价不能为空', trigger: 'blur' }
          ],
          count: [
            { required: true, message: '数量不能为空', trigge: 'blur' }
          ]
        },
        ruleForm: {
          manufacturer: [
            { required: true, message: '请选择厂商', trigger: 'change' }
          ]

        },
        // prop
        isVisibility: false,
        propForm: {
          goodType: [],
          goodInfo: [],
          goodUnit: []
        },
        form: {
          manufacturer: '',
          dealer: ''
        },

        manufacturer: [],
        dealer: [],
        goodType: []
      }
    },
    methods: {
      comfirm: function(val) {
        this.isVisibility = false
        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['count'] = ''
              tempForm['price'] = ''
              tempForm['remark'] = ''

              this.recordInfo.recordData.push(tempForm)
            }
          }
        }

        this.currentIndex = -1
      }, cancle: function() {
        this.isVisibility = false
      }, GetConfigInfo: function() {
        const params = {
          type: this.$route.query.type

        }
        getSalesReturnConfig(params).then(response => {
          if (response.data.state == 0) {
            this.$message.error(response.data.msg)
            return false
          } else {
            var warehouseList = response.data.data.warehouseList
            var warehouseInfoList = response.data.data.warehouseInfoList
            for (let i = 0; i < warehouseList.length; i++) {
              if (warehouseList[i].Manufacturer.id > 0) {
                this.manufacturer.push(warehouseList[i].Manufacturer)
              }
              if (warehouseList[i].Dealer.id > 0) {
                this.dealer.push(warehouseList[i].Dealer)
              }
            }
            for (let i = 0; i < warehouseInfoList.length; i++) {
              this.propForm.goodInfo.push(warehouseInfoList[i].GoodInfo)
            }
            const obj = {}
            const obj2 = {}
            const obj4 = {}
            // 去重复
            this.manufacturer = this.manufacturer.reduce((cur, next) => {
              obj[next.id] ? '' : obj[next.id] = true && cur.push(next)
              return cur
            }, [])
            // 去重复
            this.dealer = this.dealer.reduce((cur, next) => {
              obj2[next.id] ? '' : obj2[next.id] = true && cur.push(next)
              return cur
            }, [])
            this.propForm.goodInfo = this.propForm.goodInfo.reduce((cur, next) => {
              obj4[next.id] ? '' : obj4[next.id] = true && cur.push(next)
              return cur
            }, [])
          }
        })
      }, typeName: function(good_type_id) {
        let name = ''
        for (let i = 0; i < this.propForm.goodType.length; i++) {
          if (this.propForm.goodType[i].id == good_type_id) {
            name = this.propForm.goodType[i].type_name
          }
        }
        return name
      }, specificationName: function(good_info_id) {
        let name = ''
        for (let i = 0; i < this.propForm.goodInfo.length; i++) {
          if (this.propForm.goodInfo[i].id == good_info_id) {
            name = this.propForm.goodInfo[i].specification_name
          }
        }
        return name
      }, handleEdit: function(index, row) {
        const tempObj = {}
        tempObj['good_type_id'] = 0
        tempObj['good_id'] = 0
        tempObj['count'] = ''
        tempObj['price'] = ''
        tempObj['remark'] = ''

        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 (isNaN(val)) {
          return ''
        }
        if (val == 0) {
          return ''
        }
        return Math.round(parseFloat(val) * 100) / 100
      }, 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
          console.log(this.form.manufacturer)
          for (let i = 0; i < this.propForm.goodInfo.length; i++) {
            if (this.propForm.goodInfo[i].manufacturer == this.form.manufacturer) {
              this.propForm.goodType.push(this.propForm.goodInfo[i].GoodsType)
            }
          }
          const obj3 = {}
          this.propForm.goodType = this.propForm.goodType.reduce((cur, next) => {
            obj3[next.id] ? '' : obj3[next.id] = true && cur.push(next)
            return cur
          }, [])
        }
      }, 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
            let total = 0
            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
              }
              total = total + array[i].price * array[i].return_count
            }
            const params = {
              'stockOut': this.recordInfo.recordData
            }
            console.log(this.form.dealer)

            postWarehouseOut(params, this.warehouse_out_time, this.form.dealer, this.form.manufacturer, this.type).then(response => {
              if (response.data.state == 0) {
                this.$message.error(response.data.msg)
                return false
              } else {
                this.$notify({
                  title: '成功',
                  message: '退货成功',
                  type: 'success',
                  duration: 2000
                })
                this.recordInfo.recordData = []
                this.$router.back(-1)
              }
            })
          } else {
            return false
          }
        })
      },changeManufacturer(){
        this.recordInfo.recordData = []
        const tempObj = {}
        tempObj['good_type_id'] = 0
        tempObj['good_id'] = 0
        tempObj['return_count'] = 0
        tempObj['price'] = ''
        tempObj['remark'] = ''
        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.warehouse_out_time = endTime
      const tempObj = {}
      tempObj['good_type_id'] = 0
      tempObj['good_id'] = 0
      tempObj['return_count'] = 0
      tempObj['price'] = ''
      tempObj['remark'] = ''

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

  }
</script>

<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>
