<template>
  <div class="app-container">
    <div class="btn-condition">
      <div class="condition-left" v-show="showSearch">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
        >
          <el-form-item label="备件序列号" prop="serialNum">
            <el-input
              v-model="queryParams.serialNum"
              placeholder="请输入备件序列号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="备件名称" prop="spareName">
            <el-input
              v-model="queryParams.spareName"
              placeholder="请输入备件名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="操作类型" prop="operaType">
            <el-select
              v-model="queryParams.operaType"
              placeholder="请选择操作类型"
              clearable
            >
              <el-option
                v-for="dict in dict.type.sys_inout_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="日期范围" prop="timeArr">
            <el-date-picker
              style="width: 220px"
              v-model="timeArr"
              type="daterange"
              unlink-panels
              range-separator="~"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              @change="dateChange"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div class="primary-btn">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
        </div>
        <div class="cancel-btn">
          <el-button
            type="cancel"
            icon="el-icon-refresh"
            size="mini"
            @click="resetQuery"
            >重置</el-button
          >
        </div>
      </div>
    </div>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <div class="primary-btn" v-hasPermi="['device:spareInOut:add']">
          <el-button type="primary" size="mini" @click="handleOut"
            ><svg-icon
              icon-class="Outbound"
              style="margin-right: 5px; font-size: 13px"
            />出库</el-button
          >
        </div>
      </el-col>
      <el-col :span="1.5">
        <div class="primary-btn" v-hasPermi="['device:spareInOut:add']">
          <el-button type="primary" size="mini" @click="handleIn"
            ><svg-icon
              icon-class="Inbound"
              style="margin-right: 5px; font-size: 13px"
            />入库</el-button
          >
        </div>
      </el-col>
      <!-- <el-col :span="1.5">
        <div class="warning-btn" v-hasPermi="['system:post:export']">
          <el-button
            type="warning"
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            >导出</el-button
          >
        </div>
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postList" stripe>
      <!-- <el-table-column label="库存备件Id" align="center" prop="sparePartsId" /> -->
      <el-table-column label="备件名称" align="center" prop="spareName" />
      <el-table-column label="出入库操作类型" align="center" prop="operaType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_inout_type"
            :value="scope.row.operaType"
          />
        </template>
      </el-table-column>
      <el-table-column label="出入库量" align="center" prop="intOutNum" />
      <el-table-column label="库存数量" align="center" prop="inventoryLevels" />
      <el-table-column
        label="出入库时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </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 :title="title" :visible.sync="open" append-to-body>
      <el-form ref="form">
        <el-table :data="dialogList">
          <el-table-column label="备件名称" prop="spareName" min-width="200">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.sparePartsId"
                @change="handleSpare(scope.row, scope.row.sparePartsId)"
              >
                <el-option
                  v-for="item in spares"
                  :key="item.id"
                  :label="item.spareName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="数量" min-width="150">
            <template slot-scope="scope">
              <el-input
                placeholder="请填写"
                v-model="scope.row.intOutNum"
                @blur="blurColumn(scope.row, scope.$index)"
                @input="updateNextRowMes(scope.row, scope.$index)"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="当前库存" min-width="150" prop="inventoryLevels">
          </el-table-column>
          <el-table-column prop="data1" label="操作" min-width="130">
            <template slot-scope="scope">
              <div class="table-btn">
                <div class="delete-btn">
                  <el-button
                    size="mini"
                    type="delete"
                    icon="el-icon-delete"
                    @click="delectList(scope.row)"
                    >删除</el-button
                  >
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="success-btn" style="margin-top: 10px">
          <el-button type="success" size="mini" @click="addPriceSet"
            >添加设置</el-button
          >
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { spareInOutList, addSpareInOut } from "@/api/device/spareInOut";
import { spareList } from "@/api/device/spare";
export default {
  name: "spareInOut",
  dicts: ["sys_inout_type"],
  data() {
    return {
      timeArr: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 网关表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serialNum: "",
        spareName: "",
        beginTime: "",
        endTime: "",
        operaType: "",
      },
      dialogList: [], //弹框表格
      sparesList: [], //弹框备件列表
      spares: [],
    };
  },
  created() {
    this.getList();
    this.getSparesList();
  },
  methods: {
    // 选中日期事件
    dateChange() {
      // console.log("打印时间", this.timeArr);
      if (!this.timeArr) {
        this.$nextTick(() => {
          this.timeArr = [];
          this.queryParams.beginTime = "";
          this.queryParams.endTime = "";
        });
      } else {
        this.queryParams.beginTime = this.timeArr[0];
        this.queryParams.endTime = this.timeArr[1];
      }
    },
    /** 查询出入库列表 */
    getList() {
      this.loading = true;
      spareInOutList(this.queryParams).then((response) => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 出库按钮操作 */
    handleOut() {
      this.open = true;
      this.title = "出库";
      this.dialogList = [];
    },
    /** 入库按钮操作 */
    handleIn() {
      this.open = true;
      this.title = "入库";
      this.dialogList = [];
    },
    /** 提交按钮 */
    submitForm: function () {
      console.log("出入库参数", this.dialogList);
      for (const row of this.dialogList) {
        // 检查字段
        const intOutNumValid = this.isValidValue(row.intOutNum);
        // 只要有一个字段无效，就给出错误提示并终止循环
        if (!intOutNumValid) {
          this.$message.warning(`${this.title}数量不能有空值`);
          return;
        }
      }
      addSpareInOut(this.dialogList).then((response) => {
        this.$modal.msgSuccess(`${this.title}成功`);
        this.open = false;
        this.getList();
      });
    },
    // 定义一个函数来检查值是否为有效的数字或非空字符串
    isValidValue(value) {
      if (typeof value === "number" && !isNaN(value)) {
        return true;
      }
      if (typeof value === "string" && value.trim() !== "") {
        return true;
      }
      return false;
    },
    // 取消编辑 column
    blurColumn(row, index) {
      console.log("blurColumn");
      // this.$set(this.dialogList[index], "edit", false);
    },
    // 格式化
    updateNextRowMes(row, index) {
      // row.intOutNum = Number(row.intOutNum);
      if (this.title === "出库" && row.intOutNum > row.inventoryLevels) {
        this.$message.warning("出库数量不能大于库存剩余量");
        row.intOutNum = "";
      }
    },
    // 弹框-表格-删除
    delectList(row) {
      const index = this.dialogList.indexOf(row);
      if (index > -1) {
        // 移除当前行
        this.dialogList.splice(index, 1);
      }
    },
    // 弹框-select选择事件
    handleSpare(row, selectedValue) {
      console.log("当前行", row);
      console.log("当前select选中值", selectedValue);
      // 通过选中的 value 找到对应的 label
      const selectedItem = this.spares.find(
        (item) => item.id === selectedValue
      );
      if (selectedItem) {
        const selectedLabel = selectedItem.spareName;
        console.log("选中的 value:", selectedValue);
        console.log("选中的 label:", selectedLabel);
        // 筛选出符合条件的元素，然后提取 inventoryLevels 值
        const inventoryLevels = this.sparesList
          .filter((item) => item.id === selectedValue)
          .map((item) => item.inventoryLevels);
        // 定义要添加的数据对象
        const newItem = {
          sparePartsId: selectedValue,
          spareName: selectedLabel,
          intOutNum: "",
          inventoryLevels: inventoryLevels[0],
        };
        console.log("this.dialogList", this.dialogList);
        // // 将新数据对象添加到 dialogList 数组中
        // this.dialogList.push(newItem);
        // 直接修改 row 的属性
        row.sparePartsId = newItem.sparePartsId;
        row.spareName = newItem.spareName;
        row.inventoryLevels = newItem.inventoryLevels;
      }
    },
    // 弹框-表格-添加设置
    addPriceSet() {
      let sparePartsId = "";
      let spareName = "";
      let inventoryLevels = "";
      let operaType = "";
      if (this.title === "出库") {
        operaType = 1;
      } else if (this.title === "入库") {
        operaType = 0;
      }
      // 检查 spares 数组是否有元素
      if (this.spares.length > 0) {
        sparePartsId = this.spares[0].id;
        spareName = this.spares[0].spareName;
        inventoryLevels = this.spares[0].inventoryLevels;
      }
      // 定义要添加的数据对象
      const newItem = {
        sparePartsId: sparePartsId,
        spareName: spareName,
        intOutNum: "",
        inventoryLevels: inventoryLevels,
        operaType: operaType,
      };
      // 将新数据对象添加到 dialogList 数组中
      this.dialogList.push(newItem);
    },
    // 获取出入库弹框的的备件列表
    getSparesList() {
      let data = {
        pageNum: 1,
        pageSize: 100000,
      };
      spareList(data).then((response) => {
        this.spares = response.rows;
        this.sparesList = response.rows;
        // 获取到了备件列表后处理值
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "device/gateway/export",
        {
          ...this.queryParams,
        },
        `post_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped lang="scss">
/* 媒体查询，适配大于2000px分辨率的大屏样式 - element样式 */
@media (max-width: 2000px) {
  ::v-deep .el-dialog {
    width: 700px !important;
  }

  ::v-deep .el-dialog .el-form-item__label {
    width: 140px !important;
  }
  ::v-deep .el-dialog .el-form-item {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
}
@media (min-width: 2000px) {
  ::v-deep .el-dialog {
    width: 7.5rem !important;
  }

  ::v-deep .el-dialog .el-form-item__label {
    width: 1.4rem !important;
  }
  ::v-deep .el-dialog .el-form-item {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
}
</style>
