<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="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 prop="tiem">
              <el-date-picker
                size="small"
                style="width:240px"
                v-model="time"
                type="daterange"
                :clearable="false"
                range-separator="至"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-form-item>
          <el-form-item label="" prop="type">
            <el-select
              style="width:160px"
              v-model="queryParams.type"
              placeholder="请选择盘存单类型"
            >
              <el-option
                v-for="item in typeArr"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="state">
            <el-select placeholder="请选择盘存状态" v-model="queryParams.state" style="width:160px">
              <el-option
                v-for="item in stateArr"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></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
              size="mini"
              :loading="exportLoading"
              v-hasPermi="['inventory:takeInventory:export']"
              @click="handleOpen"
              >{{ stateOpen == 0 ? "开始盘存" : "结束盘存" }}</el-button
            >

            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['inventory:takeInventory:add']"
              >新增</el-button
            >
            <el-button type="primary" plain icon="el-icon-s-check" size="mini" @click="summary"
              >汇总</el-button
            >
          </el-form-item>
        </div>
      </div>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          :loading="exportLoading"
          v-hasPermi="['inventory:takeInventory:export']"
          >开始盘存/结束盘存</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['inventory:takeInventory:add']"
          >新增</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          v-hasPermi="['inventory:takeInventory:remove']"
          >汇总</el-button
        >
      </el-col>
    </el-row> -->

    <el-table
      v-loading="loading"
      :data="takeInventoryList"
      @selection-change="handleSelectionChange"
      border
      size="mini">
      <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="state">
        <template slot-scope="scope">
          <dict-tag :options="stateArr" :value="scope.row.state" />
        </template>
      </el-table-column>
      <el-table-column label="盘存类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="typeArr" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="盘存总数" align="center" prop="num" />
      <el-table-column
        label="盘存零售总金额"
        align="center"
        prop="amount"
      />
      <el-table-column label="制单人" align="center" prop="createBy" />
      <el-table-column label="制单时间" align="center" prop="createTime">
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.keepingTime, "{y}-{m}-{d}") }}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="记账人" align="center" prop="keepingBy" />
      <el-table-column
        label="记账时间"
        align="center"
        prop="keepingTime"
      >
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.keepingTime, "{y}-{m}-{d}") }}</span>
        </template> -->
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="260px"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            style="width: 40px"
            @click="handleUpdate(scope.row, 1)"
            v-hasPermi="['inventory:takeInventory:edit']"
            v-if="scope.row.state == 1"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="primary"
            style="width: 40px"
            @click="handleUpdate(scope.row, 2)"
            v-hasPermi="['inventory:takeInventory:edit']"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="primary"
            style="width: 40px"
            @click="handleSubmit(scope.row)"
            v-hasPermi="['inventory:takeInventory:edit']"
            >提交</el-button
          >
          <el-button
            size="mini"
            type="primary"
            style="width: 40px"
            @click="handleUpdate(scope.row, 3)"
            v-if="scope.row.state == 3"
            v-hasPermi="['inventory:takeInventory:edit']"
            >记账</el-button
          >
          <el-button
            size="mini"
            type="primary"
            style="width: 40px"
            @click="handleDelete(scope.row)"
            v-if="scope.row.state==1||scope.row.state==3"
            v-hasPermi="['inventory:takeInventory:remove']"
            >删除</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-input v-model="form.mac" style="display: none" disabled id="T6" />

    <!-- 添加或修改盘存单对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1180px"
      append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="盘存单号" prop="code">
              <el-input
                v-model="form.code"
                placeholder="请输入盘存单号"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-model="form.remarks"
                placeholder="请输入备注"
                :disabled="disableDetails"
              />
            </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="num==3" :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="num==3" :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="takeInventoryListDetail"
          :row-class-name="rowTakeDetailIndex"
          @selection-change="handleTakeDetailSelectionChange"
          ref="takeInventoryDetail"
          border
          size="mini"
          :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" :pharmacyId="form.pharmacyId" :index="scope.$index" :disableDetails="disableDetails" :info="scope.row" @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.length&&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"
          >
            <template slot-scope="scope"><span>{{scope.row.specsName}}</span></template>
          </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="实际库存数"
            align="center"
            prop="takeNum"
            width="110"
          >
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.takeNum"
                placeholder="请输入"
                :disabled="disableDetails"
                :controls="false"
                style="width:100%"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="盈亏数"
            prop="profitLossNum"
            align="center"
            width="110"
          >
            <template slot-scope="scope">
              <div>{{scope.row.takeNum-scope.row.stock}}</div>
            </template>
          </el-table-column>
          <el-table-column
            label="进货单价"
            prop="purchasePrice"
            align="center"
            width="110"
          >
            <template slot-scope="scope"><span>{{scope.row.purchasePrice}}</span></template>
          </el-table-column>
          <el-table-column
            label="进货总价"
            prop="purchasePrice"
            align="center"
            width="110"
          >
            <template slot-scope="scope">
              <div>{{(scope.row.purchasePrice * scope.row.stock).toFixed(4)}}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="盈亏进价金额"
            prop="stock"
            align="center"
            width="110"
          >
            <template slot-scope="scope">
              <div>{{(scope.row.purchasePrice *(scope.row.takeNum-scope.row.stock)).toFixed(4)}}</div>
            </template>
          </el-table-column>
          <el-table-column
            label="零售单价"
            prop="retailPrice"
            width="110"
            align="center"
          >
            <template slot-scope="scope"><span>{{scope.row.retailPrice}}</span></template>
          </el-table-column>
          <el-table-column
            label="零售总价"
            prop="retailPrice"
            width="110"
            align="center"
          >
            <template slot-scope="scope">
              {{(scope.row.retailPrice * scope.row.stock).toFixed(4)}}
            </template>
          </el-table-column>
          <el-table-column
            label="盈亏零售金额"
            prop="stock"
            align="center"
            width="110"
          >
            <template slot-scope="scope">
              <div>{{(scope.row.retailPrice *(scope.row.takeNum-scope.row.stock)).toFixed(4)}}</div>
            </template>
          </el-table-column>
          <el-table-column
            label="药品期效"
            prop="validTime"
            width="150"
            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="num !== 2 && num !== 3"
          >确 定</el-button
        >
        <el-button @click="handleKeeping" v-if="num === 3">记账</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>n
    </el-dialog>

    <el-dialog title="汇总单" :visible.sync="summaryVisible" width="90%">
      <el-table :data="summaryList" size="mini">
        <el-table-column label="序号" align="center" type="index" width="65"></el-table-column>
        <el-table-column label="药品名称" prop="drugsName" width="110" align="center"></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="takeNum" align="cneter" width="110"></el-table-column> -->
        <el-table-column label="进货单价" prop="purchasePrice" align="center" width="110"></el-table-column>
        <el-table-column label="进货总价" align="center" width="110">
          <template slot-scope="scope">
            <div>{{ (scope.row.purchasePrice * scope.row.stock).toFixed(4) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="零售单价" prop="retailPrice" width="110" align="center"></el-table-column>
        <el-table-column label="零售总价" width="110" align="center">
          <template slot-scope="scope">
            <div>
              {{ (scope.row.retailPrice * scope.row.stock).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-dialog>
  </div>
</template>

<script>
import {
  listTakeInventory,
  getTakeInventory,
  delTakeInventory,
  addTakeInventory,
  updateTakeInventory,
  exportTakeInventory,
  submit,
  keeping,
  start,
  summaryMethod
} from "@/api/inventory/takeInventory";
import { getTime } from "@/api/inventory/forward";

import { detailList } from "@/api/inventory/inventory";

import { getLodop } from "@/assets/js/LodopFuncs";
import selectOutTable from '@/components/selectTable/selectOutTable.vue'
import { listSystemWin } from "@/api/inventory/SystemWin";
export default {
  name: "TakeInventory",
  components: {
    selectOutTable
  },
  data() {
    return {
      summaryVisible: false,
      summaryList: [],
      time: [],
      BtnState: 1,
      num: null,
      specsArr: [],
      priceArr: [],
      productionCodeArr: [],
      drugsArr: [],
      stateOpen: "",
      typeArr: [
        { name: "窗口盘存单", id: "1" },
        { name: "汇总盘存单", id: "2" },
      ],
      stetaArr: [
        { name: "制单", id: "1" },
        { name: "提交", id: "2" },
        { name: "汇总", id: "3" },
        { name: "记账", id: "4" },
      ],
      disableDetails: false,
      drugsTypeOptions: [],
      unitOptions: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 盘存单表格数据
      takeInventoryList: [],
      takeInventoryListDetail: [
        {
          drugsId: "",
          specsId: "",
          riceId: "",
          priceId: "",
          stock: "",
          takeNum: "",
          purchasePrice: "",
          retailPrice: "",
          approvalCode: "",
          site: "",
          productionCode: "",
          validTime: "",
          specsArr: [],
          priceArr: [],
          productionCodeArr: [],
        },
      ],
      // 子表选中数据
      checkedWarehouseDetail: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        pharmacyId: null,
        remarks: null,
        keepingBy: null,
        keepingTime: null,
        state: null,
        del: 0,
        pharmacyId: window.localStorage.getItem("pharmacyId"),
        time: [],
      },
      // 表单参数
      form: {
        pharmacyId: window.localStorage.getItem("pharmacyId"),
        keepingBy: null,
        createBy: null,
      },
      // 表单校验
      rules: {
        pharmacyId: [
          { required: true, message: "药房id不能为空", trigger: "blur" },
        ],
      },
      stateArr: [
        { name: "制单", id: "1" },
        { name: "提交", id: "2" },
        { name: "汇总", id: "3" },
        { name: "记账", id: "4" },
      ],

      rowId: null,
      mac: '',
      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.getTimeApi();
    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) => {
      // response.data.map((item) => {
      //   this.unitOptions[item.dictValue] = item.dictLabel;
      // });
      this.unitOptions = response.data;
    });

    this.getListDrugs();

    listSystemWin({
      pageNum: 1,
      pageSize: 1
    }).then((response) => {
      //console.log(response)
      if (response.rows && response.rows.length) {
        this.mac = response.rows[0].uuid
      }
    });
  },
  methods: {
    summary () {
      if (!this.mac) {
        return this.msgError('请先到窗口设置里添加网卡标注')
      }
      var startTime = ''
      var endTime = ''
      if (this.time && this.time.length) {
        startTime = this.formatTime(this.time[0], 'yyyy-MM-dd')
        endTime = this.formatTime(this.time[1], 'yyyy-MM-dd')
      } else {
        startTime = endTime = ''
      }
      summaryMethod({
        startTime,
        endTime,
        pharmacyId: localStorage.getItem("pharmacyId"),
        mac: this.mac
      }).then(res => {
        this.msgSuccess(res.msg)
        this.getList()
        this.summaryList = res.data.takeInventoryListDetail
        this.summaryVisible = true
      })
    },
    //获取最新结转时间
    getTimeApi() {
      getTime().then((res) => {
        res.msg
          ? this.time.push(new Date(res.msg))
          : this.time.push(
              new Date(
                this.dayjs().startOf("month").format("YYYY-MM-DD") + " 00:00:00"
              )
            ); // 回显开始时间
        this.time.push(
          new Date(this.dayjs().format("YYYY-MM-DD") + " 00:00:00")
        ); // 回显结束时间
         this.getList();
      });
    },
    /** 表单合计 **/
    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 === 11 || index === 14) {
          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.takeNum - item.stock);
          });
          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.purchasePrice * item.stock);
          });
          let sum = num.reduce(function (prev, cur, index, array) {
            return prev + cur;
          });
          sums[12] = (sum-0).toFixed(4);
        }

        if (index === 13) {//盈亏进货金额
          let num = [];
          data.map((item) => {
            num.push(item.purchasePrice * (item.takeNum - item.stock))
            let sum = num.reduce(function (prev, cur, index, array) {
              return prev + cur;
            });
            sums[13] = (sum-0).toFixed(4);;
          })
        }

        if (index === 15) {//盈亏零售金额
          let num = [];
          data.map((item) => {
            num.push(item.retailPrice *item.stock);
          });
          let sum = num.reduce(function (prev, cur, index, array) {
            return prev + cur;
          });
          sums[15] = (sum-0).toFixed(4);
        }

        if (index === 16) {
          let num = [];
          data.map((item) => {
            num.push(
              item.retailPrice
                ? item.retailPrice * (item.takeNum - item.stock)
                : 0
            );
          });
          let sum = num.reduce(function (prev, cur, index, array) {
            return prev + cur;
          });
          sums[16] = (sum-0).toFixed(4);
        }
      });
      return sums;
    },
    getUUID() {
      // uUID().then((res) => {
      //   // //console.log(res, "2323");
      //   this.form.uuid = res.msg;
      // });

      this.getSystemInfo(
        "NetworkAdapter.1.PhysicalAddress",
        document.getElementById("T6")
      );
    },

    //提交
    handleSubmit(e) {
      // //console.log(e.id)
      const id = e.id;
      this.$confirm("确定要提交吗？提交后不可修改盘存单", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //console.log(id);
        submit(id).then((res) => {
          this.getList();
        });
      });
    },
    //记账
    handleKeeping() {
      //console.log(this.rowId);
      keeping(this.rowId).then((res) => {
        this.open = false;
        this.msgSuccess("记账成功");
        this.getList()
      });
    },
    /** 出库单详情序号 */
    rowTakeDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    //获取药品名称
    getListDrugs() {
      detailList({ pharmacyId: window.localStorage.getItem("pharmacyId") }).then(
        (res) => {
          this.drugsArr = res.data;
        }
      );
    },
    selectChange (data) {
      var index = data.index
      this.curIndex = index
      var r = data.data
      /*this.takeInventoryListDetail[index].drugsId = r.drugsId;
      this.takeInventoryListDetail[index].drugsType = String(r.drugsType);
      this.takeInventoryListDetail[index].specsId = r.specsId;
      this.takeInventoryListDetail[index].priceId = r.priceId;
      this.takeInventoryListDetail[index].placeName = r.placeName;
      this.takeInventoryListDetail[index].specsName = r.drugsSpecsName;
      //this.takeInventoryListDetail[index].purchasePrice = r.purchasePrice;
      this.takeInventoryListDetail[index].retailPrice = r.retailPrice;
      this.takeInventoryListDetail[index].approvalCode = r.approvalCode;
      this.takeInventoryListDetail[index].packingUnit = r.packingUnit;
      this.takeInventoryListDetail[index].drugsType = r.drugsType;
      this.takeInventoryListDetail[index].validTime = r.validTime;
      //this.takeInventoryListDetail[index].takeNum = r.store;
      this.$set(this.takeInventoryListDetail[index], "specsArr", data.result);
      this.takeInventoryListDetail[index].productionCode = r.productionCode;
      this.takeInventoryListDetail[index].purchasePrice = r.purchasePrice;
      this.takeInventoryListDetail[index].takeNum = r.stock;*/
      this.takeInventoryListDetail[index].drugsId = r.drugsId;
      this.takeInventoryListDetail[index].drugsType = String(r.drugsType);
      this.takeInventoryListDetail[index].specsId = r.specsId;
      this.takeInventoryListDetail[index].priceId = r.priceId;
      this.takeInventoryListDetail[index].dosageSizeUnit = r.dosageSizeUnit;
      this.takeInventoryListDetail[index].specsName = r.specsName;
      this.takeInventoryListDetail[index].drugsName = r.drugsName;
      this.takeInventoryListDetail[index].inventoryId = r.inventoryId;
      this.takeInventoryListDetail[index].priceName = r.priceName;
      this.takeInventoryListDetail[index].retailPrice = r.retailPrice;
      this.takeInventoryListDetail[index].approvalCode = r.approvalCode;
      this.takeInventoryListDetail[index].site = r.site;
      this.takeInventoryListDetail[index].validTime = r.validTime;
      this.takeInventoryListDetail[index].packingUnit = r.packingUnit;
      this.takeInventoryListDetail[index].drugsType = r.drugsType;
      this.takeInventoryListDetail[index].validTime = r.validTime;
      this.$set(this.takeInventoryListDetail[index], "specsArr", data.result);
      this.takeInventoryListDetail[index].productionCode = r.productionCode;
      this.takeInventoryListDetail[index].purchasePrice = r.purchasePrice;
      this.takeInventoryListDetail[index].stock = r.stock;
    },
    //通过药品名称获取药品类型
    /*handleDrugsId(e, row) {
      let newArr = this.drugsArr.filter((item) => {
        return item.drugsId === e;
      });
      this.drugsId = e;
      this.takeInventoryListDetail[row.$index].drugsType = String(
        newArr[0].drugsType
      );
      //console.log(newArr, "88887");
      this.getListSpecs(e, row.$index);

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

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

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

      // this.takeInventoryListDetail[row.$index].productionCode =
      //   newArr[0].productionCode;

      // this.takeInventoryListDetail[row.$index].validTime = newArr[0].validTime;

      // this.takeInventoryListDetail[row.$index].site = newArr[0].site;
    },
    //通过生产批号选择
    handleCode(e, row) {
      let newArr = this.takeInventoryListDetail[
        row.$index
      ].productionCodeArr.filter((item) => {
        return item.productionCode === e;
      });
      this.productionCode = newArr[0].approvalCode;
      this.takeInventoryListDetail[row.$index].purchasePrice =
        newArr[0].purchasePrice;
      this.takeInventoryListDetail[row.$index].retailPrice =
        newArr[0].retailPrice;
      this.takeInventoryListDetail[row.$index].approvalCode =
        newArr[0].approvalCode;

      this.takeInventoryListDetail[row.$index].validTime = newArr[0].validTime;

      this.takeInventoryListDetail[row.$index].site = newArr[0].site;
      this.productionCode = newArr[0].productionCode;
      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,
      };
      detailList(params).then((res) => {
        //console.log(res, 99999999);
        res.data.length < 0
          ? this.$set(this.takeInventoryListDetail[index], "inventory", "0")
          : this.$set(
              this.takeInventoryListDetail[index],
              "inventory",
              res.data[0].stock
            );
      });
    },
    /** 查询盘存单列表 */
    getList() {
      if (this.time && this.time.length) {
        this.queryParams.startTime = this.formatTime(this.time[0], 'yyyy-MM-dd')
        this.queryParams.endTime = this.formatTime(this.time[1], 'yyyy-MM-dd')
      } else {
        this.queryParams.startTime = this.queryParams.endTime = ''
      }
      this.loading = true;
      listTakeInventory(this.queryParams).then((response) => {
        this.takeInventoryList = response.rows;
        this.total = response.total;
        this.stateOpen = response.state;
        this.loading = false;
      });
    },
    //开始、结束盘存
    handleOpen() {
      // if (this.ids.length <= 0) {
      //   this.msgError("请先选择盘存");
      // } else {
      var startTime = ''
      var endTime = ''
      if (this.time && this.time.length) {
        startTime = this.formatTime(this.time[0], 'yyyy-MM-dd')
        endTime = this.formatTime(this.time[1], 'yyyy-MM-dd')
      }
      let params = {
        pharmacyId: window.localStorage.getItem("pharmacyId"),
        state: 1 - this.stateOpen,
        startTime,
        endTime
      };
      start(params).then((res) => {
        this.getList();
        if (this.stateOpen == 0) {
          this.msgSuccess('成功，开始盘存')
          this.stateOpen = 0
        } else {
          this.msgSuccess('结束盘存成功')
          this.stateOpen = 1
        }
      });
      // }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        pharmacyId: window.localStorage.getItem("pharmacyId"),
        id: null,
        code: null,
        remarks: null,
        createTime: null,
        keepingTime: null,
        state: null,
        del: null,
        drugsType: '',
        keepingBy: null,
        mac: this.mac,
        createBy: null,
      };
      this.takeInventoryListDetail = [
        {
          drugsId: "",
          specsId: "",
          riceId: "",
          stock: "",
          takeNum: "",
          priceId: "",
          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() {
      if (!this.mac) {
        return this.msgError('请先到窗口设置里添加网卡标注')
      }
      this.reset();
      this.form.code = this.dayjs().format("YYYYMMDDHHmmssSSS");
      // this.form.createTime = new Date();
      // this.form.keepingTime = new Date();
      //this.getUUID();
      this.num = ''
      this.open = true;
      this.title = "添加盘存单";
      this.disableDetails = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row, num) {
      this.reset();
      this.num = num;
      const id = row.id || this.ids;
      this.rowId = id;
      getTakeInventory(id).then((response) => {
        response.data.takeInventoryListDetail.map((item) => {
          item.drugsType = String(item.drugsType);
          item.packingUnit = String(item.packingUnit);
        });
        this.form = response.data;
        this.takeInventoryListDetail = response.data.takeInventoryListDetail;
        this.takeInventoryListDetail.forEach((item, index) => {
          //this.getListSpecs(item.drugsId, index);
          //this.getListPrice(item.specsId, index);
          // this.warehousingDetails[index].packingUnit = String(item.packingUnit)
        });
        this.open = true;
        // this.title = "修改盘存单";
        if (num === 1) {
          this.title = "修改盘存单";
          this.disableDetails = false;
        } else if (num === 2) {
          this.title = "盘存单详情";
          this.disableDetails = true;
        } else if (num === 3) {
          this.title = "记账盘存单";
          this.disableDetails = true;
        }
      });
    },
    /** 出库单详情添加按钮操作 */
    handleAddWarehouseDetail() {
      let obj = {};
      obj.drugsId = "";
      obj.specsId = "";
      obj.priceId = "";
      obj.stock = "";
      obj.takeNum = "";
      obj.purchasePrice = "";
      obj.retailPrice = "";
      obj.approvalCode = "";
      obj.site = "";
      obj.productionCode = "";
      obj.validTime = "";
      this.takeInventoryListDetail.push(obj);
    },
    /** 出库单详情删除按钮操作 */
    handleDeleteWarehouseDetail() {
      if (this.checkedTakeDetail.length == 0) {
        this.msgError("请先选择要删除的报损详情数据");
      } else {
        const takeInventoryListDetail = this.takeInventoryListDetail;
        const checkedTakeDetail = this.checkedTakeDetail;
        this.takeInventoryListDetail = takeInventoryListDetail.filter(function (
          item
        ) {
          return checkedTakeDetail.indexOf(item.index) == -1;
        });
      }
    },
    /** 复选框选中数据 */
    handleTakeDetailSelectionChange(selection) {
      this.checkedTakeDetail = selection.map((item) => item.index);
    },
    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() {
      if (this.takeInventoryListDetail.find(v => !v.stock)) {
        return this.$message.warning('请输入实际库存数')
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          //console.log(this.form)
          //this.form.mac = document.getElementById("T6").value;
          ////console.log(this.form.mac, "mac");
          this.form.takeInventoryListDetail = this.takeInventoryListDetail;
          // this.form.createTime = this.formatTime(
          //   this.form.createTime,
          //   "yyyy-MM-dd hh:mm:ss"
          // );
          // this.form.keepingTime = this.formatTime(
          //   this.form.keepingTime,
          //   "yyyy-MM-dd hh:mm:ss"
          // );
          if (this.form.id != null) {
            updateTakeInventory(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTakeInventory(this.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 delTakeInventory(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有盘存单数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportTakeInventory(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>
