<template>
  <div class="main-contain">
    <div class="position">
      <bread-crumb :crumbs="crumbs"></bread-crumb>
      <div>
        <el-button
          size="small"
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="setting"
        >设置
        </el-button
        >
      <el-button
          size="small"
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="printOrder"
        >打印
      </el-button>
      <el-button
          size="small"
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="exportStock"
        >导出
        </el-button>
      </div>
    </div>
    <div class="app-container ">
      <div class="cell clearfix">
         <el-select v-model="drug_type" style="width:160px;margin-right:10px;" placeholder="请选择" @change="changeDrug">
            <el-option
              v-for="(item,index) in drugTypeList"
              :key="index"
              :label="item.name"
              :value="item.id">
            </el-option>
        </el-select>
         <el-date-picker
            v-model="start_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"
            @change="startTimeChange"
           ></el-date-picker>-
            <el-date-picker
              v-model="end_time"
              prefix-icon="el-icon-date"
              :editable="false"
              style="width: 196px;margin-right:10px;"
              type="date"
              placeholder="选择日期时间"
              align="right"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              @change="endTimeChange"
          ></el-date-picker>
          <el-input
            style="width: 200px;"
            class="filter-item"
            v-model.trim="keywords"
            placeholder="药品名称"
          />
          <el-button
            size="small"
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="search"
          >搜索
          </el-button>
      </div>
      
       <el-table :data="tableList" border style="width: 100%">
        <!-- <el-table-column prop="date" label="药品编号" width="180">
           <template  slot-scope="scope">
              
           </template>
        </el-table-column> -->
        <el-table-column prop="drug_type" label="药品类型" width="180" align="center">
           <template slot-scope="scope">
             {{getDrugType(scope.row.drug_type)}}
           </template>
        </el-table-column>
        <el-table-column prop="drug_name" label="药品名称" align="center">
           <template slot-scope="scope">
             {{scope.row.drug_name}}
           </template>
        </el-table-column>
        <el-table-column prop="drug_name" label="规格&&单位" align="center">
           <template slot-scope="scope">
             {{scope.row.dose + scope.row.dose_unit +"*"+scope.row.min_number+scope.row.min_unit+"/"+scope.row.max_unit}}
           </template>
        </el-table-column>
         <el-table-column prop="drug_name" label="进货单价" align="center">
           <template slot-scope="scope">
             {{scope.row.last_price}}
           </template>
        </el-table-column>
         <el-table-column prop="drug_name" label="厂家" align="center">
           <template slot-scope="scope">
             {{getManufacturerList(scope.row.manufacturer)}}
           </template>
        </el-table-column>
        <el-table-column prop="drug_name" label="入库数量" align="center">
           <template slot-scope="scope">
             {{getInCount(scope.row.drug_id)}}
              <!-- {{getInCount(scope.row.drug_id)}}{{scope.row.max_unit}} -->
           </template>
        </el-table-column>
        <el-table-column prop="drug_name" label="出库数量" align="center">
           <template slot-scope="scope">
             {{getOutCount(scope.row.drug_id) + getAutoCount(scope.row.drug_id)}}
             <!-- {{getCount(scope.row.drug_id,scope.row.min_number,scope.row.max_unit,scope.row.min_unit)}} -->
           </template>
        </el-table-column>
        <el-table-column prop="drug_name" label="剩余库存量" align="center">
           <template slot-scope="scope">
            {{getInCount(scope.row.drug_id) - getOutCount(scope.row.drug_id) - getAutoCount(scope.row.drug_id)}}
            <!-- {{getCountTwo(scope.row.drug_id,scope.row.min_number,scope.row.max_unit,scope.row.min_unit)}} -->
           </template>
        </el-table-column>
        <el-table-column prop="drug_name" label="操作" align="center" width="200px">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleDetail(scope.row)"
            >库存流水
            </el-button>
            <el-button
              size="small"
              type="primary"
              @click="handleBatch(scope.row)"
            >批次
            </el-button>
          </template>
        </el-table-column>
       </el-table>
       
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 50, 100,500,1000]"
        :page-size="10"
        background
        align="right"
        style="margin-top:20px;"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <setting-dialog
      ref="dialog"
    ></setting-dialog>

  </div>
</template>

<script>
  import { uParseTime } from '@/utils/tools'
  import BreadCrumb from '@/xt_pages/components/bread-crumb'
  import { getAllDrugStockQueryList,getDrugStockList,getDrugCountList } from '@/api/drug/drug_stock'
  import SettingDialog from './settingDialog/index'
  import { getDictionaryDataConfig } from "@/utils/data";
import { min } from 'moment'
  export default {
    name: 'stockIn',
    created() {
      var drugCategory = getDictionaryDataConfig('system','drug_category')
      this.drugCategory.push(...drugCategory)
      var drugTypeList = getDictionaryDataConfig('system','drug_type') 
      this.drugTypeList.push(...drugTypeList)
      this.getlist()
      this.getDrugCountList()
    },
    components: {
      SettingDialog,
      BreadCrumb
    },
    data() {
      return {
        crumbs: [
          { path: false, name: '库存管理' },
          { path: '/stock/drugs/stock/query', name: '药品库存查询' }
        ],
        keywords: '',
        total: 0,
        multipleSelection: [],
        signAndWeighBoxPatients: 'sign-and-weigh-box-patients',
        start_time: '',
        end_time: '',
        page: 1,
        limit: 10,
        goodType: [],
        goodInfo: [],
        tempArr: [],
        sameRowArr: [],
        WarehouseInfo: {
          loading: false,
          warehouseInfoDate: []
        },
        tableData:[],
        drug_category:0,
        drugCategory:[
          {id:0,name:"全部"}
        ],
        drugTypeList:[
          {id:0,name:"全部"}
        ],
        tableList:[],
        manufacturerList:[],
        countList:[],
        outCountList:[],
        autoCountList:[],
        keyword:"",
        drug_type:0,
        minCount:[],
        drugOutList:[]
      }
    },
    methods: {
      handleSpanTempArr() {
        this.tempArr = []

        for (let i = 0; i < this.WarehouseInfo.warehouseInfoDate.length; i++) {
          if (i === 0) {
            this.tempArr.push(1)
            this.pos = 0
          } else {
            // 判断当前元素与上一个元素是否相同
            if (this.WarehouseInfo.warehouseInfoDate[i].drug_name === this.WarehouseInfo.warehouseInfoDate[i - 1].drug_name) {
              this.tempArr[this.pos] += 1
              this.tempArr.push(0)
            } else {
              this.tempArr.push(1)
              this.pos = i
            }
          }
        }

        let sameRowArr = [], sIdx = 0
        this.WarehouseInfo.warehouseInfoDate.forEach((item, index) => {
          item.index = index
          if (index === 0) {
            sameRowArr.push([index])
          } else {
            if (item.drug_name === this.WarehouseInfo.warehouseInfoDate[index - 1].drug_name) {
              sameRowArr[sIdx].push(index)
            } else {
              sIdx = sIdx + 1
              sameRowArr.push([index])
            }
          }
        })
        this.sameRowArr = sameRowArr

      },
      merge({ row, column, rowIndex, columnIndex }) {
        if (columnIndex === 0) {
          const _row = this.tempArr[rowIndex]
          const _col = _row > 0 ? 1 : 0
          return {
            rowspan: _row,
            colspan: _col
          }
        }
      },
      GetAllDrugStockQueryList: function() {
       
        const Params = {
          page: this.page,
          limit: this.limit,
          keyword: this.keywords,
          drug_category:this.drug_category,
          start_time:this.start_time,
          end_time:this.end_time,
        }
        this.WarehouseInfo.loading = true
        this.WarehouseInfo.warehouseInfoDate = []
        getAllDrugStockQueryList(Params).then(response => {
          if (response.data.state == 0) {
            this.WarehouseInfo.loading = false
            this.$message.error(response.data.msg)
            return false
          } else {
            this.WarehouseInfo.loading = false
            this.total = response.data.data.total
            var arr = []
            for (let i = 0; i < response.data.data.list.length; i++) {
              this.WarehouseInfo.warehouseInfoDate.push(response.data.data.list[i])
              arr.push(response.data.data.list[i])
            }
           
            for(let i=0;i<arr.length;i++){
               arr[i].stockInCount =  this.stockInCount(arr[i])
               arr[i].salesReturnCount = this.salesReturnCount(arr[i])
               arr[i].reactCount = (this.stockInCount(arr[i]) - this.salesReturnCount(arr[i]))?this.stockInCount(arr[i]) - this.salesReturnCount(arr[i]):0
               arr[i].stockOutCount = this.stockOutCount(arr[i])
               arr[i].cancelStockCount = this.cancelStockCount(arr[i])?this.cancelStockCount(arr[i]):0
               arr[i].reactOutCount = (this.stockOutCount(arr[i]) - this.cancelStockCount(arr[i]))?(this.stockOutCount(arr[i]) - this.cancelStockCount(arr[i])):0
               arr[i].overplusCount = (this.stockInCount(arr[i])-this.salesReturnCount(arr[i])-this.stockOutCount(arr[i])+this.cancelStockCount(arr[i]))?this.stockInCount(arr[i])-this.salesReturnCount(arr[i])-this.stockOutCount(arr[i])+this.cancelStockCount(arr[i]):0
            }
          
             this.tableData = arr
            this.handleSpanTempArr()
          }
        })
      },
      getSpecificationName: function(id) {
        let name = ''
        for (let i = 0; i < this.goodInfo.length; i++) {
          if (this.goodInfo[i].id == id) {
            name = this.goodInfo[i].specification_name
          }
        }
        return name
      },
      getTypeName: function(id) {
        let name = ''
        for (let i = 0; i < this.goodType.length; i++) {
          if (this.goodType[i].id == id) {
            name = this.goodType[i].type_name
          }
        }
        return name
      },

      handleBack: function() {
        this.$router.go(-1)
      },
      handleSizeChange(val) {
        this.limit = val
        // this.GetAllDrugStockQueryList()
        this.getlist()
      },
      handleCurrentChange(val) {
        this.page = val
        // this.GetAllDrugStockQueryList()
        this.getlist()
      },
      calculate: function(val) {
        return Math.round(parseFloat(val) * 100) / 100
      },
  
    startTimeChange: function(val) {
      var time = this.getTimestamp(val) - this.getTimestamp(this.end_time);
      
      if (time > 0) {
        this.$message.error("开始时间不能大于结束时间");
        this.start_time = "";
      } else {
        // this.GetAllDrugStockQueryList();
        this.getlist()
      }
    },
    endTimeChange: function(val) {
      var time = this.getTimestamp(val) - this.getTimestamp(this.start_time);
      if (time < 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.end_time = "";
      } else {
        // this.GetAllDrugStockQueryList();
        this.getlist()
      }
     
    },
      stockInCount: function(row) {
        let total = 0
        for (let i = 0; i < row.query_drug_warehousing_info.length; i++) {
          total = total + row.query_drug_warehousing_info[i].warehousing_count
        }
        return total
      },
      salesReturnCount: function(row) {
        let total = 0

        for (let i = 0; i < row.query_drug_sales_return_info.length; i++) {
          total = total + row.query_drug_sales_return_info[i].count
        }
        return total
      },
      stockOutCount: function(row) {
        let total = 0

        for (let i = 0; i < row.query_drug_warehouseout_info.length; i++) {
          total = total + row.query_drug_warehouseout_info[i].count
        }
        return total
      },
      cancelStockCount: function(row) {
        let total = 0
        for (let i = 0; i < row.query_drug_cancel_stock_info.length; i++) {
          total = total + row.query_drug_cancel_stock_info[i].count
        }
        return total
      },
      showStockInDetailDialog: function(val) {
      },
      showSaleReturnDetailDialog: function() {
      },
      showStockOutDetailDialog: function() {
      },
      showCancelStockDetailDialog: function() {
      },
      search: function() {
        this.getlist()
      }, 
      setting: function() {
        this.$refs.dialog.show()
      },
       exportStock(){
         import('@/vendor/Export2Excel').then(excel => {
         const tHeader = ['药品名称', '规格名称', '入库数量','单价','入库退货','实际入库','出库数量','出库退库','实际出库','剩余库存']
         const filterVal = ['drug_name', 'drug_spec', 'stockInCount','last_price','salesReturnCount','reactCount','stockOutCount','cancelStockCount','reactOutCount','overplusCount']
       
        
         const data = this.formatJson(filterVal, this.tableData)
        //  console.log("data",data)
        
         excel.export_json_to_excel({
           header: tHeader,
           data,
           filename: '药品查询'
         })
          this.downloadLoading = false
        })
       },
       formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]));
      },
      getDictionaryDataConfig(module, filed_name) {
        return getDictionaryDataConfig(module, filed_name)
      },
      getTimestamp(time) { // 把时间日期转成时间戳
        return (new Date(time)).getTime() / 1000
      },
      changeDrug(){
        this.getlist()
      },
      printOrder(){
        this.$router.push({
          name: "drugQueryPrint",
          query: {drug_category:this.drug_category,keyword:this.keywords,start_time:this.start_time,end_time:this.end_time,page:this.page,limit:this.limit}
        });
      },
 
  //获取库存
      getlist(){
        const params = {
          page: this.page,
          limit: this.limit,
          keyword: this.keywords,
          drug_type:this.drug_type,
          start_time:this.start_time,
          end_time:this.end_time,
        }
        console.log("parasm222222",params)
        getDrugStockList(params).then(response=>{
          if(response.data.state == 1){
             var list = response.data.data.list
             console.log("list99999",list)
             this.tableList = list
             var total = response.data.data.total
             console.log("total",total)
             this.total = total
             this.manufacturerList = response.data.data.manufacturerList
           
           }
        })
      },
      getDrugType(id){
       
        var name = ""
        for(let i=0;i<this.drugTypeList.length;i++){
           if(this.drugTypeList[i].id == id){

             name = this.drugTypeList[i].name
           }
        }
     
        return name
      },
      getManufacturerList(id){
        var name = ""
        for(let i=0;i<this.manufacturerList.length;i++){
          if(id == this.manufacturerList[i].id){
             name = this.manufacturerList[i].manufacturer_name
          }
        }
        return name
      },
      handleDetail(val){
        var manufacturer_name = ""
        for(let i=0;i<this.manufacturerList.length;i++){
         if(val.manufacturer == this.manufacturerList[i].id){
           manufacturer_name = this.manufacturerList[i].manufacturer_name
         }
        }
        var unit =  val.dose + val.dose_unit +"*"+val.min_number+val.min_unit+"/"+val.max_unit
        this.$router.push({path:'/drugstock/in/drugstockflow?drug_id='+val.drug_id+"&drug_name="+val.drug_name+"&manufacturer="+manufacturer_name+"&unit="+unit})
      },
      handleBatch(val){
        var manufacturer_name = ""
        for(let i=0;i<this.manufacturerList.length;i++){
         if(val.manufacturer == this.manufacturerList[i].id){
           manufacturer_name = this.manufacturerList[i].manufacturer_name
         }
        }
        var unit =  val.dose + val.dose_unit +"*"+val.min_number+val.min_unit+"/"+val.max_unit
        this.$router.push({path:'/drugstock/in/drugbatchnumber?drug_id='+val.drug_id+"&drug_name="+val.drug_name+"&manufacturer="+manufacturer_name+"&unit="+unit})
      },
      getDrugCountList(){
         var params = {
          keyword: this.keywords,
          start_time:this.start_time,
          end_time:this.end_time,
         }
        getDrugCountList(params).then(response=>{
          if(response.data.state == 1){
            var countlist =  response.data.data.countList
            console.log("入库数据",countlist)
            this.countList = countlist
            var outcountlist = response.data.data.outCountList
            console.log("出库数据",outcountlist)
            this.outCountList = outcountlist
            var aucountlist = response.data.data.auCountList
            console.log("自动数据",aucountlist)
            this.autoCountList = aucountlist
            var minCount = response.data.data.minCount
            console.log("minCount",minCount)
            this.minCount = minCount
            var info = response.data.data.info
            for(let i=0;i<info.length;i++){
              if(info[i].count_unit == info[i].max_unit){
                 info[i].count = info[i].count * info[i].min_number
              }
            }
            console.log("info2222222",info)
            this.drugOutList = info
            var arr = []
            for(let i=0;i<this.drugOutList.length;i++){
              if(this.drugOutList[i].drug_id == 1197){
                arr.push(this.drugOutList[i])
              }
            }
            console.log("arrr",arr)
          }
        })
      },
      getInCount(id){
        var count = ""
        for(let i=0;i<this.countList.length;i++){
           if(id == this.countList[i].drug_id){
             count = this.countList[i].count
           }
        }
        return count
      },

      getOutCount(id){
        var count = ""
        for(let i=0;i<this.outCountList.length;i++){
           if(id == this.outCountList[i].drug_id){
               count = this.outCountList[i].count
           }
        }
        return count
      },
      getAutoCount(id){
        var count= ""
        for(let i=0;i<this.autoCountList.length;i++){
          if(id == this.autoCountList[i].drug_id){
            count = this.autoCountList[i].count
          }
        }
        return count
      },
      getMinCount(id){
        var count=""
        for(let i=0;i<this.minCount.length;i++){
          if(id == this.minCount[i].drug_id){
            count = this.minCount[i].count
          }
        }
        return count
      },
      getCount(drug_id,min_number,max_unit,min_unit){
        var count= 0
        var str = ""
        var min_str = ""
        for(let i=0;i<this.drugOutList.length;i++){
          if(drug_id == this.drugOutList[i].drug_id){
             count += parseInt(this.drugOutList[i].count)
          }
        }
        if(parseInt(count/min_number)!=0){
          str = parseInt(count/min_number)+ max_unit
        }
        if((count%min_number)!=0){
          min_str =  count%min_number + min_unit
        }
        return str + min_str
      },

      getCountOne(drug_id){
        var count= 0
        for(let i=0;i<this.drugOutList.length;i++){
          if(drug_id == this.drugOutList[i].drug_id){
             count += parseInt(this.drugOutList[i].count)
          }
        }
        return count
      },
     getCountTwo(drug_id,min_number,max_unit,min_unit){
       var total_count = 0
       var out_count = 0
       var count = 0
       var str = ""
       var str_min = ""
       total_count = this.getInCount(drug_id) * min_number
       out_count = this.getCountOne(drug_id)
       count = total_count-out_count
       if(parseInt(count/min_number)!=0){
         str = parseInt(count/min_number) + max_unit
       }
       if((count%min_number)!=0){
         str_min = count%min_number + min_unit
       }
       return str+str_min
     }
    }
  }
</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;
  }

  }

  .title {
    background: #409eff;
    height: 44px;
    line-height: 44px;
    padding: 0 0 0 10px;
    color: #fff;
    margin: 0 0 10px 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;
  }

  .count {
    color: #bd2c00;
  }

  .el-table td,
  .el-table th.is-leaf,
  .el-table--border,
  .el-table--group {
    border-color: #d0d3da;
  }

  .el-table--border::after,
  .el-table--group::after,
  .el-table::before {
    background-color: #d0d3da;
  }
</style>
