<template>
  <div class="main-contain">
    <div class="position">
      <bread-crumb :crumbs="crumbs"></bread-crumb>
      <el-button
        size="small"
        @click="AddNewOrder"
        class="filter-item"
        style="float:right;"
        type="primary"
        icon="el-icon-circle-plus-outline"
        >新增
      </el-button>
    </div>

    <div class="app-container">
      <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: 196px;"
            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: 196px;"
            type="date"
            placeholder="选择日期时间"
            align="right"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            @change="endTimeChange"
          ></el-date-picker>
        </div>
      </div>

      

      <div class="filter-container" style="margin-top: 10px">
        <el-checkbox
          style="width: 70px"
          v-model="checked"
          @change="changeAllSelected"
          >全选</el-checkbox
        >
        <el-button size="small" icon="el-icon-delete" @click="batchDelete">删除</el-button>
        <el-button size="small" type="primary" @click="toPrint">打印</el-button>
        <el-button size="small" type="primary" @click="toExport">导出</el-button>
      </div>

      <el-row :gutter="12" style="margin-top: 10px">
        <el-table
          :data="cancelStockDate"
          @current-change='currentChange' 
          :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 type="selection" width="55"> </el-table-column>

          <el-table-column label="单据日期" align="center">
            <template slot-scope="scope">
              {{ scope.row.return_time | parseTime("{y}-{m}-{d}") }}
            </template>
          </el-table-column>

          <el-table-column label="单据编号" align="center">
            <template slot-scope="scope">
              {{ scope.row.order_number }}
            </template>
          </el-table-column>

          <el-table-column label="制单人" align="center">
            <template slot-scope="scope">
              {{ getXuserName(scope.row.creater) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="dark"
                content="编辑"
                placement="top"
              >
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit-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-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[5,10, 50, 100]"
          :page-size="5"
          background
          style="margin-top:20px;float: right"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </el-row>

     <div   v-show="showTable" style="margin-top:10px">
       <el-table
          :data="tableList"
          :class="signAndWeighBoxPatients"
          border
          highlight-current-row
          ref="multipleTableOne"
          @selection-change="select"
          :row-style="{ color: '#303133' }"
          :header-cell-style="{
            backgroundColor: 'rgb(245, 247, 250)',
            color: '#606266'
          }"
        >
          <el-table-column type="selection" width="55"> </el-table-column>

          <el-table-column label="耗材名称" align="center">
            <template slot-scope="scope">
              {{scope.row.GoodInfo.good_name}}
            </template>
          </el-table-column>

          <el-table-column label="规格&单位" align="center">
            <template slot-scope="scope">
              {{scope.row.GoodInfo.specification_name}} / {{scope.row.GoodInfo.packing_unit}}
            </template>
          </el-table-column>

           <el-table-column label="国家编码" align="center">
            <template slot-scope="scope">
              {{scope.row.GoodInfo.social_security_directory_code}}
            </template>
          </el-table-column>

          <el-table-column label="退库数量" align="center">
            <template slot-scope="scope">
              {{ scope.row.count}}{{scope.row.GoodInfo.packing_unit}}
            </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.number}}
            </template>
          </el-table-column> -->

         <el-table-column label="品名/注册证号(备案凭证号)" align="center">
            <template slot-scope="scope">
              {{ scope.row.register_account}}
            </template>
          </el-table-column>

         <el-table-column label="生产厂家" align="center">
            <template slot-scope="scope">
              {{ scope.row.manufacturer}}
            </template>
          </el-table-column>

         <el-table-column label="生产日期" align="center">
            <template slot-scope="scope">
              {{getTime(scope.row.product_date,"{y}-{h}-{d}")}}
            </template>
          </el-table-column>

          <el-table-column label="有效期" align="center">
            <template slot-scope="scope">
              {{getTime(scope.row.expiry_date,"{y}-{h}-{d}")}}
            </template>
          </el-table-column>

         <el-table-column label="经销商" align="center">
            <template slot-scope="scope">
              {{ scope.row.dealer}}
            </template>
          </el-table-column>

         <el-table-column label="退库原因" align="center">
            <template slot-scope="scope">
              {{ scope.row.remark}}
            </template>
          </el-table-column>

        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { uParseTime } from "@/utils/tools";
import { fetchAllAdminUsers, fetchAllDoctorAndNurse } from "@/api/doctor";
import {
  deleteCancelStock,
  GetAllConfig,
  getCancelStockList,
  getSingCancelOrder,
  getCancelExportList
} from "@/api/stock";
import BreadCrumb from "../components/bread-crumb";

export default {
  name: "salesReturnOrder",
  components: { BreadCrumb },
  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.GetCancelStock();
    this.GetConfigInfo();
    this.fetchAllAdminUsers();
  },
  data() {
    return {
      crumbs: [
        { path: false, name: "库存管理" },
        { path: false, name: "出库退库单" }
      ],
      searchKey: "",
      type: 1,
      page: 1,
      limit: 5,
      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: [],
      tableList:[],
      showTable:false,
      order_id:"",
      exportList:[]
    };
  },
  methods: {
    search: function() {
      const Params = {
        page: this.page,
        limit: this.limit,
        start_time: this.start_time,
        end_time: this.end_time,
        type: this.type,
        keywords: this.searchKey
      };
      this.cancelStockDate = [];
      getCancelStockList(Params).then(response => {
        if (response.data.state == 0) {
          this.$message.error(response.data.msg);
          return false;
        } else {
          this.total = response.data.data.total;
          for (let i = 0; i < response.data.data.list.length; i++) {
            this.cancelStockDate.push(response.data.data.list[i]);
          }
        }
      });
    },
    AddNewOrder: function() {
      this.$router.push({
        name: "cancelStockOrderAdd",
        query: { type: this.type }
      });
    },
    GetCancelStock: function() {
      const Params = {
        page: this.page,
        limit: this.limit,
        start_time: this.start_time,
        end_time: this.end_time,
        type: this.type
      };
      this.cancelStockDate = [];
      getCancelStockList(Params).then(response => {
        if (response.data.state == 0) {
          this.$message.error(response.data.msg);
          return false;
        } else {
          this.total = response.data.data.total;
          for (let i = 0; i < response.data.data.list.length; i++) {
            this.cancelStockDate.push(response.data.data.list[i]);
          }
        }
      });
    },
    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;
          var alen = this.adminUserOptions.length;
          for (let index = 0; index < alen; index++) {
            if (this.adminUserOptions[index].user_type == 2) {
              // this.doctorOptions.push(this.adminUserOptions[index]);
            }
          }
        }
      });
    },
    handleSelectionChange: function(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.limit = val;
      this.GetCancelStock();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.GetCancelStock();
    },
    startTimeChange(val) {
      var time = this.getTimestamp(val) - this.getTimestamp(this.end_time);
      if (time > 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.start_time = "";
      } else {
        this.GetCancelStock();
      }
      this.GetCancelStock();
    },
    endTimeChange(val) {
      var time = this.getTimestamp(val) - this.getTimestamp(this.start_time);
      if (time < 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.end_time = "";
      } else {
        this.GetCancelStock();
      }
    },
    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;
        }
      });
    },
    getManufactuerName: function(manufacturer_id) {
      for (let i = 0; i < this.manufacturer.length; i++) {
        if (this.manufacturer[i].id == manufacturer_id) {
          return this.manufacturer[i].manufacturer_name;
        }
      }
    },
    getDealerName: function(dealer_id) {
      for (let i = 0; i < this.dealer.length; i++) {
        if (this.dealer[i].id == dealer_id) {
          return this.dealer[i].dealer_name;
        }
      }
    },
    handleEdit: function(index, row) {
      console.log("row22222",row.id)
      this.$router.push({"path":"/stock/cancel/cancelstockorderedit?id="+row.id})
    },
    handleDelete: function(index, row) {
      const ids = [];
      ids.push(row.id);
      const idStr = ids.join(",");

      const params = {
        ids: idStr
      };
      console.log("params233223232323232323",params)
     
      this.$confirm("确认删除退库单记录?", "删除退库单记录", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteCancelStock(params).then(response => {
            if (response.data.state == 0) {
              this.$message.error(response.data.msg);
              return false;
            } else {
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
                duration: 2000
              });
              for (let i = 0; i < ids.length; i++) {
                for (let y = 0; y < this.cancelStockDate.length; y++) {
                  if (ids[i] == this.cancelStockDate[y].id) {
                    this.cancelStockDate.splice(y, 1);
                  }
                }
              }
            }
          });
        })
        .catch(() => {});
    },
    changeAllSelected(val) {
     
      if (val) {
        this.$refs.multipleTable.toggleAllSelection();
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    select(val) {
      var ids = []
      for(let i=0;i<val.length;i++){
         ids.push(val[i].id)
      }
      this.order_id = ids.join(",")
      this.selectedTableData = val;
      this.getCancelExportList()
    },
    batchDelete() {
      if (this.selectedTableData.length <= 0) {
        this.$message.error("请选择要删除的记录");
        return;
      }
      const ids = [];
      for (let i = 0; i < this.selectedTableData.length; i++) {
        ids.push(this.selectedTableData[i].id);
      }
      const idStr = ids.join(",");
      const params = {
        ids: idStr
      };
      this.$confirm("确认删除退库单记录?", "删除退库单记录", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteCancelStock(params).then(response => {
            if (response.data.state == 0) {
              this.$message.error(response.data.msg);
              return false;
            } else {
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
                duration: 2000
              });

              for (let i = 0; i < ids.length; i++) {
                for (let y = 0; y < this.cancelStockDate.length; y++) {
                  if (ids[i] == this.cancelStockDate[y].id) {
                    this.cancelStockDate.splice(y, 1);
                  }
                }
              }
            }
          });
        })
        .catch(() => {});
    },
    currentChange(val){
        var params ={
          id:val.id
        }
      getSingCancelOrder(params).then(response=>{
        if(response.data.state == 1){
          var list = response.data.data.list
          console.log("list0000000000",list)
          this.tableList = list
          this.showTable = true
        }
      }) 
    },
    toPrint(){
      console.log("22222",this.order_id)
      if(this.order_id == ""){
        this.$message.error("请勾选退库单")
      }else{
        console.log("232332332")
        this.$router.push({path:'/stock/drugs/cancelstockorderprint?order_id='+this.order_id+"&start_time="+this.start_time+"&end_time="+this.end_time})
      }
    },
    getTime(val) {
      if(val < 0){
        return ""
      }
      if(val == ""){
      return ""
      }else {
      return uParseTime(val, '{y}-{m}-{d}')
      }
    },
    getCancelExportList(){
       const Params = {
        start_time: this.start_time,
        end_time: this.end_time,
        order_id:this.order_id,
      };
      console.log("params2323232",Params)
     getCancelExportList(Params).then(response=>{
        if(response.data.state == 1){
          var list =  response.data.data.list
          console.log("list2323232",list)
          this.exportList = list
        }
     })
    },
   
    toExport(){
      if(this.order_id == ""){
        this.$message.error("请勾选退库单")
        return
      }
     import('@/vendor/Export2Excel').then(excel => {
      console.log("23232323",this.exportList)
      for(let i=0;i<this.exportList.length;i++){
        this.exportList[i].total_price = this.exportList[i].count * this.exportList[i].price
        this.exportList[i].good_name = this.exportList[i].GoodInfo.good_name
        this.exportList[i].unit = this.exportList[i].GoodInfo.specification_name + "/" +this.exportList[i].GoodInfo.packing_unit
        if(this.exportList[i].dealer == 0){
          this.exportList[i].dealer = ""
        }
        if(this.exportList[i].manufacturer == 0){
          this.exportList[i].manufacturer = ""
        }
      
        this.exportList[i].product_date = this.getTime(this.exportList[i].product_date,"{y}-{h}-{d}")
        this.exportList[i].expiry_date = this.getTime(this.exportList[i].expiry_date,"{y}-{h}-{d}")
      }
      const tHeader = ['耗材名称',  '规格&单位','退库数量','退库单价','批次','品名/注册证号(备案凭证号)','生产厂家','生产日期','有效期','退库原因']
      const filterVal = ['good_name', 'unit','count','price','number','register_account','manufacturer','product_date','expiry_date','remark']
      console.log("table",this.exportList)
     
      const data = this.formatJson(filterVal, this.exportList)
      excel.export_json_to_excel({
        header: tHeader,
        data,
        filename: '耗材退库单详情'
      })
      this.downloadLoading = false
     })
    },
    formatJson(filterVal, jsonData) {
    return jsonData.map(v => filterVal.map(j => v[j]));
   },
  }
};
</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>
