<template>
  <div>
    <el-button
      style="float: right"
      size="small"
      icon="el-icon-printer"
      @click="PrintAction"
      type="primary"
      >打印
    </el-button>
     <el-button
      style="float: right;margin-right:10px"
      size="small"
      @click="exportListDetai"
      type="primary"
      >明细导出
    </el-button>
     <el-button
      style="float: right;margin-right:10px"
      size="small"
      @click="exportList"
      type="primary"
      >汇总导出
    </el-button>
   
    <div class="cell clearfix">
      <el-input
        size="small"
        style="width: 400px;"
        class="filter-item"
        v-model.trim="searchKey"
        placeholder="单据编码/制单人/药品名称"
      />
      <el-button
        size="small"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="search"
        >搜索</el-button
      >
      <div style="margin-left:10px;">
        <label class="title"><span class="name">日期查询</span> : </label>
        <el-date-picker
          size="small"
          v-model="start_time"
          prefix-icon="el-icon-date"
          :editable="false"
          style="width: 150px;"
          type="date"
          placeholder="选择日期时间"
          align="right"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          @change="startTimeChange"
        ></el-date-picker>
        <span class="cellLine"> - </span>
        <el-date-picker
          size="small"
          v-model="end_time"
          prefix-icon="el-icon-date"
          :editable="false"
          style="width: 150px;"
          type="date"
          placeholder="选择日期时间"
          align="right"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          @change="endTimeChange"
        ></el-date-picker>
      </div>
    </div>

    

    <!-- <div class="cell clearfix">
      <label class="title"><span class="name">单据类型</span> : </label>
      <el-select
        size="small"
        v-model="order_type"
        clearable
        placeholder="单据类型"
        @change="changeType"
      >
        <el-option
          v-for="item in orderTypeArr"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
    </div> -->

    <!-- <div class="cell clearfix">
      <label class="title"><span class="name">其它</span> : </label>
      <el-select
        size="small"
        v-model="manufacturer_id"
        clearable
        placeholder="厂商"
        @change="changeManufacturer"
      >
        <el-option
          v-for="item in manufacturer"
          :key="item.id"
          :label="item.manufacturer_name"
          :value="item.id"
        >
        </el-option>
      </el-select>
    </div> -->

    <el-row :gutter="12" style="margin-top: 10px">
      <el-table
        :data="tableData"
        :class="signAndWeighBoxPatients"
        border
        highlight-current-row
        ref="multipleTable"
        @selection-change="select"
        :row-style="{ color: '#303133' }"
        :header-cell-style="{
          backgroundColor: 'rgb(245, 247, 250)',
          color: '#606266'
        }"
      >
        <el-table-column label="单据编号" align="center" width="200">
          <template slot-scope="scope">
            {{ scope.row.warehouse_out_order_number }}
          </template>
        </el-table-column>

        <el-table-column label="药品类型" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.drug_type == 1">西药</span>
            <span v-if="scope.row.drug_type == 2">草药</span>
            <span v-if="scope.row.drug_type == 3">成药</span>
          </template>
        </el-table-column>

         <el-table-column label="药品名称" align="center">
          <template slot-scope="scope">
            {{scope.row.drug_name}}
          </template>
        </el-table-column>

        <el-table-column label="规格型号" align="center">
          <template slot-scope="scope">
           <!-- {{scope.row.drug_spec}} -->
           {{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 label="单据类型" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.type == 1">药品出库单</span>
            <span v-if="scope.row.type == 2">其他</span>
          </template>
        </el-table-column> -->

        <el-table-column label="操作时间" align="center">
          <template slot-scope="scope">
           <span>{{getTime(scope.row.ctime)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="制单人" align="center">
          <template slot-scope="scope">
           {{getAdminUser(scope.row.creater)}}
          </template>
        </el-table-column>
        <el-table-column label="出货价" align="center">
          <template slot-scope="scope">
           {{scope.row.price}}
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center">
          <template slot-scope="scope">
            {{scope.row.count}}
          </template>
        </el-table-column>
        <el-table-column label="总价" align="center">
          <template slot-scope="scope">
            {{scope.row.price * scope.row.count}}
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 50, 100,1000]"
        :page-size="10"
        background
        style="margin-top:20px;float: right"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-row>
  </div>
</template>

<script>
import { uParseTime } from "@/utils/tools";
import { fetchAllAdminUsers } from "@/api/doctor";
import {GetAllConfig } from "@/api/stock";
import {getDrugOutDetail,getDrugOutOrderPrint } from "@/api/drug/drug_stock"
 import {getBaseDrugLibList} from '@/api/data'
export default {
  name: "stockOutDetail",

  created() {
    var nowDate = new Date();
    var nowYear = nowDate.getFullYear();
    var nowMonth = nowDate.getMonth() + 1;
    var nowDay = nowDate.getDate();
    this.end_time =
      nowYear +
      "-" +
      (nowMonth < 10 ? "0" + nowMonth : nowMonth) +
      "-" +
      (nowDay < 10 ? "0" + nowDay : nowDay);
    nowDate.setMonth(nowDate.getMonth() - 1);
    nowYear = nowDate.getFullYear();
    nowMonth = nowDate.getMonth() + 1;
    nowDay = nowDate.getDate();
    this.start_time =
      nowYear +
      "-" +
      (nowMonth < 10 ? "0" + nowMonth : nowMonth) +
      "-" +
      (nowDay < 10 ? "0" + nowDay : nowDay);
    this.getDrugOutOrderPrint()
    this.GetConfigInfo();
    this.fetchAllAdminUsers();
    this.getlist()
    this.getBaseDrugLibList()
 
  },
  data() {
    return {
      orderTypeArr: [
        { value: 1, label: "药品出库单" },
        { value: 2, label: "其他入库单" }
      ],
      manufacturer_id: "",
      dealer_id: "",
      order_type:"",

      searchKey: "",
      type: 2,
      page: 1,
      limit: 10,
      checked: false,
      total: 0,
      pageTotal: 0,
      pageSelect: 0,
      adminUserOptions: [],
      multipleSelection: [],
      signAndWeighBoxPatients: "sign-and-weigh-box-patients",
      start_time: "",
      cancelStockDate: [],
      end_time: "",
      goodType: [],
      goodInfo: [],
      manufacturer: [],
      selectedTableData: [],
      dealer: [],
      tableData:[],
      tableList:[],
      drugList:[],
      tablePrint:[]
    };
  },
  methods: {
    changeType: function(val) {
      this.order_type = val;
      this.getlist()
    },
    changeManufacturer: function(val) {
      this.manufacturer_id = val;
      this.getlist()
    },
    getTypeName: function(row) {
      let name = "";
      const name2 = "";
      if (row.type == 1) {
        name = "药品出库单";
      } else if (row.type == 2) {
        name = "其他出库单";
      }

      return name;
    },
    search: function() {
      this.getlist()
    },

    getXuserName(id) {
      if (id <= 0) {
        return "";
      }
      var name = "";
      if (
        this.adminUserOptions == null ||
        typeof this.adminUserOptions.length === "undefined"
      ) {
        return name;
      }
      var leng = this.adminUserOptions.length;
      if (leng == 0) {
        return name;
      }
      for (let index = 0; index < leng; index++) {
        if (this.adminUserOptions[index].id == id) {
          name = this.adminUserOptions[index].name;
          break;
        }
      }
      return name;
    },
    fetchAllAdminUsers() {
      fetchAllAdminUsers().then(response => {
        console.log(response);
        if (response.data.state == 1) {
          this.adminUserOptions = response.data.data.users;
        }
      });
    },
    handleSelectionChange: function(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.limit = val;
      this.getlist()
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getlist()
    },
    startTimeChange(val) {
      var time = this.getTimestamp(val) - this.getTimestamp(this.end_time);
      if (time > 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.start_time = "";
      } else {
         this.getlist()
      }
    },
    endTimeChange(val) {
      var time = this.getTimestamp(val) - this.getTimestamp(this.start_time);
      if (time < 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.end_time = "";
      } else {
        this.getlist()
      }
    },
    getTimestamp(time) {
      // 把时间日期转成时间戳
      return new Date(time).getTime() / 1000;
    },
    calculate: function(val) {
      return Math.round(parseFloat(val) * 100) / 100;
    },
    GetConfigInfo() {
      GetAllConfig().then(response => {
        if (response.data.state == 0) {
          this.$message.error(response.data.msg);
          return false;
        } else {
          this.manufacturer = response.data.data.manufacturer;
          this.dealer = response.data.data.dealer;
          this.goodInfo = response.data.data.goodInfo;
          this.goodType = response.data.data.goodType;
        }
      });
    },
   
    getTime: function(val) {
      if (val == 0) {
        return "";
      } else {
        return uParseTime(val, "{y}-{m}-{d}");
      }
    },
    PrintAction: function() {
       this.$router.push("/stock/drugoutorderprint?start_time="+this.start_time+"&end_time="+this.end_time+"&order_type="+2+"&manufacturer_id="+this.manufacturer_id+"&keyword="+this.keyword+"&limit="+this.limit+"&page="+this.page)
    },
    getlist(){
      var params = {
         start_time:this.start_time,
         end_time:this.end_time,
         order_type:this.order_type,
         manufacturer_id:this.manufacturer_id,
         keyword:this.searchKey,
         page:this.page,
         limit:this.limit,
      }  
      getDrugOutDetail(params).then(response=>{
        if(response.data.state == 1){
          var order = response.data.data.order
          console.log("出库数据",order)
          this.tableData = order
           let objInfo = {}
          order.forEach((item,index)=>{
             let { drug_id } = item
             if(!objInfo[drug_id]){
               objInfo[drug_id] = {
                 drug_id,
                 child:[],
                 drug_name:item.drug_name,
                 drug_spec:item.drug_spec,
                 min_unit:item.min_unit,
                 count:0,
                 price:item.price,
                 remark:item.remark,
                 total_price:0,
                 dose:item.dose,
                 dose_unit:item.dose_unit,
                 min_number:item.min_number,
                 max_unit:item.max_unit
               }
             }
          })
          let list = Object.values(objInfo);
          
          for(let i=0;i<order.length;i++){
            list.map(item=>{
              if(order[i].drug_id == item.drug_id){
                 item.child.push(order[i])
              }
            })
          }
          
         
          for(let i=0;i<list.length;i++){
            for(let j=0;j<list[i].child.length;j++){
              if(list[i].child[j].count!=null || list[i].child[j].count != "" || list[i].child[j].count!=0){
                list[i].count += list[i].child[j].count
              }
            }
          }
          for(let i=0;i<list.length;i++){
             list[i].total_price = list[i].count * list[i].price
          }
         
          this.tableList = list
          var total = response.data.data.total
          this.total = total
        } 
      }) 
    },

   select(){
       
   },

    getAdminUser(id){
      var name = ""
      for(let i=0;i<this.adminUserOptions.length;i++){
          if(id == this.adminUserOptions[i].id){
             name = this.adminUserOptions[i].name
          }
      }
      return name
    },

     exportList(){

        for(let i=0;i<this.tablePrint.length;i++){
          this.tablePrint[i].index = i+1
          
        }
        for(let i=0;i<this.tablePrint.length;i++){
           this.tablePrint[i].count = this.getCount(this.tablePrint[i].child,this.tablePrint[i].max_unit,this.tablePrint[i].min_unit,this.tablePrint[i].min_number)
           this.tablePrint[i].total_price = this.getTotalPrice(this.tablePrint[i].child,this.tablePrint[i].max_unit,this.tablePrint[i].min_number,this.tablePrint[i].price)
           this.tablePrint[i].unit = this.tablePrint[i].dose + this.tablePrint[i].dose_unit + "*" + this.tablePrint[i].min_number +this.tablePrint[i].min_unit +"/"+this.tablePrint[i].max_unit
            this.tablePrint[i].total = this.getTotalPriceOne(this.tablePrint[i].child,this.tablePrint[i].max_unit,this.tablePrint[i].min_number,this.tablePrint[i].price) 
        }
       console.log("列表数据333333333",this.tablePrint)
     
       import('@/vendor/Export2Excel').then(excel => {
       const tHeader = ['序号','药品名称', '规格型号', '单位','数量','单价','总价','备注']
       const filterVal = ['index','drug_name', 'unit', 'min_unit','count','price','total_price','remark']
       let obj = {'index':'合计','total_price':0}
       for(let i=0;i<this.tablePrint.length;i++){
         obj.total_price += this.tablePrint[i].total 
       }
       this.tablePrint.push(obj)
       const data = this.formatJson(filterVal, this.tablePrint)
       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]));
     },
    exportListDetai(){
      import('@/vendor/Export2Excel').then(excel => {
       const tHeader = ['序号','单据编号', '药品类型', '药品名称','规格型号','操作时间','制单人','出货价','数量','总价']
       const filterVal = ['index','warehouse_out_order_number', 'drugtype', 'drug_name','specification_name','time','user_name','price','count','total_price']
       for(let i=0;i<this.tableData.length;i++){
         this.tableData[i].index = i+1
         if(this.tableData[i].drug_type == 1){
            this.tableData[i].drugtype = "西药"
         }
         if(this.tableData[i].drug_type == 2){
            this.tableData[i].drugtype = "草药"
         }
         if(this.tableData[i].drug_type == 3){
            this.tableData[i].drugtype = "成药"
         }
        this.tableData[i].specification_name = this.tableData[i].dose + this.tableData[i].dose_unit +"*" + this.tableData[i].min_number + this.tableData[i].min_unit +  "/" + this.tableData[i].max_unit
        this.tableData[i].time = this.getTime(this.tableData[i].ctime)
        this.tableData[i].user_name = this.getAdminUser(this.tableData[i].creater)
        this.tableData[i].total = (this.tableData[i].count * this.tableData[i].price)
        this.tableData[i].total_price = (this.tableData[i].count * this.tableData[i].price)
       }
       let obj = {'index':'合计','total_price':0}
       for(let i=0;i<this.tableData.length;i++){
         obj.total_price += this.tableData[i].total 
       }
       
       this.tableData.push(obj)
       for(let j=0;j<this.tableData.length;j++){
          this.tableData[j].total_price = this.tableData[j].total_price.toFixed(2)
       }
       const data = this.formatJson(filterVal, this.tableData)
       console.log("data",data)
       
       excel.export_json_to_excel({
           header: tHeader,
           data,
           filename: '药品出库明细'
         })
          this.downloadLoading = false
      }) 
    },

    getBaseDrugLibList() {
        let params = {
          page: 1,
          limit: 1000,
          keyword:"",
          is_use: "",
          is_charge: "",
          is_inject: "",
          manufacturer:"",
          is_record:""
        }
        getBaseDrugLibList(params).then(response => {
          if (response.data.state == 0) {
            this.$message.error(response.data.msg)
            return false
          } else {
            this.drugList = []
            for (let i = 0; i < response.data.data.list.length; i++) {
              this.drugList.push(response.data.data.list[i])
            }
            console.log("药品列表",this.drugList)
          }
        })
      },
    getDrugOutOrderPrint(){
       var params = {
         start_time:this.start_time,
         end_time:this.end_time,
         order_type:2,
      }  
      console.log("poara232323223233223",params)
     getDrugOutOrderPrint(params).then(response=>{
        if(response.data.state == 1){
            var list = response.data.data.list
            console.log("药品出库详情",list)
            let objInfo = {}
            list.forEach((item,index)=>{
              let { drug_id } = item
              if(!objInfo[drug_id]){
                objInfo[drug_id] = {
                  drug_id,
                  child:[],
                  drug_name:item.XtBaseDrug.drug_name,
                  drug_spec:item.XtBaseDrug.drug_spec,
                  min_unit:item.XtBaseDrug.min_unit,
                  count:0,
                  price:item.XtBaseDrug.last_price,
                  remark:item.XtBaseDrug.remark,
                  total_price:"",
                  dose:item.XtBaseDrug.dose,
                  dose_unit:item.XtBaseDrug.dose_unit,
                  min_number:item.XtBaseDrug.min_number,
                  max_unit:item.XtBaseDrug.max_unit,
                  min_price:item.XtBaseDrug.min_price,
                }
              }
            })
            let newArr = Object.values(objInfo);
            for(let i=0;i<newArr.length;i++){
              for(let j=0;j<list.length;j++){
                if(newArr[i].drug_id == list[j].drug_id){
                   newArr[i].child.push(list[j])
                }
              }
            }
           this.tablePrint = newArr
           console.log(" this.tablePrint",this.tablePrint)  
        }
     })
    },
   getCount(arr,max_unit,min_unit,min_number){
        var total = 0
        var str = ""
        var min_str = ""
        for(let i=0;i<arr.length;i++){
          if(arr[i].count_unit == max_unit){
            arr[i].count = arr[i].count * min_number
          }
        }
        for(let i=0;i<arr.length;i++){
          total+= arr[i].count
        }

       if(total<min_number){
           str = ""
           min_str = total + min_unit
        }
        if(total >= min_number){
          if(parseInt(total/min_number)!=0){
            str = parseInt(total/min_number)+ max_unit
          }
          if((total%min_number)!=0){
            min_str =  total%min_number + min_unit
          }
        }
        return str + min_str
      },
      getTotalPrice(arr,max_unit,min_number,min_price){
        var total = 0
        for(let i=0;i<arr.length;i++){
          if(arr[i].count_unit == max_unit){
            arr[i].count = arr[i].count * min_number
          }else{
            arr[i].count = arr[i].count
          }
        }  
        for(let j=0;j<arr.length;j++){
          total +=arr[j].count
        }
        console.log("total23232",total)
        return (total*min_price).toFixed(2)
      },

      getTotalPriceOne(arr,max_unit,min_number,min_price){
        var total = 0
        for(let i=0;i<arr.length;i++){
          if(arr[i].count_unit == max_unit){
            arr[i].count = arr[i].count * min_number
          }else{
            arr[i].count = arr[i].count
          }
        }  
        for(let j=0;j<arr.length;j++){
          total +=arr[j].count
        }
        console.log("total23232",total)
        return total*min_price
      }
  }
};
</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;
}

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