<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" style="width:160px" @keyup.enter.native="handleQuery"></el-input>
          </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="warehousingType">
            <el-select style="width:160px" v-model="queryParams.warehousingType" 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 style="width:160px" 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" size="mini" border>
      <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.warehousingType" />
        </template> -->
      </el-table-column>
      <el-table-column label="单位部门" align="center" prop="supplierName"/>
      <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 label="单据状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="billOptions" :value="scope.row.state" />
        </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 !== '2'"
            >删除</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
      size="mini"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        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="warehousingType"
              :rules="[{ required: true, message: '请选择入库方式' }]"
            >
              <el-select
                v-model="form.warehousingType"
                placeholder="请选择入库方式"
                :disabled="disableDetails"
                style="width: 100%"
              >
                <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="warehousingDetails"
          :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">
              <!-- <el-input
                v-model="scope.row.drugsId"
                placeholder="请输入药品名称"
              /> -->
              <selectTable v-if="open" :info="scope.row" :index="scope.$index" :disableDetails="disableDetails" @selectChange="selectChange" :disabled="num==4||num==2"></selectTable>
            </template>
          </el-table-column>
          <el-table-column
            label="药品类型"
            prop="drugsType"
            width="110"
            align="center"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.drugsType">{{drugsTypeOptions.find(v=>v.dictValue==scope.row.drugsType).dictLabel}}</span>
              <!-- <el-input
                disabled
                v-model="scope.row.drugsType"
                placeholder="药品类型"
              /> -->
              <!-- <el-select
                v-model="scope.row.drugsType"
                placeholder="药品类型"
                disabled
              >
                <el-option
                  v-for="item in drugsTypeOptions"
                  :key="item.dictValue"
                  :value="item.dictValue"
                  :label="item.dictLabel"
                ></el-option>
              </el-select> -->
            </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"
          >
            <template slot-scope="scope">
              <span>{{scope.row.placeName}}</span>
              <!-- <el-input
                v-model="scope.row.priceId"
                placeholder="请输入药品产地"
              /> -->
              <!-- <el-select
                v-model="scope.row.priceId"
                placeholder="药品产地"
                @change="handlePriceId($event, scope)"
                :disabled="disableDetails"
              >
                <el-option
                  v-for="item in scope.row.priceArr"
                  :key="item.id"
                  :value="item.id"
                  :label="item.placeName"
                  :disabled="item.state == 1 || item.del == 0 ? false : true"
                />
              </el-select> -->
            </template>
          </el-table-column>

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

          <el-table-column
            label="库存数量"
            prop="inventory"
            align="center"
            width="110"
          >
            <!-- <template slot-scope="scope">
              <el-input
                v-model="scope.row.inventory"
                placeholder="库存"
                disabled
              />
            </template> -->
          </el-table-column>
          <el-table-column
            label="入库数量"
            prop="stock"
            align="cneter"
            width="110"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.stock"
                placeholder="入库数量"
                :disabled="disableDetails"
                type="number"
                :min="1"
                onkeypress="return (/^[-]?[0-9]*\.?[0-9]+(eE?[0-9]+)?$/.test(String.fromCharCode(event.keyCode)))"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="进货单价"
            prop="purchasePrice"
            align="center"
            width="110"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.purchasePrice"
                placeholder="进货单价"
                :disabled="num==4||num==2"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="进货总价"
            prop="purchasePriceAll"
            align="center"
            width="110"
          >
            <template slot-scope="scope">
              <!-- <el-input
                :v-model="scope.row.purchasePrice*scope.row.inventory"
                placeholder="请输入进货总价"
              /> -->
              <div>{{ (scope.row.purchasePrice * scope.row.stock).toFixed(4) }}</div>
            </template>
          </el-table-column>
          <el-table-column
            label="零售单价"
            prop="retailPrice"
            width="110"
            align="center"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.retailPrice"
                placeholder="零售单价"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column
            label="零售总价"
            prop="retailPrice"
            width="110"
            align="center"
          >
            <template slot-scope="scope">
              <!-- <el-input
                v-model="scope.row.retailPrice"
                placeholder="请输入零售总价"
              /> -->
              <div disabled>
                {{ (scope.row.retailPrice * scope.row.stock).toFixed(4) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="生产批号"
            prop="productionCode"
            align="center"
            width="110"
          >
            <template slot-scope="scope">
              <span v-if="disableDetails">{{scope.row.productionCode}}</span>
              <el-input
                v-model="scope.row.productionCode"
                placeholder="生产批号"
                v-else
              />
            </template>
          </el-table-column>
          <el-table-column label="药品效期" prop="validTime" width="155" align="center">
            <template slot-scope="scope">
              <el-date-picker
                :disabled="disableDetails"
                clearable
                size="small"
                v-model="scope.row.validTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="有效时间"
                style="width: 130px">
              </el-date-picker>
            </template>
          </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 type="primary" @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 {
  listWarehousing,
  getWarehousing,
  delWarehousing,
  addWarehousing,
  updateWarehousing,
  exportWarehousing,
  updataKeeping,
  undataWriteOff,
  listRk,
  getProductionCode
} from "@/api/inventory/warehousing";
import { listSupplier } from "@/api/pharmacy/supplier";
import { listSpecs } from "@/api/drugs/specs";
import { listDrugs } from "@/api/drugs/drugs";
import { listPrice } from "@/api/drugs/price";
import { getSumStock } from "@/api/inventory/inventory";
import { listMedicalPharmacy } from "@/api/pharmacy/MedicalPharmacy";
import selectTable from '@/components/selectTable/selectTable.vue'
export default {
  name: "Warehouse",
  components: {
    selectTable
  },
  data() {
    return {
      num: '',
      createBy: '',
      createTime: '',
      storageArr: [],
      billOptions: [],
      supplierArr: [],
      drugsArr: [],
      specsArr: [],
      priceArr: [],
      drugsId: "",
      specsId: "",
      priceId: "",
      productionCode: "",
      drugsTypeOptions: [],
      unitOptions: [],
      disableDetails: false,
      tableId: "",
      BtnState: "",
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      editable: false,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedWarehouseDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库单表格数据
      warehouseList: [],
      // 入库单详情表格数据
      warehousingDetails: [
        {
          drugsId: "",
          specsId: "",
          riceId: "",
          stock: "",
          inventory: "",
          purchasePrice: "",
          purchasePriceAll: "",
          retailPrice: "",
          approvalCode: "",
          site: "",
          productionCode: "",
          validTime: "",
          specsArr: [],
          priceArr: [],
        },
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        keepingTime: [],
        pharmacyId: window.localStorage.getItem("pharmacyId"),
      },
      // 表单参数
      form: {
        keepingBy: null,
        createBy: null,
        supplierId: '',
        pharmacyId: window.localStorage.getItem("pharmacyId"),
      },
      // 表单校验
      rules: {
        pharmacyId: [
          { required: true, message: "药房id不能为空", trigger: "blur" },
        ],
      },
      supplierArrTab: [],
      unitArr: []
    };
  },
  watch: {
    'form.warehousingType' (val) {
      if (val != null) {
        this.handleRk()
      }
    }
  },
  created() {
    this.getDicts("unit").then((response) => {
      this.unitArr = response.data;
    });
    this.createBy = localStorage.getItem('userName')
    this.createTime = this.dayjs().format("YYYY-MM-DD HH:mm:ss")
    this.getDicts("bill_state").then((response) => {
      this.billOptions = response.data;
    });
    this.getDicts("drugs_type").then((response) => {
      // response.data.map((item) => {
      //   this.drugsTypeOptions[item.dictValue] = item.dictLabel;
      // });
      this.drugsTypeOptions = response.data;
    });
    this.getDicts("unit").then((response) => {
      this.unitOptions = response.data;
    });
    this.getListSupplierArr();
    this.getList();
    this.getListStorage();

    // this.getListDrugs();
  },
  methods: {
    selectChange (data) {
      var index = data.index
      var r = data.data
      this.warehousingDetails[index].drugsType = String(r.drugsType);
      this.warehousingDetails[index].drugsId = r.drugsId;
      this.warehousingDetails[index].specsId = r.specsId;
      this.warehousingDetails[index].priceId = r.priceId;
      this.warehousingDetails[index].placeName = r.placeName;
      this.warehousingDetails[index].dosageSizeUnit = r.dosageSizeUnit;
      this.warehousingDetails[index].specsName = r.drugsSpecsName;
      this.warehousingDetails[index].drugsName = r.drugsName;
      this.warehousingDetails[index].priceName = r.placeName;
      //this.warehousingDetails[index].purchasePrice = r.purchasePrice||'';
      this.warehousingDetails[index].retailPrice = r.retail;
      this.warehousingDetails[index].approvalCode = r.approvalCode;
      this.warehousingDetails[index].site = r.site;
      this.warehousingDetails[index].packingUnit = r.packingUnit;
      //this.warehousingDetails[index].drugsType = r.drugsType;
      this.warehousingDetails[index].inventory = r.inventory;
      this.$set(this.warehousingDetails[index], "specsArr", data.result);
      if (this.title == "添加入库单") {
        getProductionCode({
          drugsId: r.drugsId,
          specsId: r.specsId,
          priceId: r.priceId,
          pharmacyId: localStorage.getItem('pharmacyId')
        }).then(res => {
          if (res.code == 200) {
            this.$set(this.warehousingDetails[index], 'productionCode', res.data || '')
          }
        })
      }
    },
    /** 表单合计 **/
    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 === 7 || index === 8 || index === 9 || index === 11) {
          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 === 10) {
          let num = [];
          data.map((item) => {
            num.push(item.stock * item.purchasePrice);
          });
          let sum = num.reduce(function (prev, cur, index, array) {
            return prev + cur;
          });
          sums[10] = (sum-0).toFixed(4);
        }

        if (index === 12) {
          let num = [];
          data.map((item) => {
            num.push(item.stock * item.retailPrice);
          });
          let sum = num.reduce(function (prev, cur, index, array) {
            return prev + cur;
          });
          sums[12] = (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
      listWarehousing(form).then((response) => {
        this.warehouseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //获取入库方式
    getListStorage() {
      listRk({
        display: 'Y'
      }).then((res) => {
        this.storageArr = res.rows;
      });
    },
    //选择入库单位
    handleRk(e) {
      //console.log(e, "87");

      let newArr = this.storageArr.filter((item) => {
        return item.id == this.form.warehousingType;
      });
      if (newArr[0].deptType == "1") {
        this.getListMedicalPharmacy();
      } else {
        this.getListSupplier();
      }
    },
    //供货单位
    getListSupplier() {
      listSupplier().then((res) => {
        //console.log(res, "res1212");
        this.supplierArr = res.rows;
      });
    },
    getListSupplierArr() {
      listSupplier().then((res) => {
        //console.log(res, "res3434");
        this.supplierArrTab = res.rows;
      });
    },
    //药房
    getListMedicalPharmacy() {
      listMedicalPharmacy({
        state: 1
      }).then((res) => {
        this.supplierArr = res.data;
      });
    },
    //获取药品名称
    /*getListDrugs() {
      listAll().then((res) => {
        this.drugsArr = res.data;
      });
    },*/
    //通过药品名称获取药品类型
    /*handleDrugsId(e, row) {
      //console.log(e);
      //console.log(this.drugsArr);
      let newArr = this.drugsArr.filter((item) => {
        return item.id === e;
      });
      this.drugsId = e;
      this.warehousingDetails[row.$index].drugsType = String(
        newArr[0].drugsType
      );
      this.getListSpecs(e, row.$index);

      this.warehousingDetails[row.$index].specsId = "";
      this.warehousingDetails[row.$index].priceId = "";
      this.warehousingDetails[row.$index].purchasePrice = "";
      this.warehousingDetails[row.$index].retailPrice = "";
      this.warehousingDetails[row.$index].approvalCode = "";
      this.warehousingDetails[row.$index].packingUnit = "";
    },*/
    //获取药品规格
    getListSpecs(drugsId, index) {
      listSpecs({ drugsId }).then((res) => {
        // this.specsArr = res.rows;
        // this.warehousingDetails[row.$index].specsArr = res.rows
        this.$set(this.warehousingDetails[index], "specsArr", res.rows);
      });
    },
    //通过药品规格获取
    handleSpecsId(e, row) {
      let newArr = this.warehousingDetails[row.$index].specsArr.filter(
        (item) => {
          return item.id === e;
        }
      );
      this.specsId = e;
      this.warehousingDetails[row.$index].packingUnit = String(
        newArr[0].packingUnit
      );
      this.getListPrice(e, row.$index);

      this.warehousingDetails[row.$index].priceId = "";
      this.warehousingDetails[row.$index].purchasePrice = "";
      this.warehousingDetails[row.$index].retailPrice = "";
      this.warehousingDetails[row.$index].approvalCode = "";
    },
    //获取产地
    getListPrice(specsId, index) {
      listPrice({ specsId }).then((res) => {
        this.$set(this.warehousingDetails[index], "priceArr", res.rows);
      });
    },
    //通过药品产地获取
    handlePriceId(e, row) {
      let newArr = this.warehousingDetails[row.$index].priceArr.filter(
        (item) => {
          return item.id === e;
        }
      );
      this.priceId = e;
      this.productionCode = newArr[0].approvalCode;
      this.warehousingDetails[row.$index].purchasePrice = newArr[0].wholesale;
      this.warehousingDetails[row.$index].retailPrice = newArr[0].retail;
      // this.warehousingDetails[row.$index].productionCode =
      //   newArr[0].approvalCode;

      this.warehousingDetails[row.$index].approvalCode = newArr[0].approvalCode;
      this.warehousingDetails[row.$index].site = newArr[0].site;

      if (
        window.localStorage.getItem("pharmacyId") &&
        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,
      };
      getSumStock(params).then((res) => {
        //console.log(res, 99999999);
        !res.data
          ? this.$set(this.warehousingDetails[index], "inventory", "0")
          : this.$set(
              this.warehousingDetails[index],
              "inventory",
              res.data.stock
            );
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        pharmacyId: window.localStorage.getItem("pharmacyId"),
        warehousingType: null,
        remarks: null,
        createTime: null,
        keepingBy: null,
        createBy: null,
        keepingTime: null,
        state: null,
        del: null,
      };
      this.warehousingDetails = [
        {
          drugsId: "",
          specsId: "",
          riceId: "",
          stock: "",
          inventory: "",
          purchasePrice: "",
          purchasePriceAll: "",
          retailPrice: "",
          approvalCode: "",
          site: "",
          productionCode: "",
          validTime: "",
          specsArr: [],
          priceArr: [],
        },
      ];
      this.resetForm("form");
    },
    /** 记账 **/
    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();
      });
    },
    /** 搜索按钮操作 */
    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 = this.dayjs().format("YYYYMMDDHHmmssSSS");
      // this.form.createTime = 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;
      getWarehousing(id).then((response) => {
        response.data.warehousingDetails.map((item) => {
          item.drugsType = String(item.drugsType);
          item.packingUnit = String(item.packingUnit);
        });
        this.form = response.data;
        this.form.supplierId += ''
        this.warehousingDetails = response.data.warehousingDetails;
        //this.warehousingDetails.forEach((item, index) => {
          //this.getListSpecs(item.drugsId, index);
          //this.getListPrice(item.specsId, index);
          // this.warehousingDetails[index].packingUnit = String(item.packingUnit)
        //});
        //this.handleRk(response.data.warehousingType);
        this.open = true;
        num == 3
          ? (this.title = "详情入库单")
          : num == 1
          ? (this.title = "修改入库单")
          : num == 4
          ? (this.title = "冲销入库单")
          : num == 2
          ? (this.title = "记账入库单")
          : "";
      });
      this.num = num
      if (num === 1) {
        this.disableDetails = false;
        this.editable = true
      } else if (num === 2 || num === 3 || num === 4) {
        this.disableDetails = true;
        this.editable = false
      }
      //console.log('num', this.num)
    },
    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() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.warehousingDetails.find(v => v.purchasePrice == '')) {
            return this.msgError('请完善进货单价信息')
          }
          this.form.warehousingDetails = this.warehousingDetails;
          // this.form.createTime = this.form.createTime
          //   ? this.formatTime(this.form.createTime, "yyyy-MM-dd hh:mm:ss")
          //   : null;
          // this.form.keepingTime = this.form.keepingTime
          //   ? this.formatTime(this.form.keepingTime, "yyyy-MM-dd hh:mm:ss")
          //   : null;
          var result = this.form.warehousingDetails.every(
            (v, i) => v.productionCode
          );
          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 (result) {
            if (form.id != null) {
              updateWarehousing(form).then((response) => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addWarehousing(form).then((response) => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          } else {
            this.msgError("生产批号不能为空");
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("确定需要删除选中数据吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delWarehousing(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.inventory = "";
      obj.purchasePrice = "";
      obj.purchasePriceAll = "";
      obj.retailPrice = "";
      obj.approvalCode = "";
      obj.site = "";
      obj.productionCode = "";
      obj.validTime = "";
      this.warehousingDetails.push(obj);
    },
    /** 入库单详情删除按钮操作 */
    handleDeleteWarehouseDetail() {
      if (this.checkedWarehouseDetail.length == 0) {
        this.msgError("请先选择要删除的入库单详情数据");
      } else {
        const warehousingDetails = this.warehousingDetails;
        const checkedWarehouseDetail = this.checkedWarehouseDetail;
        this.warehousingDetails = warehousingDetails.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 exportWarehousing(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;
}
</style>
