<template>
  <div class="settings">
    <el-card>
      <template slot="header">
        <div class="card-header">
          <span>分析设置（生命周期/LSTM权重）</span>
          <div class="header-actions">
            <el-button size="small" @click="resetToDefault" :disabled="!hasDefaults">恢复默认</el-button>
            <el-button type="primary" size="small" @click="save" :loading="saving">保存</el-button>
          </div>
        </div>
      </template>

      <el-form label-width="220px">
        <el-form-item label="生命周期-销售增长权重">
          <el-slider v-model="weights.sales_growth_weight" :min="0" :max="1" :step="0.05" :format-tooltip="formatTooltip" />
        </el-form-item>
        <el-form-item label="生命周期-库存波动权重">
          <el-slider v-model="weights.inventory_variance_weight" :min="0" :max="1" :step="0.05" :format-tooltip="formatTooltip" />
        </el-form-item>
        <el-form-item label="生命周期-周转率权重">
          <el-slider v-model="weights.turnover_weight" :min="0" :max="1" :step="0.05" :format-tooltip="formatTooltip" />
        </el-form-item>
        <el-form-item label="生命周期-状态信号权重">
          <el-slider v-model="weights.state_signal_weight" :min="0" :max="1" :step="0.05" :format-tooltip="formatTooltip" />
        </el-form-item>
        <el-form-item label="生命周期滑动窗口(天)">
          <el-input-number v-model="weights.lifecycle_window_days" :min="7" :max="60" />
        </el-form-item>

        <el-divider />

        <el-form-item label="LSTM特征-库存权重">
          <el-slider v-model="weights.feature_inventory_weight" :min="0" :max="1" :step="0.05" :format-tooltip="formatTooltip" />
        </el-form-item>
        <el-form-item label="LSTM特征-销量权重">
          <el-slider v-model="weights.feature_sales_weight" :min="0" :max="1" :step="0.05" :format-tooltip="formatTooltip" />
        </el-form-item>
        <el-form-item label="LSTM特征-入库权重">
          <el-slider v-model="weights.feature_purchase_weight" :min="0" :max="1" :step="0.05" :format-tooltip="formatTooltip" />
        </el-form-item>
        <el-form-item label="LSTM特征-净流量权重">
          <el-slider v-model="weights.feature_net_flow_weight" :min="0" :max="1" :step="0.05" :format-tooltip="formatTooltip" />
        </el-form-item>
        <el-form-item label="LSTM特征-稳定偏差权重">
          <el-slider v-model="weights.feature_stable_gap_weight" :min="0" :max="1" :step="0.05" :format-tooltip="formatTooltip" />
        </el-form-item>

        <el-divider />

        <el-form-item label="库存状态-低库存权重">
          <el-slider v-model="weights.state_low_weight" :min="0" :max="1" :step="0.05" :format-tooltip="formatTooltip" />
        </el-form-item>
        <el-form-item label="库存状态-超储权重">
          <el-slider v-model="weights.state_overstock_weight" :min="0" :max="1" :step="0.05" :format-tooltip="formatTooltip" />
        </el-form-item>
        <el-form-item label="库存状态-慢动/滞销权重">
          <el-slider v-model="weights.state_slow_weight" :min="0" :max="1" :step="0.05" :format-tooltip="formatTooltip" />
        </el-form-item>
        <el-form-item label="库存状态-需求峰值权重">
          <el-slider v-model="weights.state_spike_weight" :min="0" :max="1" :step="0.05" :format-tooltip="formatTooltip" />
        </el-form-item>
        <el-form-item label="库存状态-正常权重">
          <el-slider v-model="weights.state_normal_weight" :min="0" :max="1" :step="0.05" :format-tooltip="formatTooltip" />
        </el-form-item>

        <el-divider />

        <el-form-item label="稳定库存窗口天数">
          <el-input-number v-model="weights.stable_window_days" :min="7" :max="180" />
        </el-form-item>
        <el-form-item label="预测净流趋势权重">
          <el-slider v-model="weights.forecast_drift_weight" :min="0" :max="0.5" :step="0.01" :format-tooltip="formatTooltip" />
        </el-form-item>

        <el-divider />
        <h4 style="margin: 10px 0;">风险评分权重（总计100）</h4>
        <el-form-item label="覆盖评分权重">
          <el-input-number v-model="riskWeights.coverageWeight" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="周转评分权重">
          <el-input-number v-model="riskWeights.turnoverWeight" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="趋势评分权重">
          <el-input-number v-model="riskWeights.trendWeight" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="资金评分权重">
          <el-input-number v-model="riskWeights.capitalWeight" :min="0" :max="100" />
        </el-form-item>
        <div style="text-align:right;color:#909399">当前合计：{{ riskTotalWeight }} / 100</div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'
import { Message } from 'element-ui'

export default {
  name: 'StorageSettings',
  data() {
    return {
      weights: {
        sales_growth_weight: 0.35,
        inventory_variance_weight: 0.25,
        turnover_weight: 0.2,
        state_signal_weight: 0.3,
        lifecycle_window_days: 14,
        feature_inventory_weight: 0.4,
        feature_sales_weight: 0.25,
        feature_purchase_weight: 0.15,
        feature_net_flow_weight: 0.1,
        feature_stable_gap_weight: 0.1,
        state_low_weight: 0.3,
        state_overstock_weight: 0.3,
        state_slow_weight: 0.2,
        state_spike_weight: 0.15,
        state_normal_weight: 0.1,
        stable_window_days: 60,
        forecast_drift_weight: 0.15
      },
      saving: false,
      riskWeights: {
        coverageWeight: 40,
        turnoverWeight: 30,
        trendWeight: 20,
        capitalWeight: 10
      },
      defaultWeights: {},
      defaultRiskWeights: {}
    }
  },
  computed: {
    hasDefaults() {
      return Object.keys(this.defaultWeights).length > 0 || Object.keys(this.defaultRiskWeights).length > 0
    },
    riskTotalWeight() {
      return ['coverageWeight', 'turnoverWeight', 'trendWeight', 'capitalWeight']
        .map(k => Number(this.riskWeights[k] || 0))
        .reduce((a, b) => a + b, 0)
    }
  },
  mounted() {
    this.load()
  },
  methods: {
    formatTooltip(value) {
      return Number(value).toFixed(2)
    },
    async load() {
      try {
        const [invPayload, riskPayload] = await Promise.all([
          request({ url: '/api/inventory/settings', method: 'get' }),
          request({ url: '/api/risk/settings', method: 'get' })
        ])
        if (invPayload && invPayload.code === 200) {
          if (invPayload.data) this.weights = { ...this.weights, ...invPayload.data }
          if (invPayload.defaults) this.defaultWeights = invPayload.defaults
        }
        if (riskPayload && riskPayload.code === 200) {
          if (riskPayload.data) this.riskWeights = { ...this.riskWeights, ...riskPayload.data }
          if (riskPayload.defaults) this.defaultRiskWeights = riskPayload.defaults
        }
      } catch (e) {
        Message.error('加载设置失败')
      }
    },
    async save() {
      this.saving = true
      try {
        const [invUpdated, riskUpdated] = await Promise.all([
          request({ url: '/api/inventory/settings', method: 'post', data: this.weights }),
          request({ url: '/api/risk/settings', method: 'post', data: this.riskWeights })
        ])
        if ((invUpdated && invUpdated.code === 200) || (riskUpdated && riskUpdated.code === 200)) {
          Message.success('设置已保存')
        }
      } catch (e) {
        Message.error('保存失败')
      } finally {
        this.saving = false
      }
    },
    resetToDefault() {
      if (!this.hasDefaults) return
      if (Object.keys(this.defaultWeights).length) {
        this.weights = { ...this.weights, ...this.defaultWeights }
      }
      if (Object.keys(this.defaultRiskWeights).length) {
        this.riskWeights = { ...this.riskWeights, ...this.defaultRiskWeights }
      }
      Message.success('已恢复默认权重')
    }
  }
}
</script>

<style scoped>
.settings {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}
</style>
