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

      <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">
        <el-checkbox
          style="width: 70px"
          v-model="checked"
          @change="changeAllSelected"
          >全选</el-checkbox
        >
        <el-button size="small" icon="el-icon-delete" @click="batchDelete"
          >删除</el-button
        >
      </div>

      <el-table
        :data="warehouseOutDate"
        :class="signAndWeighBoxPatients"
        style="width: 100%"
        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" align="center"> </el-table-column>

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

        <el-table-column label="单据编号" align="center">
          <template slot-scope="scope">
            {{ scope.row.warehouse_out_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 min-width="35" align="center">
          <template slot="header" slot-scope="scope">
            <span>出库方式</span>
          </template>
          <template slot-scope="scope">
            <span v-if="scope.row.is_sys == 1">{{"自动出库"}}</span>
            <span v-if="scope.row.is_sys != 1">{{"手动出库"}}</span>

          </template>
        </el-table-column>

        <el-table-column label="厂家" align="center">
          <template slot-scope="scope">
            {{scope.row.manufacturers ? scope.row.manufacturers.manufacturer_name:''}}
          </template>
        </el-table-column>

        <el-table-column label="经销商" align="center">
          <template slot-scope="scope">
            {{scope.row.dealers ? scope.row.dealers.dealer_name:''}}
          </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"
                :disabled="scope.row.is_sys == 1"
                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="[10, 50, 100]"
        :page-size="10"
        background
        style="margin-top:20px;float: right"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { uParseTime } from "@/utils/tools";
import { fetchAllAdminUsers, fetchAllDoctorAndNurse } from "@/api/doctor";

import {
  deleteDrugWarehouseOut,
  GetAllConfig,
  getDrugWarehouseOutList
} from "@/api/drug/drug_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.GetWarehouseOut();
    this.GetConfigInfo();
    this.fetchAllAdminUsers();
  },
  data() {
    return {
      searchKey: "",
      crumbs: [
        { path: false, name: "库存管理" },
        { path: false, name: "出库单" }
      ],
      page: 1,
      limit: 10,
      checked: false,
      total: 0,
      pageTotal: 0,
      pageSelect: 0,
      adminUserOptions: [],
      multipleSelection: [],
      signAndWeighBoxPatients: "sign-and-weigh-box-patients",
      start_time: "",
      warehouseOutDate: [],
      end_time: "",
      goodType: [],
      goodInfo: [],
      manufacturer: [],
      selectedTableData: [],
      dealer: [],
      type: 1
    };
  },
  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.warehouseOutDate = [];
      getDrugWarehouseOutList(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.warehouseOutDate.push(response.data.data.list[i]);
          }
        }
      });
    },
    AddNewOrder: function() {
      this.$router.push({
        name: "drugStockOutOrderAdd",
        query: { type: this.type }
      });
    },
     GetWarehouseOut: function() {
      const Params = {
        page: this.page,
        limit: this.limit,
        start_time: this.start_time,
        end_time: this.end_time,
        type: this.type
      };
      this.warehouseOutDate = [];
      getDrugWarehouseOutList(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.warehouseOutDate.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.GetWarehouseOut();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.GetWarehouseOut();
    },
    startTimeChange(val) {
      var time = this.getTimestamp(val) - this.getTimestamp(this.end_time);
      if (time > 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.start_time = "";
      } else {
        this.GetWarehouseOut();
      }
      this.GetWarehouseOut();
    },
    endTimeChange(val) {
      var time = this.getTimestamp(val) - this.getTimestamp(this.start_time);
      if (time < 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.end_time = "";
      } else {
        this.GetWarehouseOut();
      }
    },
    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;
        }
      });
    },

    handleEdit: function(index, row) {
      this.$router.push({
        name: "drugStockOutDetail",
        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(() => {
          deleteDrugWarehouseOut(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.warehouseOutDate.length; y++) {
                  if (ids[i] == this.warehouseOutDate[y].id) {
                    this.warehouseOutDate.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(() => {
          deleteDrugWarehouseOut(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.warehouseOutDate.length; y++) {
                  if (ids[i] == this.warehouseOutDate[y].id) {
                    this.warehouseOutDate.splice(y, 1);
                  }
                }
              }
            }
          });
        })
        .catch(() => {});
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.app-container {
  // margin: 20px;
  font-size: 15px;
  .filter-container {
    padding-bottom: 5px;
  }
  .search-component {
    width: 500px;
    .searchBox {
      width: 300px;
      height: 36px;
      line-height: 36px;
      padding-left: 15px;
      border: 1px #dcdfe6 solid;
      border-right: none;
      outline: none;
      float: left;
      border-radius: 6px 0 0 6px;
      font-size: 14px;
      color: #333;
      background: #fff;
      box-shadow: 3px 3px 4px rgba(135, 135, 135, 0.05);
    }
    .searchBtn {
      background-color: #409eff;
      color: #fff;
      font-size: 15px;
      text-align: center;
      height: 36px;
      line-height: 36px;
      float: left;
      outline: none;
      width: 70px;
      border: none;
      border-radius: 0 6px 6px 0;
      font-family: "Microsoft Yahei";
      cursor: pointer;
    }
  }

  .amount {
    font-weight: normal;
    padding: 10px 0 0 0;
    color: #606266;
    font-size: 14px;
    span {
      color: #ef2525;
      font-family: "Arial";
      padding: 0 2px;
    }
  }
}
.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>
