<template>
  <div>
    <div v-show="showSearch">
      <label class="title"><span class="name">仓库</span> :</label>
        <el-select size="small" v-model="storehouse_id" filterable placeholder="请选择仓库" style="width:200px" @change="changeHouseList">
            <el-option
              v-for="(option, index) in houseList"
              :key="index"
              :label="option.storehouse_name"
              :value="option.id">
            </el-option>
       </el-select>  
     <el-autocomplete
        class="checkSearch"
        popper-class="my-autocomplete"
        v-model="form.drug_name"
        :fetch-suggestions="querySearchAsync"
        :trigger-on-focus="true"
        placeholder="请输入耗材名称"
        @select="handleSelect"
        style="width:300px;"
      >
        <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>  
  </div>
   <div v-show="showTable">
    <div>日期：{{nowTime}}   盘点人：{{user_name}}</div>
    <div style="float:right;margin-bottom:10px"><el-button type="primary" @click="saveInentoryList">保存</el-button></div>
    <el-collapse v-model="activeNames">
      <el-collapse-item :name="index" v-for="(item,index) in tableData" :key="index">
        <template slot="title">
          <div style="font-size:16px">{{item.good_name}}</div> &nbsp;&nbsp;{{item.specification_name}} <el-button type="warning" icon="el-icon-remove" style="margin-left:20px;" @click="toMove(item,index)">移除</el-button>
        </template>
        <el-table :data="item.child" border :header-cell-style="{ backgroundColor: 'rgb(245, 247, 250)' }" style="width:100%">
              <el-table-column prop="date" label="耗材名称" width="150" align="center">
                <template slot-scope="scope">
                  {{scope.row.good_name}}
                </template>
              </el-table-column>
              <el-table-column  prop="name" label="规格" width="100"  align="center">
                <template slot-scope="scope">
                  {{scope.row.specification_name}}
                </template>
              </el-table-column>
             <el-table-column  prop="name" label="入库单号" width="100"  align="center">
                <template slot-scope="scope">
                  {{scope.row.warehousing_order}}
                </template>
              </el-table-column>
              <el-table-column  prop="name" label="有效期" width="100"  align="center">
                <template slot-scope="scope">
                  {{getTime(scope.row.expiry_date)}}
                </template>
              </el-table-column>
              <el-table-column prop="name" label="批号" width="100"  align="center">
                  <template slot-scope="scope">
                    {{scope.row.number}}
                </template>
              </el-table-column>
              <el-table-column prop="name" label="进货价" width="100"  align="center">
                  <template slot-scope="scope">
                    {{scope.row.price}}
                  </template> 
              </el-table-column>
            
              <el-table-column prop="name" label="生产厂商" width="100"  align="center">
                  <template slot-scope="scope">
                    {{scope.row.manufacturer_name}}
                  </template> 
              </el-table-column>

             <el-table-column prop="name" label="仓库名称" width="100"  align="center">
                  <template slot-scope="scope">
                    {{getStorehouseName(scope.row.storehouse_id)}}
                  </template> 
              </el-table-column>
              <el-table-column prop="name" label="盘点前数量" width="120"  align="center">
                <template slot-scope="scope">
                    <span><el-input style="width:80px" v-model="scope.row.stock_count" :disabled="true"></el-input>{{scope.row.max_unit}}</span> 
                  </template> 
              </el-table-column>

             <el-table-column prop="name" label="盘点后数量" width="120"  align="center">
                <template slot-scope="scope">
                  <el-input style="width:80px" v-model="scope.row.last_stock_count"></el-input>
                 </template> 
              </el-table-column>

              <el-table-column prop="name" label="盘点原因" width="180"  align="center">
                <template slot-scope="scope">
                   <el-select v-model="scope.row.type" placeholder="请选择">
                      <el-option
                        v-for="item in reasonList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                 </template> 
              </el-table-column>
             
             <el-table-column prop="name"  width="200"  align="center">
                <template slot-scope="scope">
                    <span><el-button type="danger" @click="toDelete(scope.$index,scope.row.drug_id)">不盘点此批次</el-button></span>
                  </template> 
              </el-table-column>
          </el-table>
      </el-collapse-item>
        <label class="title"><span class="name">仓库</span>:</label>
          <el-select size="small" v-model="storehouse_id" filterable placeholder="请选择仓库" style="width:200px" @change="changeHouseList">
                <el-option
                  v-for="(option, index) in houseList"
                  :key="index"
                  :label="option.storehouse_name"
                  :value="option.id">
                </el-option>
          </el-select>
      <el-autocomplete
          class="checkSearch"
          popper-class="my-autocomplete"
          v-model="form.drug_name"
          :fetch-suggestions="querySearchAsync"
          :trigger-on-focus="true"
          placeholder="请输入耗材名称"
          @select="handleSelect"
          style="width:300px;"
          v-show="showTableOne"
        >
          <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-collapse>
   </div>
  </div>
</template>
<script> 
const moment = require("moment");
import { uParseTime } from '@/utils/tools'
import { postSearchGoodWarehouseList,getInventoryList,SaveCheckedInventory,getInventoryDetail,deleteInventory,getWarehouseTotal,getGoodInventoryWarehouseList,saveStockInentoryList } from "@/api/stock"
export default {
    name: "inventory",
    data() {
        return{
            user_name:this.$store.getters.xt_user.user.user_name,
            nowTime: moment(new Date()).format("YYYY-MM-DD HH:MM:SS"),
            searchKey:'',
            value1:'',
            value2:'',
            tableData: [],
            dialogVisible:false,
            total: 0,
            inventoryList:[
              {id:0,name:"全部"},
              {id:1,name:"盘点完成"},
              {id:2,name:"正在盘点"},
            ],
            start_time:"",
            end_time:"",
           form: {
                id:"",
                good_name: '',
                packing_price:'',
                new_price:"",
                count:"",
                remark:"",
                warehousing_order:"",
                manufacturer:"",
                dealer:"",
                license_number:"",
                warehousing_unit:"",
                specification_name:"",
                buy_price:"",
                good_id:"",
                packing_unit:"",
                good_origin_place:"",
                report_count:"",
                total:"",
                expiry_date:"",
                product_date:"",
                number:"",
                proof_count:"",
                storehouse_id:"",
            },
         manufacturerList:[],
         dealerList:[],
         goodList:[],
         currentIndex: 0,
         inventory_status:0,
         limit:10,
         page:1,
         doctorList:[],
         total:0,
         tableList:[],
         ids:"",
         checker:this.$store.getters.xt_user.user.id,
         check_time:new Date(),
         checkDialogVisible:false,
         editPriceDialogVisible:false,
         modefiyePriceDialogVisible:false,
         proofPriceDialogVisible:false,
         id:0,
         numberList:[],
         reasonList:[
          {id:6,name:"默认"},
          {id:1,name:"到期退货"},
          {id:2,name:"异常退货"},
          {id:3,name:"退货"},
          {id:4,name:"损坏"},
          {id:5,name:"不计入报损分析"},
          {id:7,name:"有效期到期"},
         ],
         activeNames: [0,1,2,3,4,5,6,7,8,9,10],
         showTable:false,
         showSearch:true,
         inventory_total:0,
         WarehouseList:[],
         showTableOne:false,
         houseList:[],
         storehouse_id:"",
        }
    },
    methods:{
         querySearchAsync(keyword, cb) {
            let key = '';
            if (keyword != undefined) {
                key = keyword
            }
            var params = {
              keyword:key,
              storehouse_id:this.storehouse_id,
            }
            postSearchGoodWarehouseList(params).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
                var dealer =  response.data.data.dealerList
                this.dealerList = dealer
                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 i=0;i<this.goodList.length;i++){
                    for(let j=0;j<this.dealerList.length;j++){
                        if(this.goodList[i].dealer == this.dealerList[j].id){
                        this.goodList[i].dealer = this.dealerList[j].dealer_name
                        }
                    }
                }
            
                cb(this.goodList)
            } else {
                cb([])
             }
          })
         },
        changeGoodName(val){
          this.currentIndex = val
        },
        handleSelect(val){
          this.getGoodInventoryWarehouseList(val.good_id)
        },
        search(){
          this.getlist()
        },
        print(){
          if(this.ids == ""){
            this.$message.error("请勾选打印数据")
            return
          }else{
           this.$router.push({path:'/stock/inventoryPrint?ids='+this.ids})   
          } 
        },
       getTime(val) {
         if(val < 0){
            return ""
          }
         if(val == ""){
            return ""
          }else {
            return uParseTime(val, '{y}-{m}-{d}')
         }
        },
        handleSizeChange(val){
          this.limit = val
          this.getlist()
        },
        handleCurrentChange(val){
          this.page = val
          this.getlist()
        },
      changeHouseList(){
        this.querySearchAsync()
      },
      getlist(){
        var params = {
              keyword:this.searchKey,
              start_time:this.start_time,
              end_time:this.end_time,
              inventory_status:this.inventory_status, 
              page:this.page,
              limit:this.limit,
            }
          getInventoryList(params).then(response=>{
              if(response.data.state ==1 ){
              var list =  response.data.data.list
              this.tableList = list
              var total = response.data.data.total
              this.total = total
              this.doctorList =  response.data.data.doctorlist
              this.houseList = response.data.data.houseList
              console.log("仓库行吗32323232232332",this.houseList)
              var houseConfig = response.data.data.houseConfig
              this.storehouse_id = houseConfig.storehouse_out_info
              }
          })
        },
      getChecker(id){
        var name = ""
        for(let i=0;i<this.doctorList.length;i++){
            if(id == this.doctorList[i].admin_user_id){
              name = this.doctorList[i].user_name
            }
        }
        return name
      },
      toCheck(){
        if(this.ids.length <=0){
          this.$message.error("请勾选核对数据")
          return
        }else{
          this.checkDialogVisible = true
        }
      },
      changePrice(val){  
        var arr = []
        
        for(let i=0;i<val.length;i++){
          arr.push(val[i].id)
        }
        var str = arr.join(",")
      
     
        this.ids = str
      
      },
      SaveCheckedInventory(){
          var params = {
              ids:this.ids,
              check_time:this.getTime(this.check_time),
              checker:this.checker,

          }
        SaveCheckedInventory(params).then(response=>{
          if(response.data.state == 1){
            this.$message.success("保存成功")
            var inventory = response.data.data.inventory
            this.checkDialogVisible = false
            this.getlist()
          }
        })
      },
      toDelete(index){
       this.tableData.splice(index,1)
     },
     getInventory(id){
       getInventoryDetail(id).then(response=>{
          if(response.data.state == 1){
            var detail =  response.data.data.detail
         
            this.form.good_name = detail.good_name
            this.form.specification_name = detail.specification_name
            this.form.count = detail.count
            this.form.remark = detail.remark
            this.form.total = detail.total
            this.form.warehousing_info_id = detail.warehousing_info_id
            this.form.good_id  = detail.good_id
            this.id = detail.id
            this.proofPriceDialogVisible = true

          }
       })
     },
     deleteInventory(id,check_status,index){
        if(check_status == 1){
          this.$message.error("已核对的不能编辑")
          return
        }
        this.$confirm('是否删除所选内容?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          
       deleteInventory(id).then(response => {
            if (response.data.state == 1) {
              var msg = response.data.data.msg
              this.$message.success("保存成功")
              this.tableList.splice(index,1)
            } 
          })
        }).catch(() => {
          this.loading = false
        });
     },
      exportList(){
       
         import('@/vendor/Export2Excel').then(excel => {
         const tHeader = ['盘点编码', '盘点日期', '盘点数量','盘点人','审核日期','核对人','状态']
         const filterVal = ['warehousing_order', 'start_time', 'count','user_name','check_time','checker','checker_status']
       
          for(let i=0;i<this.tableList.length;i++){
           this.tableList[i].start_time = this.getTime(this.tableList[i].start_time)
           this.tableList[i].check_time =  this.getTime(this.tableList[i].check_time)
           this.tableList[i].checker = this.getChecker(this.tableList[i].checker)
           if(this.tableList[i].checker_status == 1){
             this.tableList[i].checker_status = "已核对"
           }
          if(this.tableList[i].checker_status == 2){
             this.tableList[i].checker_status = "未核对"
           }
         }
         const data = this.formatJson(filterVal, this.tableList)
      
         excel.export_json_to_excel({
           header: tHeader,
           data,
           filename: '耗材盘点'
         })
          this.downloadLoading = false
        })
       },
       formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]));
      },
    
    getGoodInventoryWarehouseList(id){
       var params = {
         id:id,
         storehouse_id:this.storehouse_id,
       }
      getGoodInventoryWarehouseList(params).then(response=>{
         if(response.data.state == 1){
           var list = response.data.data.list
           for(let i=0;i<list.length;i++){
              list[i].type = 6
              list[i].good_name = list[i].GoodInfo.good_name
              list[i].specification_name = list[i].GoodInfo.specification_name
              list[i].manufacturer_name = ""
              for(let j=0;j<this.manufacturerList.length;j++){
                if(list[i].manufacturer == this.manufacturerList[j].id){
                  list[i].manufacturer_name = this.manufacturerList[j].manufacturer_name
                }
              }
               this.WarehouseList.push(list[i])
           }
            let objInfo = {}
            this.WarehouseList.forEach((item,index)=>{
              let { good_id } = item
              if(!objInfo[good_id]){
                objInfo[good_id] = {
                  good_id,
                  child:[],
                  good_name:item.good_name,
                  specification_name:item.specification_name,
                  warehouseing_unit:item.max_unit,
                  price:item.price,
                  number:item.number,
                  expiry_date:item.expiry_date,
                  type:0,
                  last_stock_count:0,
                }
              }
            })
            let newList = Object.values(objInfo);
          
            for(let i=0;i<this.WarehouseList.length;i++){
              for(let j=0;j<newList.length;j++){
                if(this.WarehouseList[i].good_id == newList[j].good_id){
                    newList[j].child.push(this.WarehouseList[i])
                }
              }
            }
        
          
          this.tableData = newList
          this.showSearch = false
          this.showTable = true
          if(this.tableData.length >=1){
            this.showTableOne = true
          }
           this.inventory_total  = this.tableData.length
         }
      })
    },
     changeInventory(){
       this.getlist()
     },
     changeStartTime(val){
       this.start_time = this.getTime(val)
       this.getlist()
     },
     changeEndTime(val){
       this.end_time = this.getTime(val)
       this.getlist()
     },
    changeNumber(val){
     this.getWarehouseTotal(val)
     this.form.warehousing_info_id = val
     },
    getWarehouseTotal(id){
        var params = {
          id:id,
        }
      getWarehouseTotal(params).then(response=>{
         if(response.data.state == 1){
           var list =  response.data.data.list
           this.form.total = list.stock_count
         }
      })
    },
    toMove(item,index){
       this.$confirm('此操作将移除耗材整个批次, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.tableData.splice(index,1)
          this.WarehouseList = []
          this.activeNames = [0,1,2,3,4,5,6,7,8,9,10]
        }).catch(() => {
          this.loading = false
        });   
    },
    toDelete(index,drug_id){
      for(let i=0;i<this.tableData.length;i++){
         if(drug_id == this.tableData[i].drug_id){
           this.tableData[i].child.splice(index,1)
           if(this.tableData[i].child.length == 0){
              this.tableData.splice(index,1)

           }
         }
      }
     this.WarehouseList = []
     this.activeNames = [0,1,2,3,4,5,6,7,8,9,10]
    },
    saveInentoryList(){
       var arr = []
       for(let i=0;i<this.tableData.length;i++){
         for(let j=0;j<this.tableData[i].child.length;j++){
            arr.push(this.tableData[i].child[j])
         }
       }

      for(let i=0;i<arr.length;i++){

        if(arr[i].last_stock_count == undefined){
        
           arr[i].last_stock_count = 0
        }else{
          arr[i].last_stock_count = parseInt(arr[i].last_stock_count)
        }
        arr[i].storehouse_id = this.storehouse_id
      }
       var params = {
         tableData:arr,
         storehouse_id:this.storehouse_id,
       }
      console.log("param23323232323232323",params)
      saveStockInentoryList(params).then(response=>{
        if(response.data.state == 1){
           var inventory = response.data.data.inventory
           this.$message.success("保存成功")
           this.WarehouseList = []
           this.tableData = []
        }
      })
    },
    getStorehouseName(id){
      var storehouse_name = ""
      for(let i=0;i<this.houseList.length;i++){
        if(id == this.houseList[i].id){
          storehouse_name = this.houseList[i].storehouse_name
        }
      }
      return storehouse_name
    }
   },
    created(){
      this.getlist()
    },
    mounted() {
    },
};
</script>