<template>
  <div class="main-contain">
    <div class="position">
      <bread-crumb :crumbs="crumbs"></bread-crumb>
      <el-button
        size="small"
        @click="handleWarehouse"
        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">
        <label class="title"><span class="name">仓库</span> :</label>
        <el-select
          size="small"
          v-model="storehouse_id"
          filterable
          placeholder="请选择仓库"
          style="width: 200px"
          @change="changeStoreHouse"
        >
          <el-option
            v-for="(option, index) in houseList"
            :key="index"
            :label="option.storehouse_name"
            :value="option.id"
          >
          </el-option>
        </el-select>
        <el-input
          size="small"
          style="width: 200px"
          v-model.trim="searchKey"
          class="filter-item"
          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 style="margin-left: 10px">
          <span>审核状态:</span>
          <el-select
            v-model="check_id"
            style="width: 140px; margin-right: 10px"
            placeholder="请选择"
            @change="changeTypeName"
          >
            <el-option
              v-for="item in checkList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div> -->
      </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
        >
        <el-button size="small" type="primary" @click="drugPrint()"
          >打印</el-button
        >
        <el-button size="small" type="primary" @click="toExport()" :disabled="exportLoding">导出</el-button>
        <div>
          <span>&nbsp;&nbsp;</span>
          <label class="title"><span class="name">审核状态</span> :</label>
          <el-select
            size="small"
            v-model="check_type"
            filterable
            placeholder="请选择仓库"
            style="width: 200px"
            @change="changeCheckType"
          >
            <el-option
              v-for="(option, index) in checkList"
              :key="index"
              :label="option.name"
              :value="option.id"
            >
            </el-option>
          </el-select>
        </div>
      </div>

      <el-table
        :data="Warehouse.warehouseDate"
        :class="signAndWeighBoxPatients"
        style="width: 100%"
        border
        highlight-current-row
        v-loading="Warehouse.loading"
        ref="multipleTable"
        @selection-change="select"
        :row-style="{ color: '#303133' }"
        :header-cell-style="{
          backgroundColor: 'rgb(245, 247, 250)',
          color: '#606266',
        }"
        @current-change="handleCurrentChangeOne"
      >
        <el-table-column align="center" type="selection" width="55">
        </el-table-column>

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

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

        <el-table-column label="仓库名称" align="center">
          <template slot-scope="scope">
            {{ getHouseName(scope.row.storehouse_id) }}
          </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">
            <span v-if="scope.row.is_sys == 13">调拨入库</span>
            <span v-else>手动入库</span>
          </template>
        </el-table-column>

        <el-table-column label="审核状态" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.is_check == 1">已审核</span>
            <span v-if="scope.row.is_check == 2">未审核</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="240">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑"
              placement="top"
            >
              <el-button
                size="small"
                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="small"
                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; text-align: right"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <el-table
        v-show="showOne"
        :data="WarehouseInfo.warehouseInfoDate"
        :class="signAndWeighBoxPatients"
        style="width: 100%; margin-top: 10px"
        border
        highlight-current-row
        v-loading="Warehouse.loading"
        ref="multipleTableOne"
        @selection-change="select"
        :row-style="{ color: '#303133' }"
        :header-cell-style="{
          backgroundColor: 'rgb(245, 247, 250)',
          color: '#606266',
        }"
      >
        <el-table-column label="药品名称" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.is_total == 0">
              {{ scope.row.drug.drug_name }}
            </span> 
          </template>
        </el-table-column>
        <el-table-column label="药品类型" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.is_total == 0"> {{ getDrugType(scope.row.drug.drug_type) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="规格&单位" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.is_total ==0">{{ scope.row.drug.dose }}&nbsp;{{ scope.row.drug.dose_unit }}*{{
              scope.row.drug.min_number
            }}{{ scope.row.drug.min_unit }}/{{ scope.row.drug.max_unit }}
            </span> 
          </template>
        </el-table-column>
        <el-table-column label="国家编码" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.is_total == 0">
               {{ scope.row.drug.medical_insurance_number }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="批号" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.is_total == 0"> {{ scope.row.batch_number }}</span>
          </template>
        </el-table-column>
        <el-table-column label="仓库名称" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.is_total == 0">
               {{ getHouseName(scope.row.storehouse_id) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="入库数量" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.is_total == 0">
               {{ scope.row.warehousing_count }}{{ scope.row.max_unit }}
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="拆零零售价" align="center">
          <template slot-scope="scope">
            {{scope.row.retail_price}}
          </template>
        </el-table-column> -->
        <el-table-column label="进货价" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.is_total == 0">{{ scope.row.price }}</span> 
          </template>
        </el-table-column>
        <el-table-column label="总价" align="center">
          <template slot-scope="scope">
            <!-- {{scope.row.total_price}} -->
            <span v-if="scope.row.is_total == 0">{{ (scope.row.warehousing_count * scope.row.price).toFixed(2) }}</span> 
            <span v-if="scope.row.is_total == 1">
              {{(scope.row.total_count).toFixed(2)}}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="生产厂家" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.is_total== 0">
               {{ getManufacturer(scope.row.manufacturer) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="生产日期" align="center">
          <template slot-scope="scope">
           <span v-if="scope.row.is_total ==0">{{ getTime(scope.row.product_date) }} </span>  
          </template>
        </el-table-column>
        <el-table-column label="有效日期" align="center">
          <template slot-scope="scope">
           <span v-if="scope.row.is_total == 0">
            {{ getTime(scope.row.expiry_date) }}
            </span> 
          </template>
        </el-table-column>
        <el-table-column label="经销商" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.is_total == 0">
               {{ getDealer(scope.row.dealer) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="批准文号" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.is_total == 0">
               {{ scope.row.number }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center">
          <template slot-scope="scope">
           <span v-if="scope.row.is_total == 0">
             {{ scope.row.remark }}
           </span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog title="药品详细" :visible.sync="dialogVisible" width="60%">
      <span>
        <el-table
          :data="WarehouseInfo.warehouseInfoDate"
          :class="signAndWeighBoxPatients"
          style="width: 100%"
          border
          :header-cell-style="{ backgroundColor: 'rgb(245, 247, 250)' }"
        >
          <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.drug_id != 0">{{
                scope.row.drug.drug_name
              }}</span>
            </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.drug_id != 0">{{
                scope.row.drug ? scope.row.drug.drug_spec : ""
              }}</span>
            </template>
          </el-table-column>

          <el-table-column min-width="23" align="center">
            <template slot="header" slot-scope="scope">
              <span>单价</span>
            </template>
            <template slot-scope="scope">
              <span>{{ scope.row.price }}</span>
            </template>
          </el-table-column>

          <el-table-column min-width="23" align="center">
            <template slot="header" slot-scope="scope">
              <span>入库数量</span>
            </template>
            <template slot-scope="scope">
              <span>{{ scope.row.warehousing_count }}</span>
            </template>
          </el-table-column>

          <el-table-column label="总价" min-width="20" align="center">
            <template slot-scope="scope">
              {{ calculate(scope.row.price * scope.row.warehousing_count) }}
            </template>
          </el-table-column>

          <el-table-column align="center" min-width="25">
            <template slot="header" slot-scope="scope">
              <span>批号</span>
            </template>
            <template slot-scope="scope">
              <span>{{ scope.row.number }}</span>
            </template>
          </el-table-column>
          <el-table-column label="生产日期" min-width="40" align="center">
            <template v-if="scope.row.product_date != 0" slot-scope="scope">
              {{ scope.row.product_date | parseTime("{y}-{m}-{d}") }}
            </template>
          </el-table-column>
          <el-table-column label="有效日期" min-width="40" align="center">
            <template v-if="scope.row.expiry_date != 0" slot-scope="scope">
              {{ scope.row.expiry_date | parseTime("{y}-{m}-{d}") }}
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="20" align="center">
            <template slot-scope="scope">
              <el-popover placement="top-start" width="250" trigger="hover">
                <div>{{ scope.row.remark }}</div>
                <span slot="reference" v-if="scope.row.remark.length > 20">{{
                  scope.row.remark.substr(0, 20) + "..."
                }}</span>
                <span slot="reference" v-else>{{ scope.row.remark }}</span>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { uParseTime } from "@/utils/tools";
import { fetchAllAdminUsers, fetchAllDoctorAndNurse } from "@/api/doctor";
import {
  deleteDrugWarehouseInfo,
  GetAllConfig,
  getDrugWarehouseInfoList,
  getDrugWarehouseList,
  exportDrugList,
} from "@/api/drug/drug_stock";
import { getAllDrugList } from "@/api/data";
import { getDictionaryDataConfig } from "@/utils/data";
import BreadCrumb from "../../components/bread-crumb";

export default {
  name: "drugStockInOrder",
  components: { BreadCrumb },
  created() {
    if (this.$route.path == "/Pharmacy/drugs/stock/in") {
      this.crumbs = [
        { path: false, name: "药品管理" },
        { path: "/stock/drugs/stock/query", name: "入库单·" },
      ];
    }
    this.drugTypeList = getDictionaryDataConfig("system", "drug_type");
    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.GetWarehouse();
    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: "",
      end_time: "",
      selectedTableData: [],
      Warehouse: {
        loading: false,
        warehouseDate: [],
        tableCurrentIndex: "",
      },

      WarehouseInfo: {
        loading: false,
        warehouseInfoDate: [],
      },
      check_id: 0,

      startTime: "",
      dialogVisible: false,
      showOne: false,
      drugTypeList: [],
      manufacturerList: [],
      order_id: "",
      dealerList: [],
      exportList: [],
      houseList: [],
      storehouse_id: 0,
      check_type: 0,
      checkList: [
        { id: 0, name: "全部" },
        { id: 1, name: "已审核" },
        { id: 2, name: "未审核" },
      ],
      exportLoding:false,
    };
  },

  methods: {
    changeTypeName() {
      this.getlist();
    },
    getlist() {
      var params = {
        check_id: this.check_id,
        start_time: this.start_time,
        end_time: this.end_time,
        keyword: this.keywords,
        page: this.page,
        limit: this.limit,
      };
      getAllSecondOrderList(params).then((response) => {
        if (response.data.state == 1) {
          var list = response.data.data.list;
          this.tableList = list;
          var total = response.data.data.total;
          this.total = total;
          this.houseList = response.data.data.houseList;
          this.doctorList = response.data.data.doctorList;
        }
      });
    },
    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,
        storehouse_id: this.storehouse_id,
        check_type: this.check_type,
      };
      this.Warehouse.warehouseDate = [];
      getDrugWarehouseList(Params).then((response) => {
        if (response.data.state == 0) {
          this.Warehouse.loading = false;
          this.$message.error(response.data.msg);
          return false;
        } else {
          this.Warehouse.loading = false;
          this.total = response.data.data.total;
          for (let i = 0; i < response.data.data.list.length; i++) {
            this.Warehouse.warehouseDate.push(response.data.data.list[i]);
          }
        }
      });
    },
    GetWarehouse: 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,
        storehouse_id: this.storehouse_id,
        check_type: this.check_type,
      };
      this.Warehouse.warehouseDate = [];
      getDrugWarehouseList(Params).then((response) => {
        if (response.data.state == 0) {
          this.Warehouse.loading = false;
          this.$message.error(response.data.msg);
          return false;
        } else {
          this.Warehouse.loading = false;
          this.total = response.data.data.total;
          for (let i = 0; i < response.data.data.list.length; i++) {
            this.Warehouse.warehouseDate.push(response.data.data.list[i]);
          }
          var obj = { id: 0, storehouse_name: "全部" };
          this.houseList = [];
          this.houseList.push(obj);
          for (let i = 0; i < response.data.data.houseList.length; i++) {
            this.houseList.push(response.data.data.houseList[i]);
          }
        }
      });
    },
    tableRowClassName({ row, rowIndex }) {
      // 把每一行的索引放进row
      row.index = rowIndex;
    },
    onRowClick(row, event, column) {
      this.WarehouseInfo.warehouseInfoDate = [];
      this.Warehouse.tableCurrentIndex = row.index;
      const params = {
        id: row.id,
      };
      this.WarehouseInfo.loading = true;
      getDrugWarehouseInfoList(params).then((response) => {
        if (response.data.state == 0) {
          this.WarehouseInfo.loading = false;
          this.$message.error(response.data.msg);
          return false;
        } else {
          this.WarehouseInfo.loading = false;
          for (let i = 0; i < response.data.data.info.length; i++) {
            this.WarehouseInfo.warehouseInfoDate.push(
              response.data.data.info[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;
    },
    fetchAllDoctorAndNurse() {
      fetchAllDoctorAndNurse().then((response) => {
        if (response.data.state == 1) {
          this.doctorOptions = response.data.data.doctors;
        }
      });
    },
    fetchAllAdminUsers() {
      fetchAllAdminUsers().then((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]);
            }
          }
        }
      });
    },
    clicks: function () {},
    handleWarehouse: function () {
      if (this.$route.path == "/Pharmacy/drugs/stock/in") {
        this.$router.push({
          path: "/Pharmacy/in/add",
          query: { type: this.type },
        });
      } else {
        this.$router.push({
          path: "/drugstock/in/add",
          query: { type: this.type },
        });
      }
    },
    handleSelectionChange: function (val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.limit = val;
      this.GetWarehouse();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.GetWarehouse();
    },
    startTimeChange(val) {
      var time = this.getTimestamp(val) - this.getTimestamp(this.end_time);
      if (time > 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.start_time = "";
      } else {
        this.startTime = this.getTimestamp(val);
        this.start_time = val;
        this.GetWarehouse();
      }
    },
    endTimeChange(val) {
      var time = this.getTimestamp(val) - this.getTimestamp(this.start_time);
      if (time < 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.end_time = "";
      } else {
        this.end_time = val;
        this.GetWarehouse();
      }
    },
    getTimestamp(time) {
      // 把时间日期转成时间戳
      return new Date(time).getTime() / 1000;
    },
    calculate: function (val) {
      return Math.round(parseFloat(val) * 100) / 100;
    },

    // handleEdit: function(index, row) {
    //   this.$router.push({
    //     name: "drugStockInDetail",
    //     query: { id: row.id, type: this.type }
    //   });

    // },
    handleEdit: function (index, row) {
      this.$router.push({
        name: "drugStockInOrderEdit",
        query: {
          id: row.id,
          type: this.type,
          supply_warehouse_id: row.supply_warehouse_id,
          is_sys: row.is_sys,
          is_check: row.is_check,
        },
      });
    },
    handleSearch(id) {
      this.WarehouseInfo.warehouseInfoDate = [];
      this.GetOrderDetail(id);
      this.dialogVisible = true;
    },
    GetOrderDetail(order_id) {
      const params = {
        id: order_id,
      };

      this.WarehouseInfo.warehouseInfoDate = [];
      getDrugWarehouseInfoList(params).then((response) => {
        if (response.data.state == 0) {
          this.$message.error(response.data.msg);
          return false;
        } else {
          var obj = {total_count:0,is_total:1}
          for (let i = 0; i < response.data.data.info.length; i++) {
            response.data.data.info[i].is_total = 0
            this.showOne = true;
            this.WarehouseInfo.warehouseInfoDate.push(
              response.data.data.info[i]
            );
            obj.total_count += (response.data.data.info[i].warehousing_count *response.data.data.info[i].price)
          }
          this.WarehouseInfo.warehouseInfoDate.push(obj)
        
          this.WarehouseInfo.warehouse = response.data.data.warehousing;
          this.getAllDrugList();
        }
      });
    },
    handleDelete: function (index, row) {
      if (row.is_sys == 13) {
        this.$message.error("调拨入库数据不能删除!");
        return false;
      }
      if (row.supply_warehouse_id > 0) {
        this.$message.error("自动入库数据不能删除!");
        return false;
      }
      if (row.is_check == 1) {
        this.$message.error("已审核的单据不能删除");
        return false;
      }
      const ids = [];
      ids.push(row.id);
      const idStr = ids.join(",");

      const params = {
        ids: idStr,
      };

      this.$confirm("确认删除入库单记录?", "删除入库单记录", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteDrugWarehouseInfo(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.Warehouse.warehouseDate.length; y++) {
                  if (ids[i] == this.Warehouse.warehouseDate[y].id) {
                    this.Warehouse.warehouseDate.splice(y, 1);
                  }
                }
              }
            }
          });
        })
        .catch(() => {});
    },
    changeAllSelected: function (val) {
      if (val) {
        this.$refs.multipleTable.toggleAllSelection();
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    select(selection) {
      var ids = [];
      for (let i = 0; i < selection.length; i++) {
        ids.push(selection[i].id);
      }
      this.order_id = ids.join(",");
      this.selectedTableData = selection;
      this.exportDrugList();
    },
    batchDelete() {
      if (this.selectedTableData.length <= 0) {
        this.$message.error("请选择要删除的记录");
        return;
      }
      const ids = [];
      const idOne = [];
      for (let i = 0; i < this.selectedTableData.length; i++) {
        if (this.selectedTableData[i].is_check == 1) {
          this.$message.error("已审核单据不能删除!");
          return false;
        }
        if (this.selectedTableData[i].is_sys == 13) {
          this.$message.error("调拨入库数据不能删除!");
          return false;
        }
        ids.push(this.selectedTableData[i].id);
        if (this.selectedTableData[i].supply_warehouse_id > 0) {
          idOne.push(this.selectedTableData[i].supply_warehouse_id);
        }
      }

      for (let i = 0; i < idOne.length; i++) {
        if (idOne[i] > 0) {
          this.$message.error("自动入库数据不能删除!");
          return false;
        }
      }
      const idStr = ids.join(",");
      const params = {
        ids: idStr,
      };
      this.$confirm("确认删除入库单记录?", "删除入库单记录", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteDrugWarehouseInfo(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.Warehouse.warehouseDate.length; y++) {
                  if (ids[i] == this.Warehouse.warehouseDate[y].id) {
                    this.Warehouse.warehouseDate.splice(y, 1);
                  }
                }
              }
            }
          });
        })
        .catch(() => {});
    },
    handleCurrentChangeOne(val) {
      this.GetOrderDetail(val.id);
    },
    getTime(val) {
      if (val < 0) {
        return "";
      }
      if (val == "") {
        return "";
      } else {
        return uParseTime(val, "{y}-{m}-{d}");
      }
    },
    getDrugType(id) {
      var name = "";
      for (let i = 0; i < this.drugTypeList.length; i++) {
        if (id == this.drugTypeList[i].id) {
          name = this.drugTypeList[i].name;
        }
      }
      return name;
    },
    getAllDrugList() {
      getAllDrugList().then((response) => {
        if (response.data.state == 1) {
          var manufacturerList = response.data.data.manufacturerList;
          this.manufacturerList = manufacturerList;
          this.dealerList = response.data.data.dealerList;
        }
      });
    },
    getManufacturer(id) {
      var name = "";
      for (let i = 0; i < this.manufacturerList.length; i++) {
        if (id == this.manufacturerList[i].id) {
          name = this.manufacturerList[i].manufacturer_name;
        }
      }
      return name;
    },
    getDealer(id) {
      var name = "";
      for (let i = 0; i < this.dealerList.length; i++) {
        if (id == this.dealerList[i].id) {
          name = this.dealerList[i].dealer_name;
        }
      }
      return name;
    },
    getDictionaryDataConfig(module, filed_name) {
      return getDictionaryDataConfig(module, filed_name);
    },
    drugPrint() {
      if (this.order_id == "") {
        this.$message.error("请选择入库单");
      } else {
        this.$router.push({
          path: "/stock/drugStockInOrderDetailPrint?id=" + this.order_id,
        });
      }
    },
    exportDrugList() {
      var params = {
        order_id: this.order_id,
      };
      this.exportLoding = true
      exportDrugList(params).then((response) => {
        if (response.data.state == 1) {
          var list = response.data.data.list;

          for (let i = 0; i < list.length; i++) {
            list[i].product_date = this.getTime(list[i].product_date);
            list[i].expiry_date = this.getTime(list[i].expiry_date);
          }
          this.exportList = list;
          this.exportLoding = false
          var manufacturerList = response.data.data.manufacturerList;
          this.manufacturerList = manufacturerList;
          var dealerList = response.data.data.dealerList;

          this.dealerList = dealerList;
        }
      });
    },

    lili(){
      console.log("exportList",this.exportList)
    },
    toExport() {
      if (this.order_id == "") {
        this.$message.error("请勾选入库单");
      }
      for (let i = 0; i < this.exportList.length; i++) {
        this.exportList[i].index = i + 1;
        this.exportList[i].unit =
          this.exportList[i].dose +
          this.exportList[i].dose_unit +
          "*" +
          this.exportList[i].min_number +
          this.exportList[i].min_unit +
          "/" +
          this.exportList[i].max_unit;

        this.exportList[i].total_price = (
          this.exportList[i].warehousing_count * this.exportList[i].price
        ).toFixed(2);
        for (let j = 0; j < this.manufacturerList.length; j++) {
          if (this.exportList[i].manufacturer == this.manufacturerList[j].id) {
            this.exportList[i].manufacturer =
              this.manufacturerList[j].manufacturer_name;
          }
          if (this.exportList[i].manufacturer == 0) {
            this.exportList[i].manufacturer = "";
          }
        }

        for (let z = 0; z < this.dealerList.length; z++) {
          if (this.exportList[i].dealer == this.dealerList[z].id) {
            this.exportList[i].dealer = this.dealerList[z].dealer_name;
          }
          if (this.exportList[i].dealer == 0) {
            this.exportList[i].dealer = "";
          }
        }
      }

      import("@/vendor/Export2Excel").then((excel) => {
        for (let i = 0; i < this.exportList.length; i++) {
          for (let j = 0; j < this.drugTypeList.length; j++) {
            if (this.exportList[i].drug_type == this.drugTypeList[j].id) {
              this.exportList[i].drug_type = this.drugTypeList[j].name;
            }
          }
        }

        const tHeader = [
          "序号",
          "药品名称",
          "药品类型",
          "规格&单位",
          "批号",
          "入库数量",
          "进货价",
          "总价",
          "生产厂家",
          "生产日期",
          "有效日期",
          "经销商",
          "批注文号",
          "备注",
        ];
        const filterVal = [
          "index",
          "drug_name",
          "drug_type",
          "unit",
          "batch_number",
          "warehousing_count",
          "price",
          "total_price",
          "manufacturer",
          "product_date",
          "expiry_date",
          "dealer",
          "number",
          "remark",
        ];

        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]));
    },
    getHouseName(id) {
      var storehouse_name = "";
      for (let i = 0; i < this.houseList.length; i++) {
        if (id == this.houseList[i].id) {
          storehouse_name = this.houseList[i].storehouse_name;
        }
      }
      return storehouse_name;
    },
    changeStoreHouse() {
      this.GetWarehouse();
    },
    changeCheckType() {
      this.GetWarehouse();
    },
  },
};
</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>
