<template>
  <div class="dashboard">
    <section class="hero">
      <div>
        <h1>库存管理系统</h1>
        <p>面向库区、产品、入库、出库和盘库的日常库存作业台。</p>
      </div>
      <el-button type="primary" icon="el-icon-mobile-phone" @click="$router.push('/mobile')">移动端入口</el-button>
    </section>

    <section class="agent-panel">
      <div class="agent-title">
        <div>
          <h2>智能库存助手</h2>
          <p>输入一句话，系统先生成操作草稿，确认后再真正执行。</p>
        </div>
        <el-tag size="small" type="info">第一阶段</el-tag>
      </div>
      <div class="agent-input">
        <el-input
          v-model="agent.text"
          type="textarea"
          :rows="2"
          resize="none"
          maxlength="200"
          show-word-limit
          placeholder="例如：销售出库 10 个某产品，库区 A，出库人张三"
          @keyup.enter.native="analyzeAgentText"
        />
        <el-button icon="el-icon-delete" :disabled="!agent.text && !agent.plan" @click="clearAgent">清空</el-button>
        <el-button type="primary" icon="el-icon-magic-stick" :loading="agent.loading" @click="analyzeAgentText">分析</el-button>
      </div>
      <div v-if="agent.plan" class="agent-result">
        <div class="agent-plan">
          <div>
            <el-tag size="small" :type="agent.plan.executable ? 'success' : 'warning'">{{ actionLabel(agent.plan.action) }}</el-tag>
            <strong>{{ agent.plan.summary || agent.plan.message || '已生成操作草稿' }}</strong>
          </div>
          <el-button
            v-if="agent.plan.needConfirm"
            type="danger"
            size="small"
            icon="el-icon-check"
            :disabled="!agent.plan.executable"
            :loading="agent.executing"
            @click="executeAgentPlan"
          >确认执行</el-button>
        </div>
        <el-descriptions v-if="planItems.length" :column="3" size="small" border>
          <el-descriptions-item v-for="item in planItems" :key="item.label" :label="item.label">{{ item.value }}</el-descriptions-item>
        </el-descriptions>
        <el-alert v-if="agent.plan.message" :title="agent.plan.message" type="info" show-icon :closable="false" />
        <div v-if="agent.plan.warnings && agent.plan.warnings.length" class="agent-warnings">
          <el-tag v-for="item in agent.plan.warnings" :key="item" type="warning" size="small">{{ item }}</el-tag>
        </div>
        <div v-if="agent.plan.candidates && agent.plan.candidates.length" class="agent-candidates">
          <span v-for="item in agent.plan.candidates" :key="item.type + item.id">{{ item.name }} {{ item.detail || '' }}</span>
        </div>
        <el-table v-if="agent.plan.results && agent.plan.results.length" :data="agent.plan.results" size="mini" class="agent-table">
          <el-table-column type="index" label="#" width="54" />
          <el-table-column v-if="canSelectAgentResult(agent.plan)" label="选择" width="86">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" plain @click="selectAgentResult(scope.row)">选择</el-button>
            </template>
          </el-table-column>
          <el-table-column label="库区" prop="areaName" width="120" />
          <el-table-column label="产品" min-width="220">
            <template slot-scope="scope">
              <div class="product-name">{{ scope.row.productName || '-' }}</div>
              <div class="product-meta">{{ productMeta(scope.row) }}</div>
            </template>
          </el-table-column>
          <el-table-column label="库存" prop="stockNum" align="right" width="110" />
        </el-table>
      </div>
    </section>

    <section class="summary-grid">
      <div class="summary-card">
        <span>库存品项</span>
        <strong>{{ summary.stockTotal }}</strong>
      </div>
      <div class="summary-card warning">
        <span>待入库</span>
        <strong>{{ summary.pendingIn }}</strong>
      </div>
      <div class="summary-card danger">
        <span>待盘库确认</span>
        <strong>{{ summary.pendingCheck }}</strong>
      </div>
      <div class="summary-card">
        <span>出库记录</span>
        <strong>{{ summary.outTotal }}</strong>
      </div>
    </section>

    <el-row :gutter="16">
      <el-col :xs="24" :lg="14">
        <el-card shadow="never">
          <div slot="header" class="card-header">
            <span>库存概览</span>
            <el-button type="text" @click="$router.push('/warehouse/stock')">查看全部</el-button>
          </div>
          <el-table :data="stockList" size="small" height="360">
            <el-table-column label="库区" prop="areaName" width="130" />
            <el-table-column label="产品信息" min-width="260">
              <template slot-scope="scope">
                <div class="product-name">{{ scope.row.productName || '-' }}</div>
                <div class="product-meta">{{ productMeta(scope.row) }}</div>
              </template>
            </el-table-column>
            <el-table-column label="库存" prop="stockNum" align="right" width="120" />
          </el-table>
        </el-card>
      </el-col>

      <el-col :xs="24" :lg="10">
        <el-card shadow="never">
          <div slot="header" class="card-header">
            <span>待处理事项</span>
          </div>
          <div class="todo-list">
            <button @click="$router.push('/warehouse/inRecord')">
              <i class="el-icon-bottom-left"></i>
              <span>确认待入库记录</span>
              <strong>{{ summary.pendingIn }}</strong>
            </button>
            <button @click="$router.push('/warehouse/stockCheck')">
              <i class="el-icon-document-checked"></i>
              <span>审核盘库记录</span>
              <strong>{{ summary.pendingCheck }}</strong>
            </button>
            <button @click="$router.push('/warehouse/product')">
              <i class="el-icon-goods"></i>
              <span>维护产品资料</span>
              <strong>产品</strong>
            </button>
            <button @click="$router.push('/warehouse/area')">
              <i class="el-icon-office-building"></i>
              <span>维护库区资料</span>
              <strong>库区</strong>
            </button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listStock } from '@/api/warehouse/stock'
import { listInRecord } from '@/api/warehouse/inRecord'
import { listOutRecord } from '@/api/warehouse/outRecord'
import { listStockCheck } from '@/api/warehouse/stockCheck'
import { analyzeAgent, executeAgent } from '@/api/warehouse/agent'

export default {
  name: 'Index',
  data() {
    return {
      summary: {
        stockTotal: 0,
        pendingIn: 0,
        pendingCheck: 0,
        outTotal: 0
      },
      stockList: [],
      agent: {
        text: '',
        loading: false,
        executing: false,
        contextResults: [],
        plan: null
      }
    }
  },
  computed: {
    planItems() {
      const plan = this.agent.plan
      if (!plan) {
        return []
      }
      return [
        { label: '库区', value: plan.areaName },
        { label: '产品', value: plan.productName },
        { label: '品牌', value: plan.brand },
        { label: '类别', value: plan.category },
        { label: '规格', value: plan.spec },
        { label: '单位', value: plan.unit },
        { label: '数量', value: plan.quantity },
        { label: '操作人', value: plan.operatorName },
        { label: '当前库存', value: plan.currentStock },
        { label: '预计库存', value: plan.afterStock },
        { label: '单号', value: plan.recordNo }
      ].filter(item => item.value !== undefined && item.value !== null && item.value !== '')
    }
  },
  created() {
    this.loadDashboard()
  },
  methods: {
    analyzeAgentText() {
      const text = (this.agent.text || '').trim()
      if (!text) {
        this.$modal.msgWarning('请输入要操作的内容')
        return
      }
      this.agent.loading = true
      analyzeAgent({ text, contextResults: this.agent.contextResults }).then(res => {
        this.agent.plan = res.data
        this.agent.text = ''
        if (res.data && res.data.results && res.data.results.length) {
          this.agent.contextResults = res.data.results
        }
      }).finally(() => {
        this.agent.loading = false
      })
    },
    executeAgentPlan() {
      if (!this.agent.plan || !this.agent.plan.executable) {
        return
      }
      this.agent.executing = true
      executeAgent({ plan: this.agent.plan }).then(res => {
        this.agent.plan = res.data
        this.$modal.msgSuccess(res.data.message || '操作完成')
        this.loadDashboard()
        this.agent.text = ''
      }).finally(() => {
        this.agent.executing = false
      })
    },
    clearAgent() {
      this.agent.text = ''
      this.agent.plan = null
    },
    canSelectAgentResult(plan) {
      return plan && ['create_out_record', 'create_in_record', 'create_stock_check'].includes(plan.action) && plan.results && plan.results.length
    },
    selectAgentResult(item) {
      if (!this.agent.plan || !item) {
        return
      }
      const plan = this.completePlanWithResult(this.agent.plan, item)
      this.agent.plan = plan
      this.agent.contextResults = [item]
      this.$modal.msgSuccess('已选择：' + (item.productName || '库存项'))
    },
    completePlanWithResult(source, item) {
      const plan = Object.assign({}, source, {
        stockId: item.id,
        areaId: item.areaId,
        productId: item.productId,
        areaName: item.areaName,
        productName: item.productName,
        brand: item.brand,
        category: item.category,
        spec: item.spec,
        unit: item.unit,
        currentStock: item.stockNum,
        candidates: [],
        results: [],
        needConfirm: true,
        message: '已选择产品，请确认后执行'
      })
      const quantity = this.toNumber(plan.quantity)
      const stock = this.toNumber(item.stockNum)
      if (plan.action === 'create_out_record') {
        plan.executable = !!(plan.areaId && plan.productId && quantity > 0)
        plan.afterStock = quantity > 0 && item.stockNum !== undefined && item.stockNum !== null ? stock - quantity : undefined
        if (plan.executable && stock < quantity) {
          plan.executable = false
          plan.message = '库存不足，当前库存：' + item.stockNum
        }
      } else if (plan.action === 'create_in_record') {
        plan.executable = !!(plan.areaId && plan.productId && quantity > 0)
        plan.afterStock = quantity > 0 && item.stockNum !== undefined && item.stockNum !== null ? stock + quantity : undefined
      } else if (plan.action === 'create_stock_check') {
        plan.executable = !!(plan.areaId && plan.productId && quantity >= 0)
        plan.afterStock = quantity >= 0 ? quantity : undefined
      }
      if (!plan.executable && plan.message === '已选择产品，请确认后执行') {
        plan.message = '已选择产品，还缺少库区或数量'
      }
      return plan
    },
    toNumber(value) {
      const numberValue = Number(value)
      return Number.isFinite(numberValue) ? numberValue : 0
    },
    actionLabel(action) {
      const map = {
        query_stock: '查询库存',
        create_in_record: '入库登记',
        confirm_in_record: '确认入库',
        create_out_record: '出库',
        create_stock_check: '盘库登记',
        create_product: '新增产品',
        create_area: '新增库区'
      }
      return map[action] || '未识别'
    },
    loadDashboard() {
      listStock({ pageNum: 1, pageSize: 8 }).then(res => {
        this.stockList = res.rows || []
        this.summary.stockTotal = res.total || 0
      })
      listInRecord({ pageNum: 1, pageSize: 1, inStatus: 0 }).then(res => {
        this.summary.pendingIn = res.total || 0
      })
      listStockCheck({ pageNum: 1, pageSize: 1, checkStatus: 0 }).then(res => {
        this.summary.pendingCheck = res.total || 0
      })
      listOutRecord({ pageNum: 1, pageSize: 1 }).then(res => {
        this.summary.outTotal = res.total || 0
      })
    },
    productMeta(row) {
      return [row.brand && '品牌：' + row.brand, row.category && '类别：' + row.category, row.spec && '规格：' + row.spec, row.unit && '单位：' + row.unit].filter(Boolean).join('  ')
    }
  }
}
</script>

<style scoped lang="scss">
.dashboard {
  padding: 18px;
}
.hero {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 16px;
  padding: 22px 24px;
  background: #ffffff;
  border: 1px solid #e6ebf2;
  border-radius: 8px;
}
.hero h1 {
  margin: 0;
  font-size: 24px;
  line-height: 34px;
  color: #1f2d3d;
}
.hero p {
  margin: 6px 0 0;
  color: #7a8794;
}
.agent-panel {
  margin-bottom: 16px;
  padding: 18px;
  background: #ffffff;
  border: 1px solid #e6ebf2;
  border-radius: 8px;
}
.agent-title {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 12px;
}
.agent-title h2 {
  margin: 0;
  font-size: 18px;
  line-height: 26px;
  color: #1f2d3d;
}
.agent-title p {
  margin: 4px 0 0;
  color: #7a8794;
}
.agent-input {
  display: grid;
  grid-template-columns: 1fr 88px 96px;
  gap: 12px;
  align-items: stretch;
}
.agent-input .el-button {
  height: 54px;
}
.agent-result {
  display: grid;
  gap: 12px;
  margin-top: 14px;
}
.agent-plan {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 12px;
  background: #f7f9fc;
  border-radius: 6px;
}
.agent-plan strong {
  margin-left: 8px;
  color: #1f2d3d;
}
.agent-warnings {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.agent-candidates {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.agent-candidates span {
  padding: 6px 10px;
  color: #606266;
  background: #f4f6f9;
  border-radius: 4px;
}
.agent-table {
  width: 100%;
}
.summary-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 16px;
  margin-bottom: 16px;
}
.summary-card {
  padding: 18px;
  background: #ffffff;
  border: 1px solid #e6ebf2;
  border-radius: 8px;
}
.summary-card span {
  display: block;
  color: #7a8794;
}
.summary-card strong {
  display: block;
  margin-top: 10px;
  font-size: 28px;
  color: #1f7aec;
}
.summary-card.warning strong {
  color: #e6a23c;
}
.summary-card.danger strong {
  color: #f56c6c;
}
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 700;
}
.product-name {
  font-weight: 600;
  line-height: 20px;
}
.product-meta {
  color: #909399;
  line-height: 18px;
}
.todo-list {
  display: grid;
  gap: 10px;
}
.todo-list button {
  display: grid;
  grid-template-columns: 36px 1fr auto;
  align-items: center;
  gap: 10px;
  width: 100%;
  padding: 14px;
  border: 1px solid #e6ebf2;
  border-radius: 8px;
  background: #ffffff;
  color: #2f4056;
  text-align: left;
  cursor: pointer;
}
.todo-list i {
  color: #1f7aec;
  font-size: 20px;
}
.todo-list strong {
  color: #1f7aec;
}
@media (max-width: 900px) {
  .hero {
    align-items: flex-start;
    flex-direction: column;
  }
  .agent-input {
    grid-template-columns: 1fr;
  }
  .agent-input .el-button {
    height: 40px;
  }
  .agent-plan {
    align-items: flex-start;
    flex-direction: column;
  }
  .summary-grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}
</style>
