<template>
  <div class="main-contain">
    <div class="position">
      <bread-crumb v-if="this.$route.query.type == 1" :crumbs='crumbs'></bread-crumb>
      <bread-crumb v-if="this.$route.query.type == 2" :crumbs='crumbs2'></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 size="small" v-model="warehouse_out_time" prefix-icon="el-icon-date" :editable="false"
                        style="width: 200px;"
                        type="date" placeholder="选择日期时间" align="right" format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd"></el-date-picker>
      </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 width="200" align="center">
              <template slot="header" slot-scope="scope">
                <span>耗材名称</span>
              </template>

              <template slot-scope="scope">
                <el-form-item style="padding-top: 20px">
                  <el-autocomplete
                      class="checkSearch"
                      popper-class="my-autocomplete"
                      v-model="scope.row.good_name"
                      :fetch-suggestions="querySearchAsync"
                      :trigger-on-focus="true"
                      placeholder="请输入耗材名称"
                      @select="handleSelect"
                      @input="changeGoodName(scope.$index)"
                      style="width:150px;"
                      :disabled="stockShow"
                    >
                      <i class="el-icon-search el-input__icon" slot="suffix"></i>
                    <template slot-scope="{ item }">
                      <div class="name">{{item.good_name +"  " +item.specification_name + "  "+  item.manufacturer}}</div>
                    </template>
                  </el-autocomplete>
                </el-form-item>
              </template>
            </el-table-column>
           <el-table-column width="140" 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: 20px">
                <el-input
                 :disabled="stockShow"
                  placeholder="请输入商品类型"
                  v-model="scope.row.good_type_id"
                  :value="typeName(scope.row.good_type_id)"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          
             
          <el-table-column width="140" 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: 20px">
                <el-input v-model="scope.row.name"  :disabled="stockShow"></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column width="140" 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: 20px">
                <!-- <el-input placeholder="请输入批号" v-model="scope.row.number"  :disabled="stockShow"></el-input> -->
               <el-select v-model="scope.row.number" filterable placeholder="请选择" :disabled="stockTrue">
                  <el-option
                    v-for="(item,index) in numberList"
                    :key="index"
                    :label="item.number"
                    :value="item.number">
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
         
          <el-table-column width="150" 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 type="number" v-model="scope.row.price"  :disabled="stockShow"></el-input>
              </el-form-item>


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

          <el-table-column width="150" 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 type="number" v-model="scope.row.count"  :disabled="stockShow"   oninput="value=value.replace(/\D|^0/g,'')"></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="总价" width="150" align="center">
            <template slot-scope="scope">
              {{calculate(scope.row.price*scope.row.count)}}
            </template>
          </el-table-column>
          <el-table-column label="生产厂商"  width="150" align="center">
            <template slot-scope="scope">
               <el-select size="small" v-model="scope.row.manufacturer" filterable placeholder="请选择厂商"  :disabled="stockShow">
                <el-option
                  v-for="(option, index) in manufacturerList"
                  :key="index"
                  :label="option.manufacturer_name"
                  :value="option.id">
                </el-option>
               </el-select>
            </template>   
          </el-table-column>
         <el-table-column label="生产日期"  width="150" align="center">
           <template slot-scope="scope">
              <el-date-picker
               :disabled="stockShow"
                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="有效期"  width="150" align="center">
            <template slot-scope="scope">
              <el-date-picker
               :disabled="stockShow"
                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  width="150" align="center">
            <template slot="header" slot-scope="scope">
            <span>批准文号<span style="color: red"></span></span>
          </template>
          <template slot-scope="scope">
              <el-input placeholder="请输入批准文号" v-model="scope.row.license_number" ></el-input>
          </template>
        </el-table-column>

          <el-table-column label="经销商"  width="150" align="center">
            <template slot-scope="scope">
               <el-select size="small" v-model="scope.row.dealer" filterable placeholder="请选择厂商"  :disabled="stockShow">
                <el-option
                  v-for="(option, index) in dealerList"
                  :key="index"
                  :label="option.dealer_name"
                  :value="option.id">
                </el-option>
               </el-select>
            </template>   
          </el-table-column>

          <el-table-column label="备注" width="150" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark"  :disabled="stockShow"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="150"  fixed="right">
            <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 { deleteWarehouseOutInfo, editWarehouseoutInfo, getSalesReturnConfig, getWarehouseOutInfo,GetAllConfig,GetAllGoodInfoByID,postSearchGoodList,getSingleOutOrderDetail,getStockBatchNumber } from '@/api/stock'
  import BreadCrumb from '../components/bread-crumb'
  import StockInDialog from './Dialog/stockInDialog'

  export default {
    components: { StockInDialog, BreadCrumb},
    name: 'stockOutOrderEdit',

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

        adminUserOptions: null,
        currentIndex: 0,
        warehouse_out_time: '',
        recordInfo: {
          recordData: [],
          stock_in_code: '',
          current_index: ''

        },
        tableRules: {
          count: [
            { required: true, message: '数量不能为空', trigge: 'blur' }
          ],
          price: [
            { required: true, message: '单价不能为空', trigger: 'blur' }
          ]

        },
        ruleForm: {
          manufacturer: [
            { required: true, message: '请选择厂商', trigger: 'change' }
          ]
        },
        // prop
        isVisibility: false,
        propForm: {
          goods:[],
          goodType: [],
          goodInfo: [],
          goodUnit: [],
          title: '入库',
          manufacturer: 0,
          dealer: 0
        },

        form: {
          manufacturer: 0,
          dealer: 0
        },
        warehouseInfoList: [],
        warehouseOut: {},
        manufacturer: [],
        dealer: [],
        goodType: [],
        goodInfo:[],
        numberList:[],
        stockShow:false,
        stockTrue:true,
      }
    },
    methods: {
      comfirm: function(val) {
        this.$refs.dialog.hide();
        this.propForm.goodType = [];
        this.propForm.goods = [];

        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.selectedGoodInfo[i].good_type_id;
              this.recordInfo.recordData[this.currentIndex].good_id =
                val.selectedGoodInfo[i].id;
              this.recordInfo.recordData[
                this.currentIndex
                ].price = val.selectedGoodInfo[i].buy_price.toString();
            } else {
              const tempForm = {};
              tempForm["id"] = 0;
              tempForm["good_type_id"] = val.selectedGoodInfo[i].good_type_id;
              tempForm["good_id"] = val.selectedGoodInfo[i].id;
              tempForm["count"] = "";
              tempForm["price"] = val.selectedGoodInfo[i].buy_price.toString();
              tempForm["remark"] = "";
              this.recordInfo.recordData.splice(
                this.currentIndex + 1,
                0,
                tempForm
              );
            }
          }
        }
        this.currentIndex = -1;
      },
      cancle: function() {
        this.$refs.dialog.hide()
        this.propForm.goods = [];

        this.propForm.goodType = [];
      }, 
      GetConfigInfo: function() {
        const loading = this.$loading({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
        GetAllConfig().then(response => {
          if (response.data.state == 0) {
            this.$message.error(response.data.msg);
            return false;
          } else {
            this.manufacturerList = response.data.data.manufacturer;
            this.dealer = response.data.data.dealer;
            this.goodType = response.data.data.goodType;
            this.goodInfo = response.data.data.goodInfo;
          }
          loading.close();
        });
      }, 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) {
        this.stockTrue = false
        if(this.stockShow == true){
         this.$message.error("自动出库数据无法编辑")
         return
        }
        const tempObj = {}
        tempObj['id'] = 0
        tempObj['good_type_id'] = 0
        tempObj['good_id'] = 0
        tempObj['count'] = ''
        tempObj['price'] = ''
        tempObj['remark'] = ''
        tempObj['number'] = ""
        tempObj['license_number'] = ""
        tempObj['dealer'] = ""
        tempObj['manufacturer'] = ""
        this.recordInfo.recordData.push(tempObj)
      }, 
      handleDelete: function(index, row) {
        if(this.stockShow == true){
         this.$message.error("自动出库数据无法删除")
         return
        }
        if (row.id == 0) {
          this.recordInfo.recordData.splice(index, 1)
        } else {
          const params = {
            id: row.id
          }
          this.$confirm('确认删除该出库耗材信息记录?', '删除出库耗材信息记录', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            deleteWarehouseOutInfo(params).then(response => {
              if (response.data.state == 0) {
                this.$message.error(response.data.msg)
                return false
              } else {
                this.$message.success('删除成功')

                this.recordInfo.recordData.splice(index, 1)
              }
            })
          }).catch(() => {
          })
        }
      }, getTime(val, temp) {
        if (val != 0) {
          return uParseTime(val, temp)
        } else {
          return ''
        }
      },
      showDialog(index, row) {
        this.currentIndex = index;
        const loading = this.$loading({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });

        const params = {
          manufacturer_id: this.form.manufacturer,
          dealer_id: this.form.dealer
        };
        this.propForm.goods = []

        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("该厂商或经销商没有物品信息");
              return;
            }
            this.$refs.dialog.show();
            for (let i = 0; i < response.data.data.goodInfo.length; i++) {
              this.propForm.goodType.push(
                response.data.data.goodInfo[i].type
              );
            }
            const obj = {};
            this.propForm.goodType = this.propForm.goodType.reduce(
              (cur, next) => {
                obj[next.id] ? "" : (obj[next.id] = true && cur.push(next));
                return cur;
              },
              []
            ); // 设置cur默认类型为数组，并且初始值为空的数组
          }

          for (let i = 0; i < this.propForm.goodType.length; i++) {
            let goodInfo = [];
            let goodObj = {};

            for (let a = 0; a < response.data.data.goodInfo.length; a++) {
              var respObj = response.data.data.goodInfo[a];
              respObj["isSelected"] = false;
              if (respObj.type.id == this.propForm.goodType[i].id) {
                goodInfo.push(respObj);
              }
            }
            const obj = {};
            goodInfo = goodInfo.reduce((cur, next) => {
              obj[next.id] ? "" : (obj[next.id] = true && cur.push(next));
              return cur;
            }, []); // 设置cur默认类型为数组，并且初始值为空的数组

            this.$set(goodObj, this.propForm.goodType[i].id, goodInfo);
            this.propForm.goods.push(goodObj);
          }
          loading.close();
        });
      },

      back() {
        this.$router.go(-1)
      },
       submit() {
        this.$refs['tableForm'].validate((valid) => {
          if (valid) {
            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
              }
            }
            for(let i=0;i<this.recordInfo.recordData.length;i++){
               if(this.recordInfo.recordData[i].dealer == ""){
                this.recordInfo.recordData[i].dealer = 0
             }
              if(this.recordInfo.recordData[i].expiry_date == "" || this.recordInfo.recordData[i].expiry_date == undefined){
                this.recordInfo.recordData[i].expiry_date = ""
              } 
              if(this.recordInfo.recordData[i].product_date == "" || this.recordInfo.recordData[i].product_date == undefined){
                this.recordInfo.recordData[i].product_date = ""
              }
               this.recordInfo.recordData[i].price = this.recordInfo.recordData[i].price.toString()
            
              for(let j=0;j<this.manufacturerList.length;j++){
                if(this.recordInfo.recordData[i].manufacturer == this.manufacturerList[j].manufacturer_name){
                  this.recordInfo.recordData[i].manufacturer = this.manufacturerList[j].id
                }
              }
              for(let z=0;z<this.dealerList.length;z++){
                if(this.recordInfo.recordData[i].dealer == this.dealerList[z].dealer_name){
                    this.recordInfo.recordData[i].dealer = this.dealerList[z].id
                }
              }
            }
            const params = {
              'stockOut': this.recordInfo.recordData
            }
           
            console.log("stockout",params,this.$route.query.id)
            
            editWarehouseoutInfo(params, this.warehouse_out_time, this.$route.query.id, this.$route.query.type, this.form.manufacturer, this.form.dealer).then(response => {
              if (response.data.state == 0) {
                this.$message.error(response.data.msg)
                return false
              } else {
                if(response.data.data.msg == 1){
                  this.$message.success('保存成功')
                  this.$router.back(-1)
                }

                if(response.data.data.msg == 5){
                  this.$message.error("该耗材无库存,请入库")
                }

                if(response.data.data.msg == 6){
                  this.$message.error("该耗材的退库数量大于入库数量,无法出库,请新增出库另一个批次")
                }
                
              }
            })
          } else {
            return false
          }
        })
      }, 
     calculate: function(val) {
        if (val == 0) {
          return ''
        }
        return Math.round(parseFloat(val) * 100) / 100
      }, changeManufacturer(val) {
        this.propForm.manufacturer = val
      }, changeDealer(val) {
        this.propForm.dealer = val
      },
       querySearchAsync(keyword, cb) {
      let key = '';
      if (keyword != undefined) {
        key = keyword
      }
      console.log("keyrowrd",key)
      postSearchGoodList(key).then(response => {
        if (response.data.state == 1) {
          
            var list = response.data.data.list
            this.goodList = list
            var manufacturerList = response.data.data.manufacturerList
            this.manufacturerList = manufacturerList
            for(let i=0;i<this.goodList.length;i++){
              for(let j=0;j<this.manufacturerList.length;j++){
                if(this.goodList[i].manufacturer == this.manufacturerList[j].id){
                    this.goodList[i].manufacturer = this.manufacturerList[j].manufacturer_name
                }
              }
             for(let z=0;z<this.dealerList.length;z++){
                if(this.goodList[i].dealer == this.dealerList[z].id){
                   this.goodList[i].dealer = this.dealerList[z].dealer_name
                }
              }
            }
          
            cb(this.goodList)
        } else {
          cb([])
        }
      })
    },
    changeGoodName(val){
      this.currentIndex = val
    },
    handleSelect(val){
       console.log("val22222",val)
        this.getStockBatchNumber(val.id)
        for(let i=0;i<this.recordInfo.recordData.length;i++){
          if(this.currentIndex == i){
            this.recordInfo.recordData[i].good_type_id = val.id
            this.recordInfo.recordData[i].good_name = val.good_name
            this.recordInfo.recordData[i].good_type_id = val.good_type_id
            this.recordInfo.recordData[i].name = val.specification_name  +"/"+val.packing_unit
            this.recordInfo.recordData[i].manufacturer = val.manufacturer
            this.recordInfo.recordData[i].remark = val.remark
            this.recordInfo.recordData[i].license_number = ""
            if(val.packing_price == 0){
               this.recordInfo.recordData[i].price = ""
            }else{
               this.recordInfo.recordData[i].price = val.packing_price
            }
           
            this.recordInfo.recordData[i].specification_name = val.specification_name
            this.recordInfo.recordData[i].good_id = val.id
             if(val.dealer == 0){
               this.recordInfo.recordData[i].dealer = ""
             }else{
               this.recordInfo.recordData[i].dealer = val.dealer
             }
           
         }
      }
    },
     getSingleOutOrderDetail(order_id){

        const loading = this.$loading({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
       const params = {
          'id': order_id
        }
      getSingleOutOrderDetail(params).then(response=>{
        if(response.data.state == 1){
          console.log("详情",response.data.data.list)
          var dealerList = response.data.data.dealerList
          this.dealerList = dealerList
          var manufacturerList = response.data.data.manufacturerList
          // console.log("hhhhhhhhh",manufacturerList)
          this.manufacturerList = manufacturerList
          this.goodType = response.data.data.goodType
          for (let i = 0; i < response.data.data.list.length; i++) {
           
            response.data.data.list[i].price = response.data.data.list[i].price.toString()
            response.data.data.list[i].count = response.data.data.list[i].count.toString()
            response.data.data.list[i].good_name = response.data.data.list[i].good_name
            response.data.data.list[i].name = response.data.data.list[i].specification_name + "/" + response.data.data.list[i].packing_unit
            response.data.data.list[i].good_type_id = response.data.data.list[i].good_type_id
            response.data.data.list[i].expiry_date = this.getTime(response.data.data.list[i].expiry_date,"{y}-{m}-{d}")
            response.data.data.list[i].product_date = this.getTime(response.data.data.list[i].product_date,"{y}-{m}-{d}")
            response.data.data.list[i].remark = response.data.data.list[i].remark
            if(response.data.data.list[i].dealer == 0){
               response.data.data.list[i].dealer = ""
            }
            if(response.data.data.list[i].manufacturer ==0 ){
               response.data.data.list[i].manufacturer = ""
            }
            this.recordInfo.recordData.push(response.data.data.list[i])
          }
          loading.close();
        }
      })
    },
      getStockBatchNumber(id){
        var params = {
          id:id
        }
        getStockBatchNumber(params).then(response=>{
          if(response.data.state == 1){
            var list = response.data.data.list
            console.log("list2243444",list)
            this.numberList = list
          }
      })
      }
    },
    created() {
      var nowDate = new Date();
      var nowYear = nowDate.getFullYear();
      var nowMonth = nowDate.getMonth() + 1;
      var nowDay = nowDate.getDate();
      this.warehouse_out_time =
        nowYear +
        "-" +
        (nowMonth < 10 ? "0" + nowMonth : nowMonth) +
        "-" +
        (nowDay < 10 ? "0" + nowDay : nowDay);
      this.propForm.goodUnit = this.$store.getters.good_unit
      const order_id = this.$route.query.id  
      this.getSingleOutOrderDetail(order_id)
      var is_sys = this.$route.query.is_sys
      if(is_sys == 0){
        this.stockShow = false
      }
      if(is_sys == 1){
        this.stockShow = true
      }
      
    }

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