<template>
  <div v-if="visible" class="forecast-form-container">

    <!-- 销售预测表单容器 - AvueJS版本 -->
    <div class="forecast-form-container basic-container">
      <!-- 表单内容区域 -->
      <div class="forecast-form-content">
        <avue-form
          ref="forecastForm"
          v-model="formData"
          :option="formOption"
          @submit="handleSubmit"
          @reset-change="handleReset"
        >
          <!-- 客户选择器插槽 -->
          <template #customerId>
            <customer-select
              v-model="formData.customerId"
              placeholder="请选择客户"
              @customer-selected="handleCustomerSelected"
            />
          </template>

          <!-- 预测年份插槽（使用 $refs.yearPicker 控制禁用） -->
          <template #year>
            <el-date-picker
              ref="yearPicker"
              v-model="formData.year"
              type="year"
              value-format="yyyy"
              placeholder="请选择年份"
              style="width: 100%"
              :disabled="isEdit"
            />
          </template>

          <!-- 预测月份插槽（使用 $refs.monthSelect 控制禁用） -->
          <template #month="{ column }">
            <el-select
              ref="monthSelect"
              v-model="formData.month"
              placeholder="请选择月份"
              style="width: 100%"
              :disabled="isEdit"
            >
              <el-option
                v-for="opt in (column && column.dicData) ? column.dicData : []"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
              />
            </el-select>
          </template>
        </avue-form>

        <!-- 物料表格区域 -->
        <div class="forecast-goods-table">
          <div class="table-title">物料列表</div>
          <!-- 选择并导入物料工具栏 -->
          <div class="table-toolbar">
            <el-select
              v-model="selectedStockId"
              filterable
              clearable
              :disabled="stockSelectOptions.length === 0"
              placeholder="物料名称"
              style="width: 360px"
            >
              <el-option
                v-for="opt in stockSelectOptions"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
              />
            </el-select>
            <el-button
              type="primary"
              :disabled="!selectedStockId"
              style="margin-left: 8px"
              @click="handleImportSelectedStock"
            >添加物料</el-button>
            <!-- 批量删除按钮：始终展示，无选中或加载中禁用 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              :disabled="tableLoading || !hasSelection"
              style="margin-left: 8px"
              @click="handleBatchDelete"
            >批量删除</el-button>
          </div>

          <el-table
            ref="stockTable"
            :data="pagedStockTableData"
            border
            stripe
            height="360"
            v-loading="tableLoading"
            :row-key="getRowUniqueKey"
            :reserve-selection="true"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="48" />
            <el-table-column prop="code" label="物料编码" min-width="140" show-overflow-tooltip />
            <el-table-column prop="cname" label="物料名称" min-width="160" show-overflow-tooltip />
            <el-table-column prop="brandName" label="品牌名称" min-width="120" show-overflow-tooltip />
            <el-table-column prop="typeNo" label="规格" min-width="120" show-overflow-tooltip />
            <el-table-column prop="storeInventory" label="库存数量" min-width="120">
              <template #default="{ row }">
                <span>{{ parseInt(row.storeInventory || 0) }}</span>
              </template>
            </el-table-column>
            <!-- Removed specs/description column: productDescription -->
            <el-table-column label="预测数量" min-width="140">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.forecastQuantity"
                  :min="0"
                  :max="999999"
                  :step="1"
                  controls-position="right"
                  style="width: 120px"
                />
              </template>
            </el-table-column>
            <!-- 操作列：删除按钮 -->
            <el-table-column label="操作" fixed="right" width="120">
              <template #default="{ row, $index }">
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-delete"
                  @click="handleDelete(row, $index)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页控件（前端分页） -->
          <div class="table-pagination" style="margin-top: 8px; text-align: right;">
            <el-pagination
              :current-page="currentPage"
              :page-size="pageSize"
              :page-sizes="[5, 10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="handlePageChange"
              @size-change="handleSizeChange"
            />
          </div>

          <div class="table-tip">提示：先在上方选择物料并点击“导入物料”，导入后的数据将显示在表格并参与保存流程。</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import forecastFormMixin from './forecast-form-mixin.js'
import CustomerSelect from '@/components/common/customer-select.vue'

/**
 * 销售预测表单组件实例类型定义
 * @typedef {object} ForecastFormAvueComponent
 * @property {import('./types').ForecastFormModel} formData - 表单数据
 * @property {import('./types').FormOption} formOption - 表单配置选项
 * @property {boolean} saveLoading - 保存加载状态
 * @property {import('./types').CustomerOption[]} customerOptions - 客户选项列表
 * @property {number|null} currentInventory - 当前库存数量
 * @property {import('./types').ApprovalStatusOption[]} approvalStatusOptions - 审批状态选项
 * @property {import('./types').ForecastFormRules} formRules - 表单验证规则
 * @property {boolean} visible - 表单可见性
 * @property {boolean} isEdit - 是否为编辑模式
 * @property {Object|null} editData - 编辑数据
 * @property {Object|null} initialFormData - 初始表单数据
 * @property {string} title - 表单标题
 * @property {string} forecastId - 预测ID
 */

/**
 * 销售预测表单组件 - AvueJS版本
 * @description 基于AvueJS的销售预测表单组件，支持新增和编辑销售预测功能
 */
export default {
  name: 'ForecastFormAvue',
  mixins: [forecastFormMixin],

  /**
   * 组件注册
   */
  components: {
    CustomerSelect
  },

  /**
   * @this {import('./types').ForecastFormMixinComponent & Vue}
   */
  mounted() {
    // 在编辑态，初始禁用“年份/月份”两个控件（通过 $refs 设置）
    this.$nextTick(() => {
      try {
        if (this.isEdit) {
          if (this.$refs.yearPicker) { /** @type {any} */ (this.$refs.yearPicker).disabled = true }
          if (this.$refs.monthSelect) { /** @type {any} */ (this.$refs.monthSelect).disabled = true }
        }
      } catch (e) {
        // 忽略可能的非关键性异常
      }
    })
  },

  methods: {
    // 通过 $refs 统一设置“年份/月份”的禁用状态
    /** @param {boolean} disabled */
    setYearMonthDisabled(disabled) {
      this.$nextTick(() => {
        try {
          if (this.$refs.yearPicker) { /** @type {any} */ (this.$refs.yearPicker).disabled = disabled }
          if (this.$refs.monthSelect) { /** @type {any} */ (this.$refs.monthSelect).disabled = disabled }
        } catch (e) {
          // 忽略可能的非关键性异常
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import './index.scss';

.forecast-goods-table {
  margin-top: 12px;
}
.table-title {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}
.table-toolbar {
  margin-bottom: 8px;
}
.table-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}
</style>
