<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
          size="mini"
          :disabled="multiple"
          @click="batch()">批次调整
        </el-button>
      </el-col>


      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          :disabled="multiple"
          @click="dateAdjustment()">生成日期调整
        </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="goodsName"/>
      <el-table-column label="子需求编号" align="center" prop="salesOrderNumber"/>
      <el-table-column label="生产批号" align="center" prop="batchNo"/>
      <el-table-column label="生产日期" align="center" prop="productionDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改前生产批号" align="center" prop="noup">
        <template slot-scope="scope">
          <span style="color: #0379ee;">{{ scope.row.noup }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改前生产日期" align="center" prop="dates" width="180">
        <template slot-scope="scope">
          <span style="color: #0379ee;">{{ parseTime(scope.row.dates, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
        <span :style="{ color: scope.row.status === '1' ? 'red' : 'green' }">
          {{ scope.row.status === '1' ? '冻结' : '未冻结' }}
        </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" round size="mini" icon="el-icon-edit"
                     @click="singleModification(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 :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="生产批号" prop="batchNo">
          <el-input v-model="form.batchNo" placeholder="请输入生产批号"/>
        </el-form-item>
        <el-form-item label="生产日期" prop="productionDate">
          <el-date-picker clearable v-model="form.productionDate" type="date" value-format="yyyy-MM-dd"
                          placeholder="请选择生产日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="title" :visible.sync="dateOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="生产日期" prop="productionDate">
          <el-date-picker clearable v-model="form.productionDate" type="date" value-format="yyyy-MM-dd"
                          placeholder="请选择生产日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import {listStock, update, getStock, updateStock, updateDate} from "@/api/system/batchAdjustment";
import {listWarehouse} from "@/api/system/freeze";


export default {
  name: "Stock",
  data() {
    return {
      options: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存表格数据
      stockList: [],
      //原始数据
      originalData:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      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: {},
      dateOpen: false,
      // 表单校验
      rules: {
        batchNo: [
          {required: true, message: '请输入生产批号', trigger: 'blur'},
          {pattern: /^[A-Za-z0-9]+$/, message: '生产批号只能包含字母和数字', trigger: 'blur'}
        ]
      }
    };
  },
  created() {
    debugger
    this.getList();
    this.getWarehouse();
  },
  methods: {
    /** 查询库存列表 */
    // 获取数据并初始化
    getList() {
      this.loading = true;
      listStock(this.queryParams).then(response => {
        const newData = response.rows;
        let previousData = localStorage.getItem('previousData');
        if (!previousData) {
          // 如果没有先前的数据，初始化并保存当前数据作为下一次的“修改前”数据
          localStorage.setItem('previousData', JSON.stringify(newData));
          previousData = newData;
        } else {
          // 如果已经有先前的数据，使用 localStorage 中的数据作为“修改前”数据
          previousData = JSON.parse(previousData);
        }
        // 更新 localStorage 为当前数据，供下一次使用
        localStorage.setItem('previousData', JSON.stringify(newData));
        // 使用先前的数据来设置 stockList
        this.stockList = newData.map(item => {
          const prevItem = previousData.find(prev => prev.id === item.id) || item;
          return {
            ...item,
            noup: prevItem.batchNo,  // 使用修改前的生产批号
            dates: prevItem.productionDate  // 使用修改前的生产日期
          };
        });
        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)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /*批量批次调整*/
    batch() {
      this.$prompt('请输入批次号', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[A-Za-z0-9]+$/,
        inputErrorMessage: '批次号格式不正确'
      }).then(({value}) => {
        this.$modal.confirm('是否确认修改选择的数据项的批次号').then(() => {
          return update(this.ids, value);
        }).then(() => {
          console.log("修改成功");  // 添加日志信息
          this.getList();
          this.$modal.msgSuccess("修改成功");
        }).catch((error) => {
          this.$message.error("修改失败");
        });
      }).catch((error) => {
        console.log("操作取消或输入不符合要求", error);
        this.$message({
          type: 'info',
          message: '操作取消或输入不符合要求'
        });
      });
    },

    /*单独修改*/
    singleModification(row) {
      this.open = true
      this.reset();
      const stockId = row.id || this.ids
      getStock(stockId).then(response => {
        this.form = response.data;

        this.form.productionDate = new Date(this.form.productionDate);
        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 {
          this.$modal.msgWarning("请输入正确的批次号");
          return false
        }
      });
    },

    /*生成日期调整*/
    dateAdjustment() {
      this.dateOpen = true
      this.title = '生产日期调整'
    },
    submit() {
      this.dateOpen = false
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$modal.confirm('是否确认修改选择的数据项的生产日期？').then(() => {
            return updateDate(this.ids, this.form.productionDate);
          }).then(() => {
            console.log("修改成功");  // 添加日志信息
            this.getList();
            this.$modal.msgSuccess("修改成功");
          }).catch((error) => {
            this.$message.error("修改失败");
          });
        } else {
          this.$modal.msgWarning("请输入正确的批次号");
          return false
        }
      });

    },



  }
};
</script>
