<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"
      icon="el-icon-printer"
      @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>

    <div class="cell clearfix">
      <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 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="cancelStockDate"
        :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.order_number }}
          </template>
        </el-table-column>

        <el-table-column label="耗材类型" align="center">
          <template slot-scope="scope">
            {{ typeName(scope.row.good_type_id) }}
          </template>
        </el-table-column>

         <el-table-column label="耗材名称" align="center">
          <template slot-scope="scope">
            {{ typeNameOne(scope.row.good_id) }}
          </template>
        </el-table-column>

        <el-table-column label="规格型号" align="center">
          <template slot-scope="scope">
            {{ specificationName(scope.row.good_id) }}
          </template>
        </el-table-column>

        <el-table-column label="单据类型" align="center">
          <template slot-scope="scope">
            {{ getTypeName(scope.row) }}
          </template>
        </el-table-column>

        <el-table-column label="操作时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.CancelStock.return_time | parseTime("{y}-{m}-{d}") }}
          </template>
        </el-table-column>
        <el-table-column label="制单人" align="center">
          <template slot-scope="scope">
            {{ getXuserName(scope.row.CancelStock.creater) }}
          </template>
        </el-table-column>

        <el-table-column label="数量" align="center">
          <template slot-scope="scope">
            {{ scope.row.count }}
          </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, fetchAllDoctorAndNurse } from "@/api/doctor";
import { deleteCancelStock, GetAllConfig, getStockDetail } from "@/api/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);
    this.GetCancelStock();
    this.GetConfigInfo();
    this.fetchAllAdminUsers();
    this.goodUnit = this.$store.getters.good_unit
  },
  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: [],
      tableList:[],
      goodUnit:[]
    };
  },
  methods: {
    PrintAction: function() {
      this.$router.push({
        path: "/stock/print",
        query: {
          type: 4,
          start_time: this.start_time,
          end_time: this.end_time
        }
      });
    },
    changeType: function(val) {
      this.order_type = val;
      this.GetCancelStock();
    },
    changeManufacturer: function(val) {
      this.manufacturer_id = val;
      this.GetCancelStock();
    },
    getTypeName: function(row) {
      let name = "";
      const name2 = "";
      if (row.type == 1) {
        name = "耗材退库单";
      } else if (row.type == 2) {
        name = "其他退库单";
      }

      return name;
    },
    typeName: function(good_type_id) {
      let name = "";
      for (let i = 0; i < this.goodType.length; i++) {
        if (this.goodType[i].id == good_type_id) {
          name = this.goodType[i].type_name;
        }
      }
      return name;
    },
    typeNameOne: function(good_id) {
     let name = "";
      for (let i = 0; i < this.goodInfo.length; i++) {
        if (this.goodInfo[i].id == good_id) {
          name = this.goodInfo[i].good_name;
        }
      }
      return name;
    },
    specificationName: function(good_info_id) {
      let name = "";
      for (let i = 0; i < this.goodInfo.length; i++) {
        if (this.goodInfo[i].id == good_info_id) {
          name = this.goodInfo[i].specification_name;
        }
      }
      return name;
    },
    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 = [];
      getStockDetail(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,
        manufacturer: this.manufacturer_id,
        order_type: this.order_type,
        dealer: this.dealer_id
      };
      
      this.cancelStockDate = [];
      getStockDetail(Params).then(response => {
        if (response.data.state == 0) {
          this.$message.error(response.data.msg);
          return false;
        } else {
          this.total = response.data.data.total;
          console.log("数据源头",response.data.data.list)
          for (let i = 0; i < response.data.data.list.length; i++) {
            this.cancelStockDate.push(response.data.data.list[i]);
            this.tableList.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();
      }
    },
    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;
          this.goodInfo = response.data.data.goodInfo;
          this.goodType = response.data.data.goodType;
        }
      });
    },
    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) {
      this.$router.push({
        name: "cancelStockDetail",
        query: { id: row.id, type: this.type }
      });
    },
    handleDelete: function(index, row) {
      const ids = [];
      ids.push(row.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(() => {});
    },
    changeAllSelected: function(val) {
      if (val) {
        this.$refs.multipleTable.toggleAllSelection();
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    select(selection) {
      this.selectedTableData = selection;
    },
    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(() => {});
    },
      exportList(){
     
        for(let i=0;i<this.tableList.length;i++){
          this.tableList[i].index = i+1
          this.tableList[i].drug_name =  this.typeNameOne(this.tableList[i].good_id) 
          this.tableList[i].drug_spec =  this.specificationName(this.tableList[i].good_id)
          this.tableList[i].min_unit = this.getUnit(this.tableList[i].GoodInfo.good_unit)
          this.tableList[i].remark = this.tableList[i].GoodInfo.remark
         
        }
       import('@/vendor/Export2Excel').then(excel => {
       const tHeader = ['序号','耗材名称', '规格型号', '单位','数量','备注']
       const filterVal = ['index','drug_name', 'drug_spec', 'min_unit','count','remark']
       
       const data = this.formatJson(filterVal, this.tableList)
       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]));
     },
     getUnit(id){
      var name = ""
      for(let i=0;i<this.goodUnit.length;i++){
       if(this.goodUnit[i].id == id){
          name = this.goodUnit[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>