<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="仓库名称" prop="storageId">
        <el-select v-model="queryParams.storageId" placeholder="请选择仓库名称">
          <el-option
            v-for="item in options"
            :key="item.storageId"
            :label="item.storageName"
            :value="item.storageId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="库区编号" prop="storageAreaId">
        <el-input
          v-model="queryParams.storageAreaId"
          placeholder="请输入库区编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="库位编号" prop="locationId">
        <el-input
          v-model="queryParams.locationId"
          placeholder="请输入库位编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料编号" prop="locationId">
        <el-input
          v-model="queryParams.goodsId"
          placeholder="请输入物料编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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-form-item>
    </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="['system:stock:add']"
          >新增</el-button
        >
      </el-col> -->

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          size="mini"
          @click="frozen"
          :disabled="freeze"
          >冻结</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          size="mini"
          @click="thaw"
          :disabled="unFreeze"
          >解冻</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="stockList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="库存编号" align="center" prop="id" />
      <el-table-column label="仓库编号" align="center" prop="storageId" />
      <el-table-column label="仓库名称" align="center" prop="storageShortName"/>
      <!-- <el-table-column label="库区编号" align="center" prop="storageAreaId" /> -->
      <el-table-column label="库位编号" align="center" prop="locationId" />
      <el-table-column label="物料编号" align="center" prop="goodsId" />
      <el-table-column label="托盘号" align="center" prop="ctl" />
      <!-- <el-table-column label="冻结数量" align="center" prop="occupyNum" /> -->
      <el-table-column
        label="上架日期"
        align="center"
        prop="wareDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.wareDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="单据编号" align="center" prop="doctNumber" /> -->
      <el-table-column label="物料名称" align="center" prop="goodsName" />
      <el-table-column prop="isFreeze" label="状态" align="center">
        <template slot-scope="scope">
          <span
            :style="{ color: scope.row.isFreeze === '1' ? 'red' : 'green' }"
          >
            <dict-tag
              :options="dict.type.is_freeze"
              :value="scope.row.isFreeze"
            />
          </span>
        </template>
      </el-table-column>


<!--      <el-table-column prop="status" label="锁定" align="center">
        <template slot-scope="scope">
          <span
            :style="{ color: scope.row.status === '1' ? 'red' : 'green' }"
          >
            <dict-tag
              :options="dict.type.is_freeze"
              :value="scope.row.is_freeze"
            />
          </span>
        </template>
      </el-table-column>-->

      <el-table-column label="生产批号" align="center" prop="batchNo" />
      <el-table-column label="冻结原因" align="center" prop="consignment" />
      <el-table-column label="冻结人" align="center" prop="frostMan" />
      <el-table-column label="仓库名称" align="center" prop="storageShortName" />

      <!-- <el-table-column
        label="过期时间"
        align="center"
        prop="dueDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dueDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column> -->

<!--      <el-table-column
        label="子需求编号"
        align="center"
        prop="salesOrderNumber"
      />-->
      <!-- <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:stock: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"
    />
  </div>
</template>

<script>
import {
  listStock,
  getStock,
  addStock,
  updateStock,
  frozen,
  thaw,
} from "@/api/system/freeze";
import { listWarehouse } from "@/api/system/freeze";

export default {
  name: "Stock",
  dicts: ["is_freeze"],
  data() {
    return {
      options: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存表格数据
      stockList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      freeze: true,
      unFreeze: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        storageId: null,
        storageAreaId: null,
        locationId: null,
        goodsId: null,
        shelvesNum: null,
        version: null,
        storageMode: null,
        providerId: null,
        productionDate: null,
        wareDate: null,
        doctNumber: null,
        goodsVolume: null,
        occupyNum: null,
        noticeId: null,
        oriBill: null,
        ctl: null,
        barcode: null,
        wgh: null,
        high: null,
        goodsName: null,
        status: null,
        customerId: null,
        batchNo: null,
        dueDate: null,
        checkDate: null,
        standard: null,
        flag: null,
        mark: null,
        orderNum: null,
        problem: null,
        price: null,
        packingNum: null,
        boxType: null,
        scaleUnit: null,
        goodsSku: null,
        factoryId: null,
        salesOrderNo: null,
        salesOrderNumber: null,
        supplier: null,
        onOrder: null,
        recordPerson: null,
        lotId: null,
        decid: null,
        unit: null,
        specification: null,
        goodsAge: null,
        arraMount: null,
        recoil: null,
        operatorId: null,
        operateDate: null,
        purchaseId: null,
        applicant: null,
        respDept: null,
        planDate: null,
        planTime: null,
        needCycle: null,
        needType: null,
        goodsTypeId: null,
        brand: null,
        totalMoney: null,
        expiryDate: null,
        providerName: null,
        receiver: null,
        needDept: null,
        purchaseDept: null,
        produclotId: null,
        receiverDept: null,
        receivingArea: null,
        packageId: null,
        useType: null,
        telephone: null,
        totalVolume: null,
        totalRoughWeight: null,
        totalNetWeigh: null,
        defaultStorageAreaId: null,
        qualityInspecStatus: null,
        periodUnit: null,
        period: null,
        reportTime: null,
        consignment: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
    this.getWarehouse();
  },
  methods: {
    /** 查询库存列表 */
    getList() {
      this.loading = true;
      listStock(this.queryParams).then((response) => {
        this.stockList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /*仓库查询*/
    getWarehouse() {
      listWarehouse(this.queryParams).then((response) => {
        this.options = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        storageId: null,
        storageAreaId: null,
        locationId: null,
        goodsId: null,
        shelvesNum: null,
        remark: null,
        version: null,
        storageMode: null,
        providerId: null,
        productionDate: null,
        wareDate: null,
        doctNumber: null,
        goodsVolume: null,
        occupyNum: null,
        noticeId: null,
        oriBill: null,
        ctl: null,
        barcode: null,
        wgh: null,
        high: null,
        goodsName: null,
        status: null,
        customerId: null,
        batchNo: null,
        dueDate: null,
        checkDate: null,
        standard: null,
        flag: null,
        mark: null,
        orderNum: null,
        problem: null,
        price: null,
        packingNum: null,
        boxType: null,
        scaleUnit: null,
        goodsSku: null,
        factoryId: null,
        salesOrderNo: null,
        salesOrderNumber: null,
        supplier: null,
        onOrder: null,
        recordPerson: null,
        lotId: null,
        decid: null,
        unit: null,
        specification: null,
        goodsAge: null,
        arraMount: null,
        recoil: null,
        operatorId: null,
        operateDate: null,
        purchaseId: null,
        applicant: null,
        respDept: null,
        planDate: null,
        planTime: null,
        needCycle: null,
        needType: null,
        goodsTypeId: null,
        brand: null,
        totalMoney: null,
        expiryDate: null,
        providerName: null,
        receiver: null,
        needDept: null,
        purchaseDept: null,
        produclotId: null,
        receiverDept: null,
        receivingArea: null,
        packageId: null,
        useType: null,
        telephone: null,
        totalVolume: null,
        totalRoughWeight: null,
        totalNetWeigh: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        defaultStorageAreaId: null,
        qualityInspecStatus: null,
        periodUnit: null,
        period: null,
        reportTime: null,
        consignment: null,
      };
      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);

      // let filteredData = this.stockList.filter((item) =>
      //   this.ids.find((element) => element === item.id)
      // );

      let freezeSize = selection.filter((s) => s.isFreeze == "0");
      let unFreezeSize = selection.filter((s) => s.isFreeze == "1");

      if (selection.length > 0 && freezeSize.length == selection.length) {
        // console.log(freezeSize);
        this.freeze = false;
      } else {
        this.freeze = true;
      }

      if (selection.length > 0 && unFreezeSize.length == selection.length) {
        // console.log(unFreezeSize);
        this.unFreeze = false;
      } else {
        this.unFreeze = true;
      }

      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加库存";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const stockId = row.id || this.ids;
      getStock(stockId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改库存";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateStock(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStock(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 冻结解冻 */
    handleDelete(row) {
      const stockIds = row.id || this.ids;
      if (row.isFreeze === "0") {
        this.$modal
          .prompt("请输入冻结原因", {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          })
          .then(({ value }) => {
            if (!value) throw new Error("需要输入冻结原因");
            return this.$modal.confirm(`是否确认冻结选中的库存项，冻结原因为：${value}`);
          })
          .then(() => {
            return frozen(stockIds);
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("冻结成功");
          })
          .catch(() => {});
      } else if (row.status === "1") {
        this.$modal
          .confirm('是否确认解冻库存编号为"' + stockIds + '"的数据项？')
          .then(function () {
            return thaw(stockIds);
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("解冻成功");
          })
          .catch(() => {});
      }
    },

    frozen(row) {
      const stockIds = row.id || this.ids;
      let reason; // 定义一个变量来存储冻结原因
      this.$modal
        .prompt("请输入冻结原因", {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        })
        .then(({ value }) => {
          if (!value) throw new Error("需要输入冻结原因");
          reason = value; // 存储冻结原因到更高作用域的变量
          return this.$modal.confirm(`是否确认冻结选中的库存项，冻结原因为：${value}`);
        })
        .then(() => {
          // 在这里传递 value 变量
          return frozen(stockIds, reason);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("冻结成功");
        })
        .catch((error) => {
          // 最好在这里处理错误，而不是忽略它
          console.error(error);
          this.$modal.msgError("冻结失败：" + error.message);
        });
    },

    thaw(row) {
      const stockIds = row.id || this.ids;
      this.$modal
        .confirm("是否确认解冻选中的库存项")
        .then(function () {
          return thaw(stockIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("解冻成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/stock/export",
        {
          ...this.queryParams,
        },
        `stock_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
