<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"
              style="width:200px"
            />
          </el-form-item>

          <el-form-item label="" prop="reportingTime">
            <el-date-picker
              clearable
              size="small"
              v-model="reportingTime"
              type="daterange"
              value-format="yyyy-MM-dd"
              start-placeholder="报损开始时间"
              end-placeholder="报损结束时间"
              style="width:240px"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item label="" prop="state">
            <!-- <el-input
              v-model="queryParams.state"
              placeholder="请选择单据状态"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            /> -->

            <el-select
              v-model="queryParams.state"
              placeholder="请选择单据状态"
              clearable
              size="small"
              style="width:200px"
            >
              <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:reporting:add']"
              >新增</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
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['inventory:reporting:add']"
          >新增</el-button
        >
      </el-col>
    </el-row> -->

    <el-table
      v-loading="loading"
      :data="reportingList"
      @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="id" align="center" prop="id" /> -->
      <el-table-column label="单号" align="center" prop="code" show-overflow-tooltip />
      <el-table-column label="制单时间" align="center" prop="createTime" show-overflow-tooltip />
      <el-table-column label="制单人" align="center" prop="createBy" show-overflow-tooltip />
      <el-table-column
        label="记账时间"
        align="center"
         show-overflow-tooltip
        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" prop="keepingBy" />
      <!-- <el-table-column label="药房id" align="center" prop="pharmacyId" /> -->
      <!-- <el-table-column
        label="报损时间"
        align="center"
        prop="reportingTime"
         show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reportingTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="备注" align="center" prop="remarks" /> -->
      <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"
        class-name="small-padding fixed-width"
        width="250"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            style="width: 40px"
            @click="handleUpdate(1, scope.row)"
            v-hasPermi="['inventory:reporting: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:reporting: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
          >
        </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-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="reportingTime">
              <el-date-picker
                clearable
                size="small"
                v-model="form.reportingTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择报损时间"
                :disabled="disableDetails"
              >
              </el-date-picker>
            </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 v-model="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="handleAddReportingDetail"
              v-if="!disableDetails"
              >添加</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDeleteReportingDetail"
              v-if="!disableDetails"
              >删除</el-button
            >
          </el-col>
        </el-row>
        <el-table :data="reportingDetails" :row-class-name="rowReportingDetailIndex" @selection-change="handleReportingDetailSelectionChange" ref="reportingDetail" border size="mini" :summary-method="getSummaries" show-summary>
          <el-table-column type="selection" width="50" align="center"></el-table-column>
          <el-table-column label="序号" align="center" prop="index" width="50"></el-table-column>
          <el-table-column label="药品名称" prop="drugsId" align="center" width="110">
            <template slot-scope="scope">
              <selectOutTable :key="now" type="deal" :info="scope.row" :pharmacyId="form.pharmacyId" :index="scope.$index" :disableDetails="disableDetails" @selectChange="selectChange"></selectOutTable>
            </template>
          </el-table-column>
          <el-table-column label="药品类型" 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">
            <template slot-scope="scope"><span>{{scope.row.productionCode}}</span></template>
          </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" width="110" align="center"></el-table-column>
          <el-table-column label="报损数量" prop="reportingNum" width="110" align="center">
            <template slot-scope="scope">
              <el-input-number :controls="false" size="mini" style="width:100%" :max="parseInt(scope.row.warehouseNum)" v-model="scope.row.reportingNum" placeholder="请输入报损数量" :disabled="disableDetails"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="进货单价" prop="purchasePrice" width="110" align="center">
            <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.reportingNum).toFixed(4) || '0'}}
              </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">{{(scope.row.retailPrice * scope.row.reportingNum).toFixed(4) || '0'}}</template>
          </el-table-column>
          <el-table-column label="报损原因" prop="remarks" width="110" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remarks" placeholder="请输入报损原因" :disabled="disableDetails"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="生产批号" prop="productionCode" width="180" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.productionCode" placeholder="生产批号" disabled></el-input>
            </template>
          </el-table-column>
          <el-table-column label="药品效期" prop="validTime" width="180" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.validTime" placeholder="药品效期" disabled></el-input>
            </template>
          </el-table-column>
          <el-table-column label="批准文号" prop="approvalCode" width="180" align="center"></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>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listReporting,
  getReporting,
  delReporting,
  addReporting,
  updateReporting,
  exportReporting,
  updataKeeping,
} from "@/api/inventory/reporting";
import { oneList } from "@/api/inventory/inventory";

import selectOutTable from '@/components/selectTable/selectOutTable.vue'
export default {
  name: "Reporting",
  components: {
    selectOutTable
  },
  data() {
    return {
      createBy: '',
      createTime: '',
      now: 0,
      unitArr: [],
      reportingTime: [],
      billOptions: [],
      drugsArr: [],
      specsArr: [],
      priceArr: [],
      productionCodeArr: [],
      drugsTypeOptions: [],
      unitOptions: [],
      tableId: "",
      BtnState: "",
      disableDetails: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedReportingDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报损单表格数据
      reportingList: [],
      // 报损单详情表格数据
      reportingDetails: [
        {
          drugsId: "",
          specsId: "",
          riceId: "",
          priceId: "",
          stock: "",
          warehouseNum: "",
          reportingNum: '',
          purchasePrice: "",
          retailPrice: "",
          approvalCode: "",
          site: "",
          productionCode: "",
          validTime: "",
          specsArr: [],
          priceArr: [],
          productionCodeArr: [],
        },
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        pharmacyId: null,
        reportingTime: null,
        remarks: null,
        keepingBy: null,
        keepingTime: null,
        state: null,
        del: null,
        endTime: '',
        startTime: '',
        pharmacyId: window.localStorage.getItem("pharmacyId"),
      },
      // 表单参数
      form: {
        keepingBy: null,
        createBy: window.localStorage.getItem("userName"),
        pharmacyId: window.localStorage.getItem("pharmacyId"),
      },
      // 表单校验
      rules: {
        pharmacyId: [
          { required: true, message: "药房id不能为空", trigger: "blur" },
        ],
      },
      billOptions: [
        { dictLabel: "制单", dictValue: "1" },
        { dictLabel: "记账", dictValue: "2" },
        { dictLabel: "删除", dictValue: "3" },
      ],
    };
  },
  created() {
    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("unit").then((response) => {
      this.unitArr = response.data;
    });
    this.getDicts("drugs_type").then((response) => {
      this.drugsTypeOptions = response.data;
    });
    this.getList();
    //this.getListDrugs();
  },
  methods: {
    /** 表单合计 **/
    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) {
          let num = [];
          data.map((item) => {
            num.push(item.stock);
          });
          let sum = num.reduce(function (prev, cur, index, array) {
            return prev + cur;
          }, 0);
          if (sum >= 0) {
            sums[7] = Number(sum).toFixed(4);
          } else {
            sum[7] = '0.000'
          }
        }
        if (index === 8) {
          let num = [];
          data.map((item) => {
            num.push(item.reportingNum);
          });
          let sum = num.reduce(function (prev, cur, index, array) {
            return prev + cur;
          }, 0);
          sums[8] = (sum-0).toFixed(4);
        }
        if (index === 9) {
          let num = [];
          data.map((item) => {
            num.push(item.purchasePrice);
          });
          let sum = num.reduce(function (prev, cur, index, array) {
            return prev + cur;
          }, 0);
          sums[9] = (sum-0).toFixed(4);
        }
        if (index === 10) {
          let num = [];
          data.map((item) => {
            num.push(item.purchasePrice * item.reportingNum);
          });
          let sum = num.reduce(function (prev, cur, index, array) {
            return prev + cur;
          }, 0);
          sums[10] = (sum-0).toFixed(4);
        }
        if (index === 11) {
          let num = [];
          data.map((item) => {
            num.push(item.retailPrice);
          });
          let sum = num.reduce(function (prev, cur, index, array) {
            return prev + cur;
          }, 0);
          sums[11] = (sum-0).toFixed(4);
        }
        if (index === 12) {
          let num = [];
          data.map((item) => {
            num.push(item.retailPrice * item.reportingNum);
          });
          let sum = num.reduce(function (prev, cur, index, array) {
            return prev + cur;
          }, 0);
          sums[12] = (sum-0).toFixed(4);
        }
      });
      return sums;
    },

    //获取药品名称
    getListDrugs() {
      oneList({ 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.reportingDetails[index].drugsId = r.drugsId;
      this.reportingDetails[index].drugsType = String(r.drugsType);
      this.reportingDetails[index].specsId = r.specsId;
      this.reportingDetails[index].priceId = r.priceId;
      this.reportingDetails[index].packingUnit = r.packingUnit;
      this.reportingDetails[index].specsName = r.specsName;
      this.reportingDetails[index].drugsName = r.drugsName;
      this.reportingDetails[index].priceName = r.priceName;
      this.reportingDetails[index].inventoryId = r.inventoryId;
      this.reportingDetails[index].retailPrice = r.retailPrice;
      this.reportingDetails[index].approvalCode = r.approvalCode;
      this.reportingDetails[index].site = r.site;
      this.reportingDetails[index].packingUnit = r.packingUnit;
      this.reportingDetails[index].drugsType = r.drugsType;
      this.reportingDetails[index].validTime = r.validTime;
      this.$set(this.reportingDetails[index], "specsArr", data.result);
      this.reportingDetails[index].productionCode = r.productionCode;
      this.reportingDetails[index].purchasePrice = r.purchasePrice;
      this.reportingDetails[index].stock = r.stock;
    },
    //通过药品名称获取药品类型
    /*handleDrugsId(e, row) {
      let newArr = this.drugsArr.filter((item) => {
        return item.drugsId === e;
      });
      this.drugsId = e;
      this.reportingDetails[row.$index].drugsType = String(newArr[0].drugsType);
      this.getListSpecs(e, row.$index);

      this.reportingDetails[row.$index].specsId = "";
      this.reportingDetails[row.$index].priceId = "";
      this.reportingDetails[row.$index].purchasePrice = "";
      this.reportingDetails[row.$index].retailPrice = "";
      this.reportingDetails[row.$index].approvalCode = "";
      this.reportingDetails[row.$index].packingUnit = "";
    },

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

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

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

      // if (
      //   this.productionCode &&
      //   window.localStorage.getItem("pharmacyId") &&
      //   this.drugsId &&
      //   this.specsId &&
      //   this.priceId
      // ) {
      //   this.getOneList(row.$index);
      // }
    },

    //获取生产批号
    handleCode(e, row) {
      let newArr = this.reportingDetails[row.$index].productionCodeArr.filter(
        (item) => {
          return item.productionCode === e;
        }
      );

      this.reportingDetails[row.$index].site = newArr[0].site;
      this.productionCode = newArr[0].productionCode;
      this.reportingDetails[row.$index].validTime = newArr[0].validTime;
      this.reportingDetails[row.$index].approvalCode = newArr[0].approvalCode;
      this.reportingDetails[row.$index].retailPrice = newArr[0].retailPrice;
      this.reportingDetails[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) => {
        if (res.data.length <= 0) {
          this.$set(this.reportingDetails[index], "reportingNum", "0");
        } else {
          this.$set(
            this.reportingDetails[index],
            "reportingNum",
            res.data[0].stock
          );
          this.$set(this.reportingDetails[index], "site", res.data[0].site);
          this.$set(
            this.reportingDetails[index],
            "approvalCode",
            res.data[0].approvalCode
          );
          this.$set(
            this.reportingDetails[index],
            "validTime",
            res.data[0].validTime
          );
          this.$set(
            this.reportingDetails,
            "productionCode",
            res.data[0].productionCode
          );
        }
        // res.data.length <= 0
        //   ? this.$set(this.reportingDetails[index], "reportingNum", "0")
        //   : this.$set(
        //       this.reportingDetails[index],
        //       "reportingNum",
        //       res.data[0].stock
        //     );
      });
    },

    /** 查询报损单列表 */
    getList() {
      this.loading = true;
      if (this.reportingTime && this.reportingTime.length) {
        this.queryParams.startTime = this.reportingTime[0]
        this.queryParams.endTime = this.reportingTime[0]
      } else {
        delete this.queryParams.startTime
        delete this.queryParams.endTime
      }
      listReporting(this.queryParams).then((response) => {
        this.reportingList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        pharmacyId: window.localStorage.getItem("pharmacyId"),
        reportingTime: null,
        remarks: null,
        createBy: null,
        createTime: null,
        keepingBy: null,
        createBy: null,
        state: null,
        del: null,
      };
      this.reportingDetails = [
        {
          drugsId: "",
          specsId: "",
          riceId: "",
          priceId: "",
          stock: "",
          warehouseNum: "",
          purchasePrice: "",
          retailPrice: "",
          approvalCode: "",
          site: "",
          productionCode: "",
          validTime: "",
          specsArr: [],
          productionCodeArr: [],
        },
      ];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.reportingTime = []
      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.form.keepingTime = new Date();
      this.open = true;
      this.BtnState = 1;
      this.title = "添加报损单";
      this.now = Date.now()
      this.disableDetails = false;
    },
    /** 修改按钮操作 */
    handleUpdate(num, row) {
      this.BtnState = num;
      this.reset();
      const id = row.id || this.ids;
      this.tableId = id;
      getReporting(id).then((response) => {
        response.data.reportingDetails.map((item) => {
          item.drugsType = String(item.drugsType);
          item.packingUnit = String(item.packingUnit);
        });
        this.form = response.data;
        this.reportingDetails = response.data.reportingDetails;
        /*this.reportingDetails &&
          this.reportingDetails.forEach((item, index) => {
            this.getListSpecs(item.drugsId, index);
            this.getListPrice(item.specsId, index);
          });*/
        this.open = true;
        this.now = Date.now()
        // this.title = "修改报损单";
        num == 3
          ? ((this.title = "详情报损单"), (this.disableDetails = true))
          : num == 1
          ? ((this.title = "修改报损单"), (this.disableDetails = false))
          : num == 2
          ? ((this.title = "记账报损单"), (this.disableDetails = true))
          : "";
      });
    },
    /** 记账 **/
    handleUpdataKeeping() {
      updataKeeping(this.tableId).then((res) => {
        this.msgSuccess("记账成功");
        this.open = false;
        this.getList();
      });
    },
    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) {
          this.form.reportingDetails = this.reportingDetails;
          // 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;

          if (this.form.id != null) {
            updateReporting(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReporting(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 delReporting(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 报损单详情序号 */
    rowReportingDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 报损单详情添加按钮操作 */
    handleAddReportingDetail() {
      let obj = {};
      obj.drugsId = "";
      obj.specsId = "";
      obj.priceId = "";
      obj.stock = "";
      obj.reportingNum = "";
      obj.purchasePrice = "";
      obj.retailPrice = "";
      obj.approvalCode = "";
      obj.site = "";
      obj.productionCode = "";
      obj.validTime = "";
      this.reportingDetails.push(obj);
    },
    /** 报损单详情删除按钮操作 */
    handleDeleteReportingDetail() {
      if (this.checkedReportingDetail.length == 0) {
        this.msgError("请先选择要删除的报损单详情数据");
      } else {
        const reportingDetails = this.reportingDetails;
        const checkedReportingDetail = this.checkedReportingDetail;
        this.reportingDetails = reportingDetails.filter(function (item) {
          return checkedReportingDetail.indexOf(item.index) == -1;
        });
      }
    },
    /** 复选框选中数据 */
    handleReportingDetailSelectionChange(selection) {
      this.checkedReportingDetail = selection.map((item) => item.index);
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有报损单数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportReporting(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>
