<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="exportListOne"
      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"
        ></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"
        ></el-date-picker>
        <el-button
        size="small"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="getAllQuery"
        >查询</el-button
      >
      </div>
    </div>

    <!-- <el-row :gutter="12" style="margin-top: 10px"> -->
      <el-table class="eltable"
        :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'
        }"
        height="calc(100vh - 300px)"
      >
        <el-table-column label="单据编号" align="center" width="200">
          <template slot-scope="scope">
            {{scope.row.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>
            <!-- {{getTypeList(scope.row.drug_type)}} -->
          </template>
        </el-table-column>

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

        <el-table-column label="规格型号" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.specification_name}}</span>
          </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">
                {{getPatientName(scope.row.patient_id)  }}
            </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.unit}}
          </template>
        </el-table-column>
        <el-table-column label="总价" align="center">
          <template slot-scope="scope">
            {{scope.row.total_price}}
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 50, 100]"
        :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 { getDrugCancelDetail } from "@/api/drug/drug_stock";
export default {
  name: "cancelStockDetail",

  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);

    var start = window.sessionStorage.getItem('start_cancel_time')
    if(start!=null){
     this.start_time = start
    }
    if(end!=null){
      var end =  window.sessionStorage.getItem('end_cancel_time')
      this.end_time = end
    }

    this.GetConfigInfo();
    this.fetchAllAdminUsers();
    this.getlist()
  },
  data() {
    return {
      orderTypeArr: [
        { value: 1, label: "药品退库单" },
        { value: 2, label: "其他入库单" }
      ],
      manufacturer_id: "",
      dealer_id: "",
      order_type: "",
      searchKey: "",
      type: 4,
      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:[],
      tableDataList:[],
      drugTypeList:[],
      dealerList:[],
      manufacturerList:[],
      patientsList:[]
    };
  },
  methods: {
    PrintAction() {
        window.sessionStorage.setItem('start_cancel_time',this.start_time)
        window.sessionStorage.setItem('end_cancel_time',this.end_time)
        this.$router.push("/stock/drugcanceldetaiprint?start_time="+this.start_time+"&end_time="+this.end_time+"&order_type="+this.order_type+"&manufacturer_id="+this.manufacturer_id+"&keyword="+this.keyword+"&limit="+this.limit+"&page="+this.page)
    },
    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() {
      this.getlist()
    },



    fetchAllAdminUsers() {
      fetchAllAdminUsers().then(response => {
        console.log(response);
        if (response.data.state == 1) {
          this.adminUserOptions = response.data.data.users;
        }
      });
    },
    handleSelectionChange: function(val) {
      this.multipleSelection = val;
      this.getlist()
    },
    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()
      }
    },
    getAllQuery(){
      this.getlist()
    },
    getTimestamp(time) {
      // 把时间日期转成时间戳
      return new Date(time).getTime() / 1000;
    },
    calculate: function(val) {
      return Math.round(parseFloat(val) * 100) / 100;
    },
    GetConfigInfo: function() {
      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;
        }
      });
    },



    select(selection) {

    },
    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,
        limit:this.limit,
        page:this.page,
       }
       const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
       })
      getDrugCancelDetail(params).then(response=>{
         if(response.data.state == 1){
           loading.close()
           var order =  response.data.data.order
           var list = response.data.data.orderPrint
           this.dealerList =  response.data.data.dealerList
           this.manufacturerList =  response.data.data.manufacturerList
           this.patientsList =response.data.data.patientsList
           //this.drugTypeList = response.data.data.drugTypeList
           for(let i=0;i<list.length;i++){
             list[i].child = []
            for(let j=0;j<order.length;j++){
               if(list[i].drug_id == order[j].drug_id){
                  list[i].child.push(order[j])
               }
            }
            list[i].manufacturer_name = this.getManufacturerName(list[i].manufacturer)
            list[i].dealer_name = this.getDealerName(list[i].dealer)
           }
           this.tableDataList = list
           console.log("数据我我我",this.tableDataList)

           var total_price = 0
          for(let i=0;i<order.length;i++){
             order[i].specification_name  = order[i].dose + order[i].dose_unit + "*" + order[i].min_number +  order[i].min_unit + "/" + order[i].max_unit
             order[i].is_total = 0
             order[i].total_price = order[i].count * order[i].price
             total_price += order[i].count * order[i].price
             order[i].manufacturer_name = this.getManufacturerName(order[i].manufacturer)
             order[i].dealer_name = this.getDealerName(order[i].dealer)
          }

           order.push({
            order_number: "合计",
            is_total: 1,
            specification_name:"",
            unit:"",
            ctime:"",
            total_price:total_price.toFixed(2),
          });
           this.tableData = order
           this.tableList = order
           var total = response.data.data.total
           this.total = total
         }else{
          loading.close()
         }
      })
    },
    getManufacturerName(id){
        var manufacturer_name = ""
        for(let i=0;i<this.manufacturerList.length;i++){
          if(id == this.manufacturerList[i].id){
            manufacturer_name = this.manufacturerList[i].manufacturer_name
          }
        }
        return manufacturer_name
     },
     getDealerName(id){
       var dealer_name = ""
       for(let i=0;i<this.dealerList.length;i++){
          if(id == this.dealerList[i].id){
              dealer_name = this.dealerList[i].dealer_name
          }
       }
       return dealer_name
     }, 
     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
    },

     getTime: function(val) {
      if (val == 0) {
        return "";
      } else {
        return uParseTime(val, "{y}-{m}-{d}");
      }
    },
    exportList(){
       for(let i=0;i<this.tableDataList.length;i++){
        //   if(this.tableDataList[i].drug_type == 1){
        //     this.tableDataList[i].drug_type == "西药"
        //   }
        //   if(this.tableDataList[i].drug_type == 2){
        //     this.tableDataList[i].drug_type == "草药"
        //   }
        //  if(this.tableDataList[i].drug_type == 3){
        //     this.tableDataList[i].drug_type == "成药"
        //   }
          this.tableDataList[i].drug_type = this.getTypeList(this.tableDataList[i].drug_type)
          this.tableDataList[i].index = i+1
          this.tableDataList[i].unit = this.tableDataList[i].dose + this.tableDataList[i].dose_unit + "*"+this.tableDataList[i].min_number + this.tableDataList[i].min_unit+"/"+this.tableDataList[i].max_unit
          this.tableDataList[i].user_name = this.getAdminUser(this.tableDataList[i].creater)
          this.tableDataList[i].total_count  = this.getTotalCount(this.tableDataList[i].child)
          this.tableDataList[i].total_price = this.tableDataList[i].total_count * this.tableDataList[i].price
          this.tableDataList[i].ctime = this.getTime(this.tableDataList[i].ctime)
        }
       import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['序号','单据编号', '药品名称', '规格型号','生产厂商','进销商','单据类型','操作时间','制单人','数量','退库价','总价']
        const filterVal = ['index','order_number','drug_name', 'specification_name','manufacturer_name','dealer_name', 'drug_type','ctime','user_name','total_count','price','total_price']

        const data = this.formatJson(filterVal, this.tableDataList)

        excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '药品退库明细'
          })
            this.downloadLoading = false
         })
       },
     formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]));
     },
    exportListOne(){
      // let obj = {'index':'合计','total_price':0}
    
      console.log("@332322323232332",this.tableList)
       for(let i=0;i<this.tableList.length;i++){
          this.tableList[i].index = i+1
          this.tableList[i].unit_one = this.tableList[i].dose + this.tableList[i].dose_unit + "*"+this.tableList[i].min_number + this.tableList[i].min_unit+"/"+this.tableList[i].max_unit
          if(this.tableList[i].drug_type == 1){
             this.tableList[i].drugtype = "西药"
          }
          if(this.tableList[i].drug_type == 2){
             this.tableList[i].drugtype = "草药"
          }
          if(this.tableList[i].drug_type == 3){
             this.tableList[i].drugtype = "成药"
          }
          this.tableList[i].time = this.getTime(this.tableList[i].ctime)
          this.tableList[i].user_name = this.getAdminUser(this.tableList[i].creater)

        }
    
    

  
      
       import('@/vendor/Export2Excel').then(excel => {
       const tHeader = ['序号','单据编号', '药品类型','药品名称', '规格型号','生产厂商','进销商','操作时间','制单人','退货价','数量','单位','总价']
       const filterVal = ['index','order_number','drugtype','drug_name', 'specification_name','manufacturer_name','dealer_name', 'time','user_name','price','count','unit','total_price']

       const data = this.formatJson(filterVal, this.tableList)

       excel.export_json_to_excel({
           header: tHeader,
           data,
           filename: '药品退库明细'
         })
          this.downloadLoading = false
        })
     },
    getTotalCount(val){
      var total = 0
      if(val.length > 0){
         for(let i=0;i<val.length;i++){
           total +=val[i].count
         }
      }
      return total
    },
    getTypeList(id){
      var name = ""
      for(let i=0;i<this.drugTypeList.length;i++){
        if(id == this.drugTypeList[i].value){
          name = this.drugTypeList[i].name
        }
      }
      return name
    },
    getPatientName(id){
     
     var name =""
     for(let i=0;i<this.patientsList.length;i++){
       if(id == this.patientsList[i].id){
         name = this.patientsList[i].name
       }
     }
     return name
    },
  }
};
</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>
