<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" v-loading="loading">

      <div class="cell clearfix">
      
        <label class="title"><span class="name">入库时间</span> : </label>
        <el-date-picker size="small" 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>
       <label class="title"><span class="name">调入仓库</span> : </label>
        <el-select size="small" v-model="storehouse_in_id" filterable placeholder="请选择仓库">
          <el-option
            v-for="(option, index) in houseList"
            :key="index"
            :label="option.storehouse_name"
            :value="option.id">
          </el-option>
        </el-select>

        <label class="title"><span class="name">调出仓库</span> : </label>
        <el-select size="small" v-model="storehouse_out_id" filterable placeholder="请选择仓库">
          <el-option
            v-for="(option, index) in houseList"
            :key="index"
            :label="option.storehouse_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" fixed="left">
             <template slot="header" slot-scope="scope">
              <span>商品名称</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                :prop="'tableList.' + scope.$index + '.name'"
                :rules="tableRules.name"
              >
                <el-select
                  v-model="scope.row.name"
                  style="width: 160"
                  filterable
                  placeholder="请选择商品"
                  @change="changeName"
                  @input="changeGoodName(scope.$index)"
                  :disabled="disabled"
                >
                  <el-option
                    v-for="(item, index) in tabList"
                    :key="index"
                    :label="item.project_name"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </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: 20px;">
                <el-input v-model="scope.row.project_type" :disabled="true" style="width:180px"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column align="center" width="300">
            
            <template slot="header" slot-scope="scope">
              <span>规格<span style="color: red">*</span></span>
            </template>
            <template slot-scope="scope">

              <el-form-item style="padding-top: 20px">
                 <el-input v-model="scope.row.second_specification_name" style="width:200px" :disabled="true"></el-input>
              </el-form-item>

            </template>
          </el-table-column>
        
          <el-table-column align="center" width="250">
            <template slot="header" slot-scope="scope">
              <span>调拨数量<span style="color: red">*</span></span>
            </template>
            <template slot-scope="scope">
              <el-form-item style="padding-top: 20px" :prop="'recordData.' + scope.$index + '.number'"
                            :rules='tableRules.number' >
                <el-input v-model="scope.row.count" style="width:100px"></el-input>
                <el-select
                  v-model="scope.row.sencond_unit"
                  style="width: 100px"
                  filterable
                  placeholder="请选择"
                  :disabled="disabled"
                >
                  <el-option
                    v-for="(item, index) in scope.row.unitList"
                    :key="index"
                    :label="item.name"
                    :value="item.name"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>


    
          <el-table-column align="center" width="220">
            <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 + '.packing_price'" :rules='tableRules.packing_price'
                            style="padding-top: 20px">
                <el-input v-model="scope.row.second_total" style="width:200px"></el-input>
              </el-form-item>


            </template>
          </el-table-column>
      
          <el-table-column label="备注" align="center" width="300">
            <template slot-scope="scope">
               <el-input v-model="scope.row.remake" style="width:200px"></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 { uParseTime } from '@/utils/tools'
  import {getSencondeGoodList,updateSencondOrder,getSencondOrderDetail} from '@/api/seconde'
  import BreadCrumb from '../components/bread-crumb'

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

    data() {
     
      return {
        crumbs: [
          { path: false, name: '库存管理' },
          { path: false, name: '耗材入库单' },
          { path: false, name: '新增入库单' }
        ],
        crumbs2: [
          { path: false, name: '库存管理' },
          { path: false, name: '其他入库单' },
          { path: false, name: '新增入库单' }
        ],
        signAndWeighBoxPatients: 'sign-and-weigh-box-patients',
        warehousing_time: '',
        adminUserOptions: null,
        currentIndex: 0,
        tableRules: {
          price: [
            { required: true, message: '单价不能为空', trigger: 'blur' }
          ],
        },
        goodType: [],
        manufacturerList:[],
        goodList:[],
        loading:false,
        list:[],
        configlist:{},
        recordInfo: {
          recordData: [],
        },
        drugList:[],
        goodTypeList:[],
        drugTypeList:[],
        houseList:[],
        tabList:[],
        disabled:false,
        storehouse_out_id:"",
        storehouse_in_id:"",
      }
    },
    methods: {
      handleEdit: function(index, row) {
        const tempObj = {}
        tempObj["id"] = 0
        tempObj["name"] = "";
        tempObj['project_name'] = ""
        tempObj['project_type'] = ""
        tempObj['second_specification_name'] = ''
        tempObj['sencond_unit'] = ''
        tempObj['count'] = ''
        tempObj['second_total'] = ''
        tempObj["is_source"] = 0
        tempObj["remake"] = ''
        tempObj["project_id"] = 0
        tempObj["min_price"] = 0
        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
      }, 
    getTime(val, temp) {
        if (val != 0) {
          return uParseTime(val, temp)
        } else {
          return ''
        }
      },
      submit() {
       
        this.$refs['tableForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            const array = this.recordInfo.recordData
            if(this.storehouse_in_id <=0){
              this.$message.error("调入仓库不能为空!")
              return
            }
            if(this.storehouse_out_id <=0){
              this.$message.error("调出仓库不能为空!")
              return
            }
            for (let i = 0; i < array.length; i++) {
              array[i].count = parseInt(array[i].count)
              array[i].second_total = array[i].second_total.toString()
            }

            const loading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            const params = {
              'stockIn': this.recordInfo.recordData
            }
            var storehouse_in_id = parseInt(this.storehouse_in_id)
            var storehouse_out_id = parseInt(this.storehouse_out_id)
            var id = parseInt(this.$route.query.id)
            updateSencondOrder(params, this.warehousing_time,storehouse_in_id,storehouse_out_id,id).then(response => {
              if (response.data.state == 1) {
                var warehousingInfo = response.data.data.warehousingInfo   
                this.$message.success('保存成功')
                this.loading = false 
                loading.close()
              } else {
                this.$message.error("保存失败")
                loading.close()
              }
            })
          } else {
            return false
          }
        })
      },
      changeGoodName(val){
        this.currentIndex = val
      },
      //获取基本数据信息
      getlist(){
       getSencondeGoodList().then(response=>{
         if(response.data.state == 1){
            var drugList = response.data.data.drugList
            this.drugList= drugList
            var goodList = response.data.data.goodList
            this.goodList = goodList
            var manufactuerList = response.data.data.manufactuerList
            var goodTypeList = response.data.data.goodTypeList
            this.goodTypeList = goodTypeList
            var drugTypeList = response.data.data.drugTypeList
            this.drugTypeList = drugTypeList
            var houseList =  response.data.data.houseList
            this.houseList = houseList

            for(let i=0;i<drugList.length;i++){
              for (let z = 0; z < drugList[i].drug_warehouse_info.length; z++) {
                if (drugList[i].max_unit ==drugList[i].drug_warehouse_info[z].max_unit) {
                    drugList[i].drug_warehouse_info[z].stock_max_number = drugList[i].drug_warehouse_info[z].stock_max_number *drugList[i].min_number;
                }
               }
               for (let y = 0; y < this.drugTypeList.length; y++) {
                  if (drugList[i].drug_type == this.drugTypeList[y].value) {
                     drugList[i].drug_type = this.drugTypeList[y].name;
                   }
                }
                drugList[i].name =drugList[i].drug_name + " " +drugList[i].dose + drugList[i].dose_unit + "*" +drugList[i].min_number +drugList[i].min_unit + "/" + drugList[i].max_unit + " " +drugList[i].manufacturer;
                drugList[i].project_name =drugList[i].drug_name + " " +drugList[i].dose + drugList[i].dose_unit + "*" +drugList[i].min_number +drugList[i].min_unit + "/" + drugList[i].max_unit + " " +drugList[i].manufacturer;
                drugList[i].project_type = drugList[i].drug_type;
                drugList[i].second_specification_name = drugList[i].dose + drugList[i].dose_unit +"*" + drugList[i].min_number +drugList[i].min_unit +"/" + drugList[i].max_unit;
                drugList[i].second_total = this.getWarehoseInfo(drugList[i].drug_warehouse_info,drugList[i].max_unit,drugList[i].min_unit,drugList[i].min_number);
                drugList[i].is_source = 1
                drugList[i].count = ""
                drugList[i].remake = ""
                drugList[i].min_price = drugList[i].min_price
             if (drugList[i].max_unit != drugList[i].min_unit) {
                drugList[i].unitList = [
                    { id: 1, name: "" },
                    { id: 2, name: "" },
                ];
             }
            if (drugList[i].max_unit == drugList[i].min_unit) {
               drugList[i].unitList = [{ id: 1, name: "" }];
            }

            drugList[i].sencond_unit = drugList[i].max_unit;
            for (let j = 0; j < drugList[i].unitList.length; j++) {
              if (drugList[i].max_unit != drugList[i].min_unit) {
                drugList[i].unitList[0].name = drugList[i].max_unit;
                drugList[i].unitList[1].name = drugList[i].min_unit;
              }
              if (drugList[i].max_unit == drugList[i].min_unit) {
                drugList[i].unitList[0].name = drugList[i].max_unit;
              }
            }
            this.tabList.push(drugList[i]);
            }

           for (let i = 0; i < goodList.length; i++) {
            for (let y = 0; y < this.goodTypeList.length; y++) {
              if (goodList[i].good_type_id == this.goodTypeList[y].id) {
                goodList[i].good_type_id = this.goodTypeList[y].type_name;
              }
            }
            goodList[i].project_name = goodList[i].good_name + " " + goodList[i].specification_name + " " + goodList[i].manufacturer;
            goodList[i].project_type = goodList[i].good_type_id;
            goodList[i].second_specification_name = goodList[i].specification_name;
            goodList[i].second_total = this.getTotalStockCount(
              goodList[i].good_warehouse_info
            );
            goodList[i].count = ""
            goodList[i].is_source = 2;
            goodList[i].name = goodList[i].good_name;
            goodList[i].unitList = [{ id: 1, name: "" }];
            goodList[i].sencond_unit = goodList[i].packing_unit;
            goodList[i].remake = ""
            goodList[i].min_price = goodList[i].retail_price
            for (let j = 0; j < goodList[i].unitList.length; j++) {
              goodList[i].unitList[0].name = goodList[i].packing_unit;
            }
            this.tabList.push(goodList[i]);
          }
            
         }
       })
      },
      
      getWarehoseInfo(arr, max_unit, min_unit, min_number) {
        var total = 0;
        var max_str = "";
        var min_str = "";
        if (arr.length > 0) {
            for (let i = 0; i < arr.length; i++) {
            total += parseInt(arr[i].stock_max_number + arr[i].stock_min_number);
            }
        }
        if (total < min_number) {
            min_str = total + min_unit;
        }
        if (total == 0) {
            min_str = "";
            max_str = "";
        }
        if (total >= min_number) {
            if (parseInt(total / min_number) != 0) {
            max_str = parseInt(total / min_number) + max_unit;
            }
            if (total % min_number != 0) {
            min_str = (total % min_number) + min_unit;
            }
        }
        return max_str + min_str;
      },
      getTotalStockCount(arr) {
        var total_count = 0;
        for (let i = 0; i < arr.length; i++) {
            total_count += arr[i].stock_count;
        }
        return total_count;
      },
     changeGoodName(val) {
      this.currentIndex = val;
    },
    changeName(val) {
      for (let i = 0; i < this.recordInfo.recordData.length; i++) {
        if (this.currentIndex == i) {
          this.recordInfo.recordData[i].project_id = val.id;
          this.recordInfo.recordData[i].is_source = val.is_source;
          this.recordInfo.recordData[i].name = val.name;
          this.recordInfo.recordData[i].project_name = val.project_name;
          this.recordInfo.recordData[i].project_type = val.project_type;
          this.recordInfo.recordData[i].second_specification_name = val.second_specification_name;
          this.recordInfo.recordData[i].second_total = val.second_total;
          this.recordInfo.recordData[i].sencond_unit = val.sencond_unit
          this.recordInfo.recordData[i].min_price = val.min_price
          if (val.count == NaN) {
            this.recordInfo.recordData[i].count = "";
          } else {
            this.recordInfo.recordData[i].count = val.count? val.count : "";
          }
          this.recordInfo.recordData[i].unitList = val.unitList;
        }
      }
    },
    getSencondOrderDetail(){
       var id = parseInt(this.$route.query.id)
      getSencondOrderDetail(id).then(response=>{
         if(response.data.state == 1){
           var warehouse = response.data.data.warehouse
           this.storehouse_in_id = warehouse.storehouse_in_id
           this.storehouse_out_id = warehouse.storehouse_out_id
           var list = response.data.data.list
           for(let i=0;i<list.length;i++){
              list[i].id = list[i].id
              list[i].name = list[i].project_name
           }
           this.recordInfo.recordData = list
           console.log("list23233223323232322323",list)
         }
      })   
    }
    },
    created() {
      var nowDate = new Date()
      var nowYear = nowDate.getFullYear()
      var nowMonth = nowDate.getMonth() + 1
      var nowDay = nowDate.getDate()
      this.warehousing_time =
        nowYear +
        '-' +
        (nowMonth < 10 ? '0' + nowMonth : nowMonth) +
        '-' +
        (nowDay < 10 ? '0' + nowDay : nowDay)
      const tempObj = {}
      tempObj["name"] = "";
      tempObj['project_name'] = ""
      tempObj['project_type'] = ""
      tempObj['second_specification_name'] = ''
      tempObj['sencond_unit'] = ''
      tempObj['count'] = ''
      tempObj['second_total'] = ''
      tempObj["remake"] = ''
      tempObj["is_source"] = 0
      tempObj["project_id"] = 0
      tempObj["min_price"] = 0
      tempObj["id"] = 0
      this.recordInfo.recordData.push(tempObj)
      this.getlist()
      this.getSencondOrderDetail()
    }

  }
</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;
  }
  .el-autocomplete-suggestion{
    width: 400px !important;
  }
  

</style>
