<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <div class="query-box">
        <div class="query-box__left">
          <el-form-item label="" prop="code">
            <el-input v-model="queryParams.code" placeholder="请输入单据号" clearable size="small" @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <!-- <el-form-item label="" prop="keepingTime">
            <el-date-picker clearable size="small" v-model="queryParams.keepingTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择出库时间"></el-date-picker>
          </el-form-item> -->
          <el-form-item label="" prop="keepingTime">
            <el-date-picker clearable size="small" style="width:260px" v-model="queryParams.keepingTime" type="daterange" value-format="yyyy-MM-dd" start-placeholder="出库开始时间" end-placeholder="出库结束时间"></el-date-picker>
          </el-form-item>
          <el-form-item label="" prop="warehouseType">
            <el-select v-model="queryParams.warehouseType" placeholder="请选择出库方式" clearable size="small">
              <el-option v-for="item in storageArr" :key="item.id" :value="item.id" :label="item.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="state">
            <el-select v-model="queryParams.state" placeholder="请选择单据状态" clearable size="small">
              <el-option v-for="item in billOptions" :key="item.dictValue" :value="item.dictValue" :label="item.dictLabel"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['inventory:warehouse:add']">新增</el-button>
          </el-form-item>
        </div>
      </div>
    </el-form>

    <el-table v-loading="loading" :data="warehouseList" @selection-change="handleSelectionChange" border size="mini">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" width="55" align="center" label="序号" />
      <el-table-column label="出库单号" align="center" prop="code" />
      <el-table-column label="出库方式" align="center" prop="typeName">
        <!-- <template slot-scope="scope">
          <dict-tag :options="storageArr" :value="scope.row.warehouseType" />
        </template> -->
      </el-table-column>
      <el-table-column label="单位部门" align="center" prop="supplierName"></el-table-column>
      <el-table-column label="制单人" align="center" prop="createBy" />
      <el-table-column label="制单时间" align="center" prop="createTime"/>
      <el-table-column label="记账人" align="center" prop="keepingBy" />
      <el-table-column label="记账时间" align="center" prop="keepingTime">
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="billOptions" :value="scope.row.state"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            style="width: 40px"
            @click="handleUpdate(1, scope.row)"
            v-hasPermi="['inventory:warehouse:edit']"
            v-if="scope.row.state === '1'"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="primary"
            style="width: 40px"
            v-hasPermi="['inventory:warehouse:remove']"
            @click="handleUpdate(2, scope.row)"
            v-if="scope.row.state === '1'"
            >记账</el-button
          >
          <el-button
            size="mini"
            type="primary"
            style="width: 40px"
            @click="handleDelete(scope.row)"
            v-hasPermi="['inventory:warehouse:remove']"
            v-if="scope.row.state === '1'"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="primary"
            style="width: 40px"
            v-hasPermi="['inventory:warehouse:remove']"
            @click="handleUpdate(3, scope.row)"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="primary"
            style="width: 40px"
            v-hasPermi="['inventory:warehouse:remove']"
            @click="handleUpdate(4, scope.row)"
            v-if="scope.row.state === '2'"
            >冲销</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改出库单对话框 -->
    <el-dialog
      :fullscreen="true"
      :title="title"
      :visible.sync="open"
      width="1180px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-position="top">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="出库单号" prop="code">
              <el-input
                v-model="form.code"
                placeholder="请输入单号"
                disabled
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item
              label="出库方式"
              prop="warehouseType"
              :rules="[{ required: true, message: '请选择出库方式' }]"
            >
              <el-select
                v-model="form.warehouseType"
                placeholder="请选择出库方式"
                :disabled="disableDetails"
                style="width: 100%"
                @change="handleRk"
              >
                <el-option
                  v-for="item in storageArr"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item
              label="单位部门"
              prop="supplierId"
              :rules="[{ required: true, message: '请选择单位部门' }]"
            >
              <el-select
                v-if="editable||disableDetails"
                v-model="form.supplierName"
                placeholder="请选择单位部门"
                :disabled="!editable||disableDetails"
                style="width: 100%"
              >
                <el-option
                  v-for="item in supplierArr"
                  :key="item.id"
                  :value="item.id+''"
                  :label="item.name"
                />
              </el-select>
              <el-select
                v-else
                v-model="form.supplierId"
                placeholder="请选择单位部门"
                style="width: 100%"
                value-key="id"
              >
                <el-option
                  v-for="item in supplierArr"
                  :key="item.id"
                  :value="item"
                  :label="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-model="form.remarks"
                placeholder="请输入备注"
                :disabled="disableDetails"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="制单人" prop="createBy">
              <el-input v-if="form.createBy" v-model="form.createBy" disabled style="width: 100%"></el-input>
              <el-input v-else :value="createBy" disabled style="width: 100%"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="制单时间" prop="createTime">
              <el-input v-if="form.createTime" v-model="form.createTime" disabled style="width: 100%"></el-input>
              <el-input v-else v-model="createTime" disabled style="width: 100%"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="记账人" prop="keepingBy">
              <el-input v-if="form.keepingBy" v-model="form.keepingBy" disabled style="width: 100%"></el-input>
              <template v-else>
                <el-input v-if="BtnState==2" :value="createBy" disabled style="width: 100%"></el-input>
                <el-input v-else value="" disabled style="width: 100%"></el-input>
              </template>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="记账时间" prop="keepingTime">
              <el-input v-if="form.keepingTime" v-model="form.keepingTime" disabled style="width: 100%"></el-input>
              <template v-else>
                <el-input v-if="BtnState==2" :value="createTime" disabled style="width: 100%"></el-input>
                <el-input v-else value="" disabled style="width: 100%"></el-input>
              </template>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="center">出库单详情信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAddWarehouseDetail"
              v-if="!disableDetails"
              >添加</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDeleteWarehouseDetail"
              v-if="!disableDetails"
              >删除</el-button
            >
          </el-col>
        </el-row>
        <el-table
          :data="warehouseDetails"
          :row-class-name="rowWarehouseDetailIndex"
          @selection-change="handleWarehouseDetailSelectionChange"
          ref="warehouseDetail"
          border
          :summary-method="getSummaries"
          show-summary
        >
          <el-table-column type="selection" width="80" align="center" />
          <el-table-column
            label="序号"
            align="center"
            prop="index"
            width="65"
          />
          <el-table-column
            label="药品名称"
            prop="drugsName"
            width="110"
            align="center"
          >
            <template slot-scope="scope">
              <selectOutTable v-if="open" type="deal" :toBank="true" :info="scope.row" :pharmacyId="form.pharmacyId" :index="scope.$index" :disableDetails="disableDetails" @selectChange="selectChange"></selectOutTable>
            </template>
          </el-table-column>
          <el-table-column
            label="药品类型"
            prop="specsName"
            width="110"
            align="center"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.drugsType">{{drugsTypeOptions.find(v=>v.dictValue==scope.row.drugsType)&&drugsTypeOptions.find(v=>v.dictValue==scope.row.drugsType).dictLabel}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="药品规格"
            prop="specsName"
            width="110"
            align="center"
          ></el-table-column>
          <el-table-column
            label="药品产地"
            prop="priceName"
            width="110"
            align="center"
          ></el-table-column>

          <el-table-column
            label="生产批号"
            prop="productionCode"
            align="center"
            width="180"
          ></el-table-column>

          <el-table-column
            label="药品单位"
            prop="packingUnit"
            width="110"
            align="center"
          >
            <template slot-scope="scope">
              <dict-tag v-if="scope.row.packingUnit" :options="unitArr" :value="scope.row.packingUnit" />
            </template>
          </el-table-column>

          <el-table-column
            label="库存数量"
            prop="stock"
            align="center"
            width="110"
          ></el-table-column>
          <el-table-column
            label="出库数量"
            prop="warehouseNum"
            align="cneter"
            width="110"
          >
            <template slot-scope="scope">
              <el-input-number
                style="width:100%"
                size="mini"
                v-model.number="scope.row.warehouseNum"
                placeholder="出库数量"
                controls-position="right"
                :disabled="disableDetails"
                type="number"
                :min="1"
              />
            </template>
          </el-table-column>
          <el-table-column label="进货单价" prop="purchasePrice" align="center" width="110"></el-table-column>
          <el-table-column label="进货总价" prop="purchasePrice" align="center" width="110">
            <template slot-scope="scope">
              <div>{{ (scope.row.purchasePrice * scope.row.warehouseNum).toFixed(4) }}</div>
            </template>
          </el-table-column>
          <el-table-column label="零售单价" prop="retailPrice" width="110" align="center"></el-table-column>
          <el-table-column label="零售总价" prop="retailPrice" width="110" align="center">
            <template slot-scope="scope">
              <div>
                {{ (scope.row.retailPrice * scope.row.warehouseNum).toFixed(4) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="药品效期" prop="validTime" width="155" align="center"></el-table-column>
          <el-table-column label="批准文号" prop="approvalCode" align="center" width="110"></el-table-column>
          <el-table-column label="摆放位置" prop="site" width="110" align="center"></el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="BtnState === 1"
          >确 定</el-button
        >
        <el-button @click="cancel" v-if="BtnState === 1">取 消</el-button>

        <el-button @click="handleUpdataKeeping" v-if="BtnState === 2"
          >记 账</el-button
        >
        <el-button @click="handleOff" v-if="BtnState === 4">冲销</el-button>
      </div>
    </el-dialog>

    
  </div>
</template>

<script>
import {
  listWarehouse,
  getWarehouse,
  delWarehouse,
  addWarehouse,
  updateWarehouse,
  exportWarehouse,
  updataKeeping,
  undataWriteOff,
  listCk,
} from "@/api/inventory/warehouse";
import { listStorage } from "@/api/pharmacy/storage";
import { listSupplier } from "@/api/pharmacy/supplier";
// import { listDrugs } from "@/api/drugs/drugs";
// import { listSpecs } from "@/api/drugs/specs";
// import { listPrice } from "@/api/drugs/price";
import { oneList } from "@/api/inventory/inventory";
import { listMedicalPharmacy } from "@/api/pharmacy/MedicalPharmacy";
import selectOutTable from '@/components/selectTable/selectOutTable.vue'
export default {
  components: {
    selectOutTable
  },
  name: "Warehouse",
  data() {
    return {
      curIndex: 0,
      pvisible: false,
      currentRow: '',
      prows: [],
      storageArr: [],
      billOptions: [],
      supplierArr: [],
      drugsArr: [],
      specsArr: [],
      priceArr: [],
      productionCodeArr: [],
      drugsId: "",
      specsId: "",
      priceId: "",
      productionCode: "",
      drugsTypeOptions: [],
      unitOptions: [],
      disableDetails: false,
      editable: false,
      BtnState: "",
      tableId: "",
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedWarehouseDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出库单表格数据
      warehouseList: [],
      // 出库单详情表格数据
      warehouseDetails: [
        {
          drugsId: "",
          specsId: "",
          riceId: "",
          stock: "",
          warehouseNum: "",
          priceId: "",
          purchasePrice: "",
          retailPrice: "",
          approvalCode: "",
          site: "",
          productionCode: "",
          validTime: "",
          specsArr: [],
          priceArr: [],
          productionCodeArr: [],
        },
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        keepingTime: [],
        pharmacyId: window.localStorage.getItem("pharmacyId"),
        warehouseType: null,
      },
      // 表单参数
      form: {
        // keepingBy: window.localStorage.getItem("userName"),
        createBy: null,
        pharmacyId: window.localStorage.getItem("pharmacyId"),
      },

      // 表单校验
      rules: {
        pharmacyId: [
          { required: true, message: "药房id不能为空", trigger: "blur" },
        ],
      },
      deptTypeOptions: [
        { dictLabel: "药房", dictValue: "1" },
        { dictLabel: "供货单位", dictValue: "2" },
      ],
      unitArr: [],
      createBy: '',
      createTime: ''
    };
  },
  created() {
    this.createBy = localStorage.getItem('userName')
    this.createTime = this.dayjs().format("YYYY-MM-DD HH:mm:ss")
    this.getDicts("unit").then((response) => {
      this.unitArr = response.data;
    });
    this.getDicts("bill_state").then((response) => {
      this.billOptions = response.data;
    });
    this.getDicts("drugs_type").then((response) => {
      this.drugsTypeOptions = response.data;
    });
    this.getDicts("unit").then((response) => {
      this.unitOptions = response.data;
    });
    this.getList();
    this.getListStorage();
    // this.getListSupplier();
    //this.getListDrugs();
  },
  methods: {
    selectChange (data) {
      var index = data.index
      this.curIndex = index
      var r = data.data
      this.warehouseDetails[index].drugsId = r.drugsId;
      this.warehouseDetails[index].drugsType = String(r.drugsType);
      this.warehouseDetails[index].specsId = r.specsId;
      this.warehouseDetails[index].priceId = r.priceId;
      this.warehouseDetails[index].packingUnit = r.packingUnit;
      this.warehouseDetails[index].specsName = r.specsName;
      this.warehouseDetails[index].inventoryId = r.inventoryId;
      this.warehouseDetails[index].drugsName = r.drugsName;
      this.warehouseDetails[index].priceName = r.priceName;
      this.warehouseDetails[index].retailPrice = r.retailPrice;
      this.warehouseDetails[index].approvalCode = r.approvalCode;
      this.warehouseDetails[index].site = r.site;
      this.warehouseDetails[index].packingUnit = r.packingUnit;
      this.warehouseDetails[index].drugsType = r.drugsType;
      this.warehouseDetails[index].validTime = r.validTime;
      this.$set(this.warehouseDetails[index], "specsArr", data.result);
      this.warehouseDetails[index].productionCode = r.productionCode;
      this.warehouseDetails[index].purchasePrice = r.purchasePrice;
      this.warehouseDetails[index].stock = r.stock;
    },
    /** 表单合计 **/
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总价";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (index === 8 || index === 9 || index === 10 || index === 12) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] = sums[index].toFixed(4);
        } else {
          sums[index] = "/";
        }

        if (index === 11) {
          let num = [];
          data.map((item) => {
            num.push(item.warehouseNum * item.purchasePrice);
          });
          let sum = num.reduce(function (prev, cur, index, array) {
            return prev + cur;
          });
          sums[11] = (sum-0).toFixed(4)
        }

        if (index === 13) {
          let num = [];
          data.map((item) => {
            num.push(item.warehouseNum * item.retailPrice);
          });
          let sum = num.reduce(function (prev, cur, index, array) {
            return prev + cur;
          });
          sums[13] = (sum-0).toFixed(4)
        }
      });
      return sums;
    },

    /** 查询出库单列表 */
    getList() {
      this.loading = true;
      var form = Object.assign({}, this.queryParams)
      if (form.keepingTime && form.keepingTime.length) {
        form.startTime = form.keepingTime[0]
        form.endTime = form.keepingTime[1]
      } else {
        form.startTime = form.endTime = ''
      }
      delete form.keepingTime
      listWarehouse(form).then((response) => {
        this.warehouseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //获取出库方式
    getListStorage() {
      listCk({
        display: 'Y'
      }).then((res) => {
        this.storageArr = res.rows;
      });
    },
    //选择入库单位
    handleRk(e) {
      let newArr = this.storageArr.filter((item) => {
        return item.id === e;
      });
      if (newArr[0].deptType === "1") {
        this.getListMedicalPharmacy();
      } else {
        this.getListSupplier();
      }
    },
    //获取药房
    getListMedicalPharmacy() {
      listMedicalPharmacy({
        state: 1
      }).then((res) => {
        this.supplierArr = res.data;
      });
    },
    //获取单位部门
    getListSupplier() {
      listSupplier().then((res) => {
        this.supplierArr = res.rows;
      });
    },
    /** 记账 **/
    handleUpdataKeeping() {
      updataKeeping(this.tableId).then((res) => {
        this.msgSuccess("记账成功");
        this.open = false;
        this.getList();
      });
    },
    /**冲销**/
    handleOff() {
      undataWriteOff(this.tableId).then((res) => {
        this.msgSuccess("冲销成功");
        this.open = false;
        this.getList();
      });
    },
    //获取药品名称
    getListDrugs() {
      oneList({ pharmacyId: window.localStorage.getItem("pharmacyId") }).then(
        (res) => {
          this.drugsArr = res.data;
        }
      );
    },
    //通过药品名称获取药品类型
    /*handleDrugsId(e, row) {
      let newArr = this.drugsArr.filter((item) => {
        return item.drugsId === e;
      });
      this.getListSpecs(e, row.$index);
      this.drugsId = e;
      this.warehouseDetails[row.$index].drugsType = String(newArr[0].drugsType);

      this.warehouseDetails[row.$index].specsId = "";
      this.warehouseDetails[row.$index].priceId = "";
      this.warehouseDetails[row.$index].purchasePrice = "";
      this.warehouseDetails[row.$index].retailPrice = "";
      this.warehouseDetails[row.$index].approvalCode = "";
      this.warehouseDetails[row.$index].packingUnit = "";
    },
    //获取药品规格
    getListSpecs(drugsName, index) {
      let pharmacyId = window.localStorage.getItem("pharmacyId");
      oneList({ drugsName, pharmacyId }).then((res) => {
        if (res.code === 200) {
          this.$set(this.warehouseDetails[index], "specsArr", res.data);
        }
      });
    },*/

    //通过药品规格获取
    handleSpecsId(e, row) {
      let newArr = this.warehouseDetails[row.$index].specsArr.filter((item) => {
        return item.specsId === e;
      });
      this.specsId = e;
      this.warehouseDetails[row.$index].packingUnit = String(
        newArr[0].packingUnit
      );
      this.getListPrice(e, row.$index);

      this.warehouseDetails[row.$index].priceId = "";
      this.warehouseDetails[row.$index].purchasePrice = "";
      this.warehouseDetails[row.$index].retailPrice = "";
      this.warehouseDetails[row.$index].approvalCode = "";
    },
    //获取产地
    getListPrice(specsId, index) {
      let pharmacyId = window.localStorage.getItem("pharmacyId");
      oneList({ specsId, pharmacyId, drugsId: this.drugsId }).then((res) => {
        // this.priceArr = res.rows;
        this.$set(this.warehouseDetails[index], "productionCodeArr", res.data);
        this.$set(this.warehouseDetails[index], "priceArr", res.data);
      });
    },
    //通过药品产地获取
    handlePriceId(e, row) {
      let newArr = this.warehouseDetails[row.$index].priceArr.filter((item) => {
        return item.priceId === e;
      });
      this.priceId = e;
      // this.$set(this.warehouseDetails[row.$index], "priceId", e);
    },
    //获取生产批号
    handleCode(e, row) {
      let newArr = this.warehouseDetails[row.$index].productionCodeArr.filter(
        (item) => {
          return item.productionCode === e;
        }
      );

      this.warehouseDetails[row.$index].site = newArr[0].site;
      this.productionCode = newArr[0].productionCode;
      this.warehouseDetails[row.$index].validTime = newArr[0].validTime;
      this.warehouseDetails[row.$index].approvalCode = newArr[0].approvalCode;
      this.warehouseDetails[row.$index].retailPrice = newArr[0].retailPrice;
      this.warehouseDetails[row.$index].purchasePrice = newArr[0].purchasePrice;
      if (
        window.localStorage.getItem("pharmacyId") &&
        newArr[0].productionCode &&
        this.drugsId &&
        this.specsId &&
        this.priceId
      ) {
        this.getOneList(row.$index);
      }
    },
    //获取库存数量
    getOneList(index) {
      let params = {
        pharmacyId: window.localStorage.getItem("pharmacyId"),
        drugsId: this.drugsId,
        specsId: this.specsId,
        priceId: this.priceId,
        productionCode: this.productionCode,
      };
      oneList(params).then((res) => {
        res.data.length <= 0
          ? this.$set(this.warehouseDetails[index], "warehouseNum", "0")
          : this.$set(
              this.warehouseDetails[index],
              "warehouseNum",
              res.data[0].stock
            );
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        pharmacyId: window.localStorage.getItem("pharmacyId"),
        warehouseType: null,
        remarks: null,
        createTime: null,
        // keepingBy: window.localStorage.getItem("userName"),
        createBy: null,
        keepingTime: null,
        state: null,
        del: null,
      };
      this.warehouseDetails = [
        {
          drugsId: "",
          specsId: "",
          riceId: "",
          priceId: "",
          stock: "",
          warehouseNum: "",
          purchasePrice: "",
          retailPrice: "",
          approvalCode: "",
          site: "",
          productionCode: "",
          validTime: "",
          specsArr: [],
          priceArr: [],
          productionCodeArr: [],
        },
      ];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // this.form.code = new Date().getTime();
      this.form.code = this.dayjs().format("YYYYMMDDHHmmssSSS");
      // this.form.createTime = new Date();
      // this.form.keepingTime = new Date();
      this.open = true;
      
      this.title = "添加出库单";
      this.BtnState = 1;
      this.disableDetails = false;
    },
    /** 修改按钮操作 */
    handleUpdate(num, row) {
      this.BtnState = num;
      this.reset();
      const id = row.id || this.ids;
      this.tableId = id;
      getWarehouse(id).then((response) => {
        response.data.warehouseDetails.map((item) => {
          item.drugsType = String(item.drugsType);
          item.packingUnit = String(item.packingUnit);
        });
        this.form = response.data;
        this.form.supplierId += ''
        this.warehouseDetails = response.data.warehouseDetails;
        // this.warehouseDetails &&
        //   this.warehouseDetails.forEach((item, index) => {
        //     this.getListSpecs(item.drugsName, index);
        //     this.getListPrice(item.specsId, index);
        //   });
        this.handleRk(response.data.warehouseType);
        this.open = true;
        num == 3
          ? (this.title = "详情出库单")
          : num == 1
          ? (this.title = "修改出库单")
          : num == 4
          ? (this.title = "冲销出库单")
          : num == 2
          ? (this.title = "记账出库单")
          : "";
        if (num === 2) {
          // this.form.keepingTime = new Date();
          this.keepingBy = window.localStorage.getItem("userName");
        }
      });
      if (num === 1) {
        this.disableDetails = false;
        this.editable = true
      } else if (num === 2 || num === 3 || num === 4) {
        this.disableDetails = true;
        this.editable = false
      }
    },
    formatTime(date, fmt) {
      var date = new Date(date);
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      }
      var o = {
        "M+": date.getMonth() + 1,
        "d+": date.getDate(),
        "h+": date.getHours(),
        "m+": date.getMinutes(),
        "s+": date.getSeconds(),
      };
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
          var str = o[k] + "";
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length === 1 ? str : ("00" + str).substr(str.length)
          );
        }
      }
      return fmt;
    },
    /** 提交按钮 */
    submitForm() {
      var flag = true
      for (var i = 0; i < this.warehouseDetails.length; i++) {
        for (var j = i+1; j < this.warehouseDetails.length; j++) {
          if (this.warehouseDetails[i].drugsId == this.warehouseDetails[j].drugsId && this.warehouseDetails[i].specsId == this.warehouseDetails[j].specsId && this.warehouseDetails[i].productionCode == this.warehouseDetails[j].productionCode) {
            flag = false
            break
          }
        }
      }
      if (!flag) {
        return this.$message.warning('存在相同药品，请检查')
      }
      if (this.warehouseDetails.find(v => !v.warehouseNum)) {
        return this.$message.warning('请完善出库数量')
      }
      if (this.warehouseDetails.find(v => v.warehouseNum > v.stock)) {
        return this.$message.warning('出库数量不可大于库存数量，请确认')
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.warehouseDetails = this.warehouseDetails;
          var form = Object.assign({}, this.form)
          if (!this.editable) {
            form.supplierId = this.form.supplierId.id
            form.supplierName = this.form.supplierId.name
          } else {
            if (this.supplierArr.find(v => v.id == form.supplierId)) {
              form.supplierId = this.supplierArr.find(v => v.name == form.supplierName).id
            }
          }
          if (form.id != null) {
            updateWarehouse(form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWarehouse(form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("确定需要删除选中数据吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delWarehouse(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 出库单详情序号 */
    rowWarehouseDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 出库单详情添加按钮操作 */
    handleAddWarehouseDetail() {
      let obj = {};
      obj.drugsId = "";
      obj.specsId = "";
      obj.priceId = "";
      obj.stock = "";
      obj.warehouseNum = "";
      obj.purchasePrice = "";
      obj.retailPrice = "";
      obj.approvalCode = "";
      obj.site = "";
      obj.productionCode = "";
      obj.validTime = "";
      this.warehouseDetails.push(obj);
    },
    /** 出库单详情删除按钮操作 */
    handleDeleteWarehouseDetail() {
      if (this.checkedWarehouseDetail.length == 0) {
        this.msgError("请先选择要删除的出库单详情数据");
      } else {
        const warehouseDetails = this.warehouseDetails;
        const checkedWarehouseDetail = this.checkedWarehouseDetail;
        this.warehouseDetails = warehouseDetails.filter(function (item) {
          return checkedWarehouseDetail.indexOf(item.index) == -1;
        });
      }
    },
    /** 复选框选中数据 */
    handleWarehouseDetailSelectionChange(selection) {
      this.checkedWarehouseDetail = selection.map((item) => item.index);
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有出库单数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportWarehouse(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>
<style scoped>
/* .el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 190px;
} */
.el-input--small .el-input__inner {
  height: 36px;
  line-height: 36px;
}
input[type="number"] {
  -moz-appearance: textfield;
}
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
</style>
