<template>
    <div class="NCC-common-layout">
        <div class="NCC-common-layout-center">
            <!-- 搜索区域 -->
            <el-row class="NCC-common-search-box" :gutter="16">
                <el-form @submit.native.prevent>
                    <el-col :span="6">
                        <el-form-item label="产品名称">
                            <el-input v-model="query.productName" placeholder="请输入产品名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="产品分类">
                            <el-input v-model="query.productCategory" placeholder="请输入产品分类" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="负责部门">
                            <el-select v-model="query.departmentId" placeholder="请选择负责部门" clearable style="width: 100%">
                                <el-option v-for="dept in departmentList" :key="dept.id" :label="dept.name"
                                    :value="dept.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item>
                            <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
                            <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>

            <!-- 主要内容区域 -->
            <div class="NCC-common-layout-main NCC-flex-main">
                <!-- 操作按钮区域 -->
                <div class="NCC-common-head">
                    <div>
                        <el-button type="primary" icon="el-icon-plus" @click="addInventoryHandle()">添加库存</el-button>
                        <el-button type="success" icon="el-icon-edit" @click="editInventoryHandle()"
                            :disabled="selectedIds.length !== 1">编辑库存</el-button>
                        <el-button type="warning" icon="el-icon-s-operation"
                            @click="usageRecordHandle()">使用记录</el-button>
                        <el-button type="text" icon="el-icon-download" @click="exportData()">导出</el-button>
                    </div>
                    <div class="NCC-common-head-right">
                        <el-tooltip effect="dark" content="刷新" placement="top">
                            <el-link icon="icon-ym icon-ym-Refresh NCC-common-head-icon" :underline="false"
                                @click="reset()" />
                        </el-tooltip>
                        <screenfull isContainer />
                    </div>
                </div>

                <!-- 库存列表表格 -->
                <NCC-table v-loading="listLoading" :data="list" has-c @selection-change="handleSelectionChange">
                    <el-table-column prop="productName" label="产品名称" align="left" show-overflow-tooltip />
                    <el-table-column prop="productCategory" label="产品分类" align="left" width="120" />
                    <el-table-column prop="price" label="单价" align="right" width="100">
                        <template slot-scope="scope">
                            {{ formatMoney(scope.row.price) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="quantity" label="库存数量" align="right" width="100">
                        <template slot-scope="scope">
                            <span :class="scope.row.quantity <= 10 ? 'text-danger' : ''">{{ scope.row.quantity }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="standardUnit" label="单位" align="center" width="80" />
                    <el-table-column prop="totalValue" label="总价值" align="right" width="120">
                        <template slot-scope="scope">
                            {{ formatMoney(scope.row.totalValue) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="departmentName" label="负责部门" align="left" width="120" />
                    <el-table-column prop="createTime" label="创建时间" align="center" width="160">
                        <template slot-scope="scope">
                            {{ scope.row.createTime | dateTimeFormat }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="200" fixed="right">
                        <template slot-scope="scope">
                            <el-button type="text" @click="viewInventoryInfo(scope.row)">查看详情</el-button>
                            <el-button type="text" @click="editInventory(scope.row)">编辑</el-button>
                            <el-button type="text" @click="viewUsageRecords(scope.row)">使用记录</el-button>
                        </template>
                    </el-table-column>
                </NCC-table>

                <!-- 分页组件 -->
                <pagination v-show="total > 0" :total="total" :page.sync="query.currentPage"
                    :limit.sync="query.pageSize" @pagination="getList" />
            </div>
        </div>

        <!-- 添加/编辑库存弹窗 -->
        <InventoryForm v-if="inventoryFormVisible" ref="InventoryForm" @refreshDataList="getList" />

        <!-- 库存详情弹窗 -->
        <InventoryInfoDialog v-if="inventoryInfoVisible" ref="InventoryInfoDialog" />

        <!-- 使用记录弹窗 -->
        <UsageRecordDialog v-if="usageRecordVisible" ref="UsageRecordDialog" />
    </div>
</template>

<script>
import { getInventoryList } from '@/api/extend/lqInventory'
import { getUserList } from '@/api/permission/user'
import InventoryForm from './InventoryForm'
import InventoryInfoDialog from './InventoryInfoDialog'
import UsageRecordDialog from './UsageRecordDialog'
import Pagination from '@/components/Pagination'

export default {
    name: 'LqInventory',
    components: {
        InventoryForm,
        InventoryInfoDialog,
        UsageRecordDialog,
        Pagination
    },
    data() {
        return {
            query: {
                productName: '',
                productCategory: '',
                departmentId: '',
                currentPage: 1,
                pageSize: 20
            },
            list: [],
            total: 0,
            listLoading: true,
            inventoryFormVisible: false,
            inventoryInfoVisible: false,
            usageRecordVisible: false,
            selectedIds: [],
            departmentList: [] // 部门列表
        }
    },
    created() {
        this.getDepartmentList()
        this.getList()
    },
    methods: {
        // 获取部门列表
        getDepartmentList() {
            const params = {
                currentPage: 1,
                pageSize: 1000, // 获取所有部门
                enabledMark: 1 // 只获取启用的部门
            }

            getUserList(params).then(response => {
                if (response.code === 200) {
                    // 将用户列表转换为部门列表格式
                    this.departmentList = response.data.list.map(user => ({
                        id: user.id,
                        name: user.realName
                    }))
                } else {
                    this.$message.error(response.msg || '获取部门列表失败')
                }
            }).catch(() => {
                this.$message.error('获取部门列表失败')
            })
        },

        // 获取库存列表
        getList() {
            this.listLoading = true
            getInventoryList(this.query).then(response => {
                if (response.code === 200) {
                    this.list = response.data.list || []
                    this.total = (response.data.pagination && response.data.pagination.total) || 0
                } else {
                    this.$message.error(response.msg || '获取库存列表失败')
                }
                this.listLoading = false
            }).catch(() => {
                this.listLoading = false
            })
        },

        // 搜索
        search() {
            this.query.currentPage = 1
            this.getList()
        },

        // 重置
        reset() {
            this.query = {
                productName: '',
                productCategory: '',
                departmentId: '',
                currentPage: 1,
                pageSize: 20
            }
            this.getList()
        },

        // 添加库存
        addInventoryHandle() {
            this.inventoryFormVisible = true
            this.$nextTick(() => {
                this.$refs.InventoryForm.init()
            })
        },

        // 编辑库存
        editInventoryHandle() {
            if (this.selectedIds.length === 0) {
                this.$message.warning('请选择一个库存记录')
                return
            }
            if (this.selectedIds.length > 1) {
                this.$message.warning('请只选择一个库存记录')
                return
            }

            const selectedInventory = this.list.find(item => item.id === this.selectedIds[0])
            if (selectedInventory) {
                this.inventoryFormVisible = true
                this.$nextTick(() => {
                    this.$refs.InventoryForm.init(selectedInventory.id)
                })
            }
        },

        // 编辑库存（从操作列）
        editInventory(row) {
            this.inventoryFormVisible = true
            this.$nextTick(() => {
                this.$refs.InventoryForm.init(row.id)
            })
        },

        // 查看库存详情
        viewInventoryInfo(row) {
            this.inventoryInfoVisible = true
            this.$nextTick(() => {
                this.$refs.InventoryInfoDialog.init(row.id)
            })
        },

        // 使用记录管理
        usageRecordHandle() {
            this.usageRecordVisible = true
            this.$nextTick(() => {
                this.$refs.UsageRecordDialog.init()
            })
        },

        // 查看使用记录
        viewUsageRecords(row) {
            this.usageRecordVisible = true
            this.$nextTick(() => {
                this.$refs.UsageRecordDialog.init(row.id, row.productName)
            })
        },

        // 多选
        handleSelectionChange(selection) {
            this.selectedIds = selection.map(item => item.id)
        },

        // 格式化金额
        formatMoney(value) {
            if (value === null || value === undefined || value === '') {
                return '0.00'
            }
            return Number(value).toFixed(2)
        },

        // 导出
        exportData() {
            this.$message.info('导出功能开发中...')
        }
    }
}
</script>

<style scoped>
.NCC-common-layout {
    height: 100%;
}

.text-danger {
    color: #f56c6c;
    font-weight: bold;
}
</style>
