<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--分类树-->
        <pane size="20">
          <el-col>
            <div class="head-container">
              <el-input
                v-model="categoryName"
                placeholder="请输入分类名称"
                clearable
                size="small"
                prefix-icon="el-icon-search"
                style="margin-bottom: 20px"
                @input="handleCategoryFilter"
              />
            </div>
            <div class="head-container">
              <el-tree
                :data="categoryTreeData"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterCategoryNode"
                ref="categoryTree"
                node-key="id"
                default-expand-all
                highlight-current
                @node-click="handleCategoryNodeClick"
              />
            </div>
          </el-col>
        </pane>
        <!--物资列表-->
        <pane size="80">
          <el-col>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
              <el-form-item label="物资编码" prop="materialCode">
                <el-input
                  v-model="queryParams.materialCode"
                  placeholder="请输入物资编码"
                  clearable
                  style="width: 220px"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="物资名称" prop="materialName">
                <el-input
                  v-model="queryParams.materialName"
                  placeholder="请输入物资名称"
                  clearable
                  style="width: 220px"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="仓库" prop="warehouseId">
                <el-select v-model="queryParams.warehouseId" placeholder="请选择仓库" clearable style="width: 220px">
                  <el-option
                    v-for="warehouse in warehouseList"
                    :key="warehouse.id"
                    :label="warehouse.warehouseName"
                    :value="warehouse.id"
                  />
                </el-select>
              </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">
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
            </el-row>

            <el-table
              v-loading="loading"
              :data="materialList"
              row-key="id"
              :expand-row-keys="expandedRows"
              @expand-change="handleExpandChange"
            >
              <el-table-column type="expand">
                <template slot-scope="props">
                  <div v-loading="props.row.inventoryLoading" style="padding: 20px">
                    <el-table :data="props.row.inventoryList" border size="small">
                      <el-table-column label="仓库名称" prop="warehouseName" min-width="150" />
                      <el-table-column label="总数量" prop="totalQty" width="120" align="right">
                        <template slot-scope="scope">
                          <span>{{ scope.row.totalQty || 0 }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="可用数量" prop="availableQty" width="120" align="right">
                        <template slot-scope="scope">
                          <span :style="getInventoryStyle(scope.row, props.row)">{{ scope.row.availableQty || 0 }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="锁定数量" prop="lockedQty" width="120" align="right">
                        <template slot-scope="scope">
                          <span>{{ scope.row.lockedQty || 0 }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="已使用数量" prop="usedQty" width="120" align="right">
                        <template slot-scope="scope">
                          <span>{{ scope.row.usedQty || 0 }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" width="150" fixed="right">
                        <template slot-scope="scope">
                          <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-warning"
                            @click="handleAdjustInventory(scope.row, props.row)"
                            v-hasPermi="['resource:material:inventory:adjust']"
                          >库存调整</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <div style="margin-top: 10px">
                      <el-button
                        size="mini"
                        type="primary"
                        icon="el-icon-plus"
                        @click="handleAddInventory(props.row)"
                        v-hasPermi="['resource:material:inventory:add']"
                      >添加库存</el-button>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="序号" type="index" width="50" align="center" />
              <el-table-column label="物资编码" align="center" prop="materialCode" :show-overflow-tooltip="true" min-width="120" />
              <el-table-column label="物资名称" align="center" prop="materialName" :show-overflow-tooltip="true" min-width="150" />
              <el-table-column label="分类" align="center" prop="categoryName" :show-overflow-tooltip="true" width="120" />
              <el-table-column label="单位" align="center" prop="unit" width="80">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.material_unit" :value="scope.row.unit" />
                </template>
              </el-table-column>
              <el-table-column label="总数量" align="center" prop="totalQty" width="100">
                <template slot-scope="scope">
                  <span>{{ getTotalQty(scope.row) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="可用数量" align="center" prop="availableQty" width="100">
                <template slot-scope="scope">
                  <span :style="getTotalAvailableQtyStyle(scope.row)">{{ getTotalAvailableQty(scope.row) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="库存状态" align="center" width="100">
                <template slot-scope="scope">
                  <el-tag v-if="getInventoryAlert(scope.row)" type="danger" size="small">预警</el-tag>
                  <el-tag v-else type="success" size="small">正常</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="200" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-plus"
                    @click="handleAddInventory(scope.row)"
                    v-hasPermi="['resource:material:inventory:add']"
                  >添加库存</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-col>
        </pane>
      </splitpanes>
    </el-row>

    <!-- 添加库存对话框 -->
    <el-dialog :title="inventoryTitle" :visible.sync="inventoryOpen" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="inventoryForm" :model="inventoryForm" :rules="inventoryRules" label-width="100px">
        <el-form-item label="仓库" prop="warehouseId">
          <el-select 
            v-model="inventoryForm.warehouseId" 
            placeholder="请选择仓库" 
            style="width: 100%"
            :disabled="!!currentInventory"
          >
            <el-option
              v-for="warehouse in warehouseList"
              :key="warehouse.id"
              :label="warehouse.warehouseName"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="totalQty">
          <el-input-number
            v-model="inventoryForm.totalQty"
            :min="0"
            :precision="2"
            placeholder="请输入数量"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="inventoryForm.remark" type="textarea" placeholder="请输入备注" maxlength="500" :rows="3" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitInventoryForm">确 定</el-button>
        <el-button @click="inventoryOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 库存调整对话框 -->
    <el-dialog title="库存调整" :visible.sync="adjustOpen" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="adjustForm" :model="adjustForm" :rules="adjustRules" label-width="100px">
        <el-form-item label="仓库" prop="warehouseId">
          <el-select v-model="adjustForm.warehouseId" disabled style="width: 100%">
            <el-option
              v-for="warehouse in warehouseList"
              :key="warehouse.id"
              :label="warehouse.warehouseName"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="调整数量" prop="adjustmentQty">
          <el-input-number
            v-model="adjustForm.adjustmentQty"
            :precision="2"
            placeholder="请输入调整数量（可为负数）"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="调整原因" prop="reason">
          <el-select v-model="adjustForm.reason" placeholder="请选择调整原因" style="width: 100%">
            <el-option
              v-for="dict in dict.type.inventory_adjustment_reason"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="adjustForm.remark" type="textarea" placeholder="请输入备注" maxlength="500" :rows="3" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAdjustForm">确 定</el-button>
        <el-button @click="adjustOpen = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listMaterial } from '@/api/resource/material'
import { listCategory } from '@/api/resource/material/category'
import { listWarehouse } from '@/api/resource/warehouse'
import {
  listMaterialInventory,
  addMaterialInventory,
  adjustMaterialInventory
} from '@/api/resource/material/inventory'
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'

export default {
  name: 'ResourceMaterialInventory',
  dicts: ['material_unit', 'inventory_adjustment_reason'],
  components: {
    Splitpanes,
    Pane
  },
  data() {
    const validateAdjustmentQty = (rule, value, callback) => {
      if (value === undefined || value === null || value === '') {
        callback(new Error('调整数量不能为空'))
      } else if (Number(value) === 0) {
        callback(new Error('调整数量不能为0'))
      } else {
        callback()
      }
    }

    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物资表格数据
      materialList: [],
      // 仓库列表
      warehouseList: [],
      // 分类树数据（用于左侧树）
      categoryTreeData: [],
      // 分类名称（用于搜索）
      categoryName: undefined,
      // 树组件默认属性
      defaultProps: {
        children: 'children',
        label: 'categoryName'
      },
      // 展开的行
      expandedRows: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialCode: undefined,
        materialName: undefined,
        categoryId: undefined,
        warehouseId: undefined
      },
      // 库存对话框
      inventoryOpen: false,
      inventoryTitle: '',
      inventoryForm: {},
      inventoryRules: {
        warehouseId: [{ required: true, message: '仓库不能为空', trigger: 'change' }],
        totalQty: [{ required: true, message: '数量不能为空', trigger: 'blur' }]
      },
      adjustOpen: false,
      adjustForm: {},
      adjustRules: {
        warehouseId: [{ required: true, message: '仓库不能为空', trigger: 'change' }],
        adjustmentQty: [{ validator: validateAdjustmentQty, trigger: 'blur' }],
        reason: [{ required: true, message: '调整原因不能为空', trigger: 'change' }]
      },
      // 当前物资
      currentMaterial: null,
      // 当前库存
      currentInventory: null
    }
  },
  created() {
    this.getCategoryTree()
    this.getWarehouseList()
    this.getList()
  },
  methods: {
    /** 查询物资列表 */
    getList() {
      this.loading = true
      listMaterial(this.queryParams).then(response => {
        this.materialList = (response.rows || []).map(item => ({
          ...item,
          inventoryList: [],
          inventoryLoading: false
        }))
        this.total = response.total || 0
        // 清空展开的行，将所有子表折叠
        this.expandedRows = []
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 查询分类树（用于左侧树） */
    getCategoryTree() {
      listCategory({}).then(response => {
        const treeData = this.handleTree(response.data, 'id')
        // 添加"全部"选项
        this.categoryTreeData = [
          {
            id: 0,
            categoryName: '全部',
            children: treeData
          }
        ]
      })
    },
    /** 过滤分类树节点 */
    filterCategoryNode(value, data) {
      if (!value) return true
      return data.categoryName && data.categoryName.indexOf(value) !== -1
    },
    /** 处理分类树过滤 */
    handleCategoryFilter(value) {
      this.$refs.categoryTree.filter(value)
    },
    /** 分类树节点点击事件 */
    handleCategoryNodeClick(data) {
      if (data.id === 0) {
        // 点击"全部"时，清空分类筛选
        this.queryParams.categoryId = undefined
      } else {
        this.queryParams.categoryId = data.id
      }
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 查询仓库列表 */
    getWarehouseList() {
      listWarehouse({}).then(response => {
        this.warehouseList = response.rows || []
      })
    },
    /** 展开行变化 */
    handleExpandChange(row, expandedRows) {
      if (expandedRows.includes(row)) {
        // 展开时加载库存
        this.loadInventory(row)
      }
    },
    /** 加载库存 */
    loadInventory(row) {
      if (row.inventoryLoading) return
      row.inventoryLoading = true
      listMaterialInventory(row.id, {}).then(response => {
        row.inventoryList = response.rows || []
        row.inventoryLoading = false
      }).catch(() => {
        row.inventoryLoading = false
      })
    },
    /** 获取总数量 */
    getTotalQty(row) {
      // 优先使用后端返回的聚合字段，如果没有则从库存列表计算
      if (row.totalQty !== undefined && row.totalQty !== null) {
        return parseFloat(row.totalQty).toFixed(2)
      }
      if (!row.inventoryList || row.inventoryList.length === 0) return '0.00'
      return row.inventoryList.reduce((sum, inv) => sum + (parseFloat(inv.totalQty) || 0), 0).toFixed(2)
    },
    /** 获取总可用数量 */
    getTotalAvailableQty(row) {
      // 优先使用后端返回的聚合字段，如果没有则从库存列表计算
      if (row.availableQty !== undefined && row.availableQty !== null) {
        return parseFloat(row.availableQty).toFixed(2)
      }
      if (!row.inventoryList || row.inventoryList.length === 0) return '0.00'
      return row.inventoryList.reduce((sum, inv) => sum + (parseFloat(inv.availableQty) || 0), 0).toFixed(2)
    },
    /** 获取总可用数量样式 */
    getTotalAvailableQtyStyle(row) {
      const availableQty = parseFloat(this.getTotalAvailableQty(row))
      const threshold = parseFloat(row.threshold || 0)
      if (threshold > 0 && availableQty < threshold) {
        return { color: '#f56c6c', fontWeight: 'bold' }
      }
      return {}
    },
    /** 获取库存预警 */
    getInventoryAlert(row) {
      const availableQty = parseFloat(this.getTotalAvailableQty(row))
      const threshold = parseFloat(row.threshold || 0)
      return threshold > 0 && availableQty < threshold
    },
    /** 获取库存样式 */
    getInventoryStyle(inventory, material) {
      const availableQty = parseFloat(inventory.availableQty || 0)
      const threshold = parseFloat(material.threshold || 0)
      if (threshold > 0 && availableQty < threshold) {
        return { color: '#f56c6c', fontWeight: 'bold' }
      }
      return {}
    },
    /** 添加库存 */
    handleAddInventory(row) {
      this.currentMaterial = row
      this.currentInventory = null
      this.inventoryTitle = '添加库存'
      this.inventoryForm = {
        warehouseId: undefined,
        totalQty: undefined,
        remark: undefined
      }
      this.inventoryOpen = true
    },
    /** 打开库存调整 */
    handleAdjustInventory(inventory, material) {
      if (!material || !inventory) {
        this.$modal.msgWarning('请选择具体仓库记录后再调整')
        return
      }
      this.currentMaterial = material
      this.currentInventory = inventory
      this.adjustForm = {
        warehouseId: inventory ? inventory.warehouseId : undefined,
        adjustmentQty: undefined,
        reason: undefined,
        remark: undefined
      }
      this.adjustOpen = true
    },
    /** 提交库存表单 */
    submitInventoryForm() {
      this.$refs['inventoryForm'].validate(valid => {
        if (valid) {
          // 添加库存
          addMaterialInventory(this.currentMaterial.id, this.inventoryForm).then(() => {
            this.$modal.msgSuccess('添加成功')
            this.inventoryOpen = false
            this.loadInventory(this.currentMaterial)
          })
        }
      })
    },
    /** 提交调整表单 */
    submitAdjustForm() {
      if (!this.currentMaterial) {
        return
      }
      this.$refs['adjustForm'].validate(valid => {
        if (valid) {
          adjustMaterialInventory(this.currentMaterial.id, {
            warehouseId: this.adjustForm.warehouseId,
            adjustmentQty: this.adjustForm.adjustmentQty,
            reason: this.adjustForm.reason,
            remark: this.adjustForm.remark
          }).then(() => {
            this.$modal.msgSuccess('调整成功')
            this.adjustOpen = false
            this.loadInventory(this.currentMaterial)
          })
        }
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      // 重置分类筛选
      this.queryParams.categoryId = undefined
      // 清空分类树选中状态
      if (this.$refs.categoryTree) {
        this.$refs.categoryTree.setCurrentKey(null)
      }
      this.handleQuery()
    }
  }
}
</script>

<style scoped>
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
</style>