<template>
  <div class="app-container">
    <PageTitle>
      <template #buttons>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="medium"
          @click="handleAdd"
          v-hasPermi="['inventory:stocktakes:add']"
        >新增</el-button>
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="medium"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['inventory:stocktakes:remove']"-->
<!--        >删除</el-button>-->
        <el-button
          type="success"
          plain
          icon="el-icon-tickets"
          size="medium"
          @click="handleCount"
          v-hasPermi="['inventory:stocktakes:count']"
        >处理结果统计</el-button>
      </template>
    </PageTitle>
    <div class="page-container">
      <page-wrapper-search
        :model="queryParams"
        ref="queryForm"
        size="small"
        @search="handleQuery"
        @reset="resetQuery"
      >
        <el-form-item label="计划日期">
          <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="盘点状态" prop="stocktakeStatus">
          <el-select v-model="queryParams.stocktakeStatus" placeholder="盘点状态" clearable style="width: 240px">
            <el-option v-for="dict in dict.type.stocktake_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
      </page-wrapper-search>


      <div class="table-container">
      <el-table v-loading="loading" :data="stocktakesList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="id" />
  <!--      <el-table-column label="盘点单号 隐藏，根据id同步生成值" align="center" prop="stocktakeId" />-->
  <!--      <el-table-column label="盘点类型1-全面盘点 2-循环盘点 3-指定物料盘点 暂无用，默认1" align="center" prop="stocktakeType" />-->
  <!--      <el-table-column label="仓库ID 暂无用" align="center" prop="warehouseId" />-->
        <el-table-column label="计划日期" align="center" prop="plannedDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.plannedDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="stocktakeStatus" label="盘点状态" width="80">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.stocktake_status" :value="scope.row.stocktakeStatus"/>
          </template>
        </el-table-column>
  <!--      <el-table-column label="盘点物料范围 暂时无用" align="center" prop="materialRange" />-->
  <!--      <el-table-column label="盘点库位范围 暂时无用" align="center" prop="locationRange" />-->
  <!--      <el-table-column label="总差异金额 暂时无用" align="center" prop="totalVarianceAmount" />-->
        <el-table-column label="备注" align="center" prop="remark" />
  <!--      <el-table-column label="应用数据1使用0删除 删除用" align="center" prop="isUsed" />-->
  <!--      <el-table-column label="排序" align="center" prop="sortNo" />-->
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
  <!--      <el-table-column label="排序号" align="center" prop="updateUserCode" />-->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleViewInfo(scope.row)"
              v-hasPermi="['inventory:stocktakes:query']"
            >查看</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleCheck(scope.row)"
              v-if="scope.row.stocktakeStatus === '1'"
              v-hasPermi="['inventory:stocktakes:check']"
            >盘点</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              v-if="scope.row.stocktakeStatus === '1'"
              @click="handleDelete(scope.row)"
              v-hasPermi="['inventory:stocktakes:remove']"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-circle-check"
              @click="handleConfirm(scope.row)"
              v-if="scope.row.stocktakeStatus === '2'"
              v-hasPermi="['inventory:stocktakes:confirm']"
            >盘点确认</el-button>
          </template>
        </el-table-column>
      </el-table>
      </div>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 添加库存盘点对话框 -->
    <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="plannedDate">
          <el-date-picker clearable
            v-model="form.plannedDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择计划日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </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="checkTitle" :visible.sync="checkOpen" width="1500px" append-to-body>
      <el-form ref="checkFormRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="盘点单号" prop="stocktakeId" >
                  <el-input v-model="form.stocktakeId" placeholder="请输入盘点单号" disabled />
                </el-form-item>
        <el-form-item label="计划日期" prop="plannedDate">
          <el-date-picker clearable disabled
                          v-model="form.plannedDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择计划日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"  disabled />
        </el-form-item>
        <!-- 分割线 -->
        <el-divider content-position="center">盘点单明细信息</el-divider>
        <!-- 引入子表组件（核心：传递数据+监听事件） -->
        <stocktake-items-table
          ref="stocktakeItemsTable"
          :itemsList="stocktakeItemsList"
          :isConfirm="false"
          @item-change="handleStocktakeItemChange"
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCheckForm">确 定</el-button>
        <el-button @click="cancelCheck">取 消</el-button>
      </div>
    </el-dialog>
    <!--    盘点确认弹窗-->
    <el-dialog :title="confirmTitle" :visible.sync="confirmOpen" width="1500px" append-to-body>
      <el-form ref="confirmFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="盘点单号" prop="stocktakeId" >
          <el-input v-model="form.stocktakeId" placeholder="请输入盘点单号" disabled />
        </el-form-item>
        <el-form-item label="计划日期" prop="plannedDate">
          <el-date-picker clearable disabled
                          v-model="form.plannedDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择计划日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"  disabled />
        </el-form-item>
        <!-- 分割线 -->
        <el-divider content-position="center">盘点单明细信息</el-divider>
        <!-- 引入子表组件（核心：传递数据+监听事件） -->
        <stocktake-items-table
          :itemsList="stocktakeItemsList"
          :isConfirm="true"
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary"
                   v-if="this.buttonShow"
                   @click="submitConfirmForm">确 定</el-button>
        <el-button @click="cancelConfirm">取 消</el-button>
      </div>
    </el-dialog>

    <!--    处理统计弹窗-->
    <el-dialog :title="confirmTitle" :visible.sync="countOpen" width="1500px" append-to-body>
      <el-form ref="confirmFormRef" :model="form" :rules="rules" label-width="80px">
        <!-- 引入子表组件（核心：传递数据+监听事件） -->
        <stocktake-count-table/>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelConfirm">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStocktakes, getStocktakes, delStocktakes, addStocktakes, updateStocktakes } from "@/api/inventory/stocktakes"
// 引入子表组件--盘点
import stocktakeItemsTable from '@/views/inventory/stocktakes/stocktakeItemsTable.vue';
// 引入子表组件--统计
import stocktakeCountTable from '@/views/inventory/stocktakes/stocktakeCountTable.vue';
export default {
  name: "Stocktakes",
  dicts: ['stocktake_status'],
  // 注册子组件
  components: { stocktakeItemsTable,stocktakeCountTable },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedStocktakeItems: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存盘点表格数据
      stocktakesList: [],
      // 盘点单明细表格数据
      stocktakeItemsList: [],
      // 弹出层标题
      title: "",
      // 日期范围
      dateRange: [],
      // 是否显示弹出层
      open: false,

      buttonShow: true,//是否展示确认按钮
      checkOpen: false, // 盘点弹窗
      confirmOpen: false, // 盘点确认弹窗
      checkTitle: "库存盘点",
      confirmTitle: "盘点确认",
      countOpen: false, // 盘点统计弹窗

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stocktakeId: null,
        stocktakeType: null,
        warehouseId: null,
        stocktakeStatus: null,
        plannedDate: null,
        materialRange: null,
        locationRange: null,
        totalVarianceAmount: null,
        isUsed: null,
        sortNo: null,
        createUserCode: null,
        updateUserCode: null
      },
      // 表单参数
      form: {
        id: null,
        stocktakeId: null,
        remark: null,
        plannedDate: this.formatCurrentDate()
      },
      // 表单校验
      rules: {
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 格式化当前日期为 yyyy-MM-dd
    formatCurrentDate() {
      const date = new Date();
      const year = date.getFullYear();
      // 月份/日期补 0（确保是两位数，比如 2 月→02，5 日→05）
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    /** 查询库存盘点列表 */
    getList() {
      this.loading = true
      listStocktakes(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.stocktakesList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.checkOpen = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        stocktakeId: null,
        stocktakeType: null,
        warehouseId: null,
        stocktakeStatus: null,
        plannedDate: null,
        materialRange: null,
        locationRange: null,
        totalVarianceAmount: null,
        remark: null,
        isUsed: null,
        sortNo: null,
        createTime: null,
        createUserCode: null,
        updateTime: null,
        updateUserCode: null
      }
      this.stocktakeItemsList = []
      this.resetForm("form")
      this.$refs.formRef && this.$refs.formRef.resetFields();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.stocktakeStatus = null
      this.dateRange = []
      // 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.plannedDate = this.formatCurrentDate() // 重置后重新赋值当前日期
      this.open = true
      this.title = "添加库存盘点"
    },
    /** 盘点按钮操作 */
    handleCheck(row) {
      this.reset();
      const id = row.id || this.ids
      getStocktakes(id,'check').then(response => {
        this.form = response.data
        // 过滤 undefined 行，避免子组件渲染报错
        this.stocktakeItemsList = (response.data.stocktakeItemsList || []).filter(item => item);
        this.checkOpen = true
      })
    },
    // 盘点确认按钮：打开弹窗
    handleConfirm(row) {
      this.reset();
      const id = row.id || this.ids
      this.confirmTitle = '盘点确认'
      getStocktakes(id,'confirm').then(response => {
        this.form = response.data
        // 过滤 undefined 行，避免子组件渲染报错
        this.stocktakeItemsList = (response.data.stocktakeItemsList || []).filter(item => item);
        this.confirmOpen = true;
      })
    },
    // 详情按钮：打开弹窗
    handleViewInfo(row) {
      this.reset();
      const id = row.id || this.ids
      this.buttonShow = false
      this.confirmTitle = '盘点查看'
      getStocktakes(id,'check').then(response => {
        this.form = response.data
        // 过滤 undefined 行，避免子组件渲染报错
        this.stocktakeItemsList = (response.data.stocktakeItemsList || []).filter(item => item);
        this.confirmOpen = true;
      })
    },
    /** 处理结果统计按钮操作 */
    handleCount() {
      this.reset()
      this.countOpen = true
      this.confirmTitle = " 处理结果统计"
    },
    /** 子组件字段编辑事件（确保父组件数据同步） */
    handleStocktakeItemChange(updatedRow) {
      // 找到更新的行，替换数据（确保引用一致）
      const index = this.stocktakeItemsList.findIndex(row => row.id === updatedRow.id);
      if (index !== -1) {
        this.stocktakeItemsList.splice(index, 1, updatedRow);
      }
    },
// 盘点提交：带 operationType=check
    submitCheckForm() {
      this.$refs.checkFormRef.validate(async (valid) => {
        if (valid) {
          // 1. 获取子组件实例
          const subTable = this.$refs.stocktakeItemsTable;
          if (!subTable) {
            this.$modal.msgError("子表组件加载失败，请刷新重试");
            return;
          }

          // 2. 调用子组件的校验方法（检查调整原因必填）
          const isSubValid = subTable.validateSubTable();
          if (!isSubValid) return; // 校验失败直接终止提交

          // 3. 调用子组件的方法获取最新子表数据
          const latestSubTableData = subTable.getSubTableData();
          // 4. 组装提交数据
          const submitData = {
            ...this.form,
            stocktakeItemsList: latestSubTableData, // 子表最新数据（含实时计算的差异量）
            operationType: "check"
          };

          try {
            // 5. 提交接口
            await updateStocktakes(submitData);
            this.$modal.msgSuccess("盘点成功");
            this.checkOpen = false;
            this.getList();
          } catch (err) {
            this.$modal.msgError("盘点失败：" + (err.message || "服务器异常"));
          }
        }
      });
    },

    // 盘点确认提交：带 operationType=confirm
    submitConfirmForm() {
      this.$refs.confirmFormRef.validate(valid => {
        if (valid) {
          const submitData = {
            ...this.form,
            stocktakeItemsList: this.stocktakeItemsList, // 含id，后台用于确认
            operationType: "confirm" // 确认标识
          };
          updateStocktakes(submitData).then(() => {
            this.$modal.msgSuccess("盘点确认成功");
            this.confirmOpen = false;
            this.getList();
          });
        }
      });
    },

    // 取消操作
    cancelCheck() { this.checkOpen = false; this.reset(); },
    cancelConfirm() { this.confirmOpen = false; this.countOpen = false; this.reset(); },

    /** 新增提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.stocktakeItemsList = this.stocktakeItemsList
          if (this.form.id != null) {
            updateStocktakes(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addStocktakes(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除库存盘点编号为"' + ids + '"的数据项？').then(function() {
        return delStocktakes(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
	/** 盘点单明细序号 */
    rowStocktakeItemsIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 盘点单明细添加按钮操作 */
    handleAddStocktakeItems() {
      let obj = {}
      obj.materialId = ""
      obj.batchCode = ""
      obj.warehouseId = ""
      obj.locationId = ""
      obj.systemQuantity = ""
      obj.actualQuantity = ""
      obj.varianceQuantity = ""
      obj.varianceAmount = ""
      obj.stocktakeStatus = ""
      obj.countedBy = ""
      obj.countedAt = ""
      obj.adjusted = ""
      obj.adjustmentReason = ""
      obj.adjustedBy = ""
      obj.adjustedAt = ""
      obj.startTime = ""
      obj.endTime = ""
      obj.materialRange = ""
      obj.locationRange = ""
      obj.remark = ""
      obj.isUsed = ""
      obj.sortNo = ""
      obj.createUserCode = ""
      obj.updateUserCode = ""
      this.stocktakeItemsList.push(obj)
    },
    /** 盘点单明细删除按钮操作 */
    handleDeleteStocktakeItems() {
      if (this.checkedStocktakeItems.length == 0) {
        this.$modal.msgError("请先选择要删除的盘点单明细数据")
      } else {
        const stocktakeItemsList = this.stocktakeItemsList
        const checkedStocktakeItems = this.checkedStocktakeItems
        this.stocktakeItemsList = stocktakeItemsList.filter(function(item) {
          return checkedStocktakeItems.indexOf(item.index) == -1
        })
      }
    },
    /** 复选框选中数据 */
    handleStocktakeItemsSelectionChange(selection) {
      this.checkedStocktakeItems = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('inventory/stocktakes/export', {
        ...this.queryParams
      }, `stocktakes_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
