<template>
    <div>
    <el-dialog title="库存使用记录管理" :visible.sync="visible" width="1400px" @close="closeDialog">
        <div class="usage-record-container">
            <!-- 搜索区域 -->
            <div class="search-section">
                <el-form :model="query" :inline="true" class="search-form">
                    <el-form-item label="产品名称">
                        <el-input v-model="query.productName" placeholder="请输入产品名称" clearable size="small" />
                    </el-form-item>
                    <el-form-item label="产品分类">
                        <el-input v-model="query.productCategory" placeholder="请输入产品分类" clearable size="small" />
                    </el-form-item>
                    <el-form-item label="门店">
                        <el-select v-model="query.storeId" placeholder="请选择门店" style="width: 100%">
                            <el-option v-for="store in storeList" :key="store.id" :label="store.name"
                                :value="store.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="使用时间">
                        <el-date-picker v-model="query.usageTimeRange" type="daterange" range-separator="至"
                            start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" size="small">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" size="small" @click="search">搜索</el-button>
                        <el-button size="small" @click="reset">重置</el-button>
                        <el-button type="success" size="small" icon="el-icon-plus"
                            @click="addUsageRecord">添加使用记录</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 使用记录列表 -->
            <div class="table-section">
                <el-table :data="usageList" v-loading="loading" border stripe style="width: 100%">
                    <el-table-column prop="productName" label="产品名称" width="150" fixed="left" />
                    <el-table-column prop="productCategory" label="产品分类" width="120" />
                    <el-table-column prop="productPrice" label="单价" width="100" align="right">
                        <template slot-scope="scope">
                            {{ formatMoney(scope.row.productPrice) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="usageQuantity" label="使用数量" width="100" align="right" />
                    <el-table-column prop="storeName" label="使用门店" width="120" />
                    <el-table-column prop="usageTime" label="使用时间" width="120" :formatter="ncc.tableDateFormat">
                    </el-table-column>
                    <el-table-column prop="relatedConsumeId" label="关联消费ID" width="120" />
                    <el-table-column prop="createUserName" label="创建人" width="100" />
                    <el-table-column prop="createTime" label="创建时间" width="160" :formatter="ncc.tableDateFormat">
                    </el-table-column>
                    <el-table-column prop="isEffective" label="状态" width="80" align="center">
                        <template slot-scope="scope">
                            <el-tag :type="scope.row.isEffective === 1 ? 'success' : 'danger'" size="small">
                                {{ scope.row.isEffective === 1 ? '有效' : '无效' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120" fixed="right">
                        <template slot-scope="scope">
                            <el-button v-if="scope.row.isEffective === 1" type="text" size="small"
                                @click="cancelUsageRecord(scope.row)">作废</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="pagination-section">
                    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :current-page="pagination.pageIndex" :page-sizes="[10, 20, 50, 100]"
                        :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper"
                        :total="pagination.total">
                    </el-pagination>
                </div>
            </div>
        </div>

      

  
    </el-dialog>
      <!-- 添加使用记录弹窗 -->
      <AddUsageRecordForm v-if="addUsageRecordVisible" ref="AddUsageRecordForm" @refreshDataList="getUsageList" />
    </div>
</template>

<script>
import { getInventoryUsageList, cancelInventoryUsage } from '@/api/extend/lqInventory'
import AddUsageRecordForm from './AddUsageRecordForm'
import request from '@/utils/request'

export default {
    name: 'UsageRecordDialog',
    components: {
        AddUsageRecordForm
    },
    data() {
        return {
            visible: false,
            loading: false,
            productId: '', // 特定产品ID，为空时显示所有
            productName: '', // 特定产品名称
            usageList: [],
            query: {
                productName: '',
                productCategory: '',
                storeName: '',
                usageTimeRange: [],
                productId: '',
                storeId: '',
                relatedConsumeId: '',
                currentPage: 1,
                pageSize: 20
            },
            pagination: {
                pageIndex: 1,
                pageSize: 20,
                total: 0
            },
            addUsageRecordVisible: false,
            storeList: [] // 门店列表
        }
    },
    methods: {
        init(productId = '', productName = '') {
            this.visible = true
            this.productId = productId
            this.productName = productName
            this.query.productId = productId
            if (productName) {
                this.query.productName = productName
            }
            this.getUsageList()
            this.getStoreList()
        },

        // 获取门店列表
        getStoreList() {
            request({
                url: '/api/Extend/LqMdxx',
                method: 'GET'
            }).then(response => {
                this.storeList = response.data.list || []
                if (response.code == 200 && response.data.list.length > 0) {
                    this.storeList = response.data.list.map(item => ({
                        id: item.id,
                        name: item.dm
                    }))
                } else {
                    this.storeList = []
                }
            }).catch(() => {
                this.storeList = []
            })
        },
        // 获取使用记录列表
        getUsageList() {
            this.loading = true
            const params = {
                ...this.query,
                currentPage: this.pagination.pageIndex,
                pageSize: this.pagination.pageSize
            }

            // 处理日期范围
            if (this.query.usageTimeRange && this.query.usageTimeRange.length === 2) {
                params.usageStartTime = this.query.usageTimeRange[0]
                params.usageEndTime = this.query.usageTimeRange[1]
            }

            getInventoryUsageList(params).then(response => {
                if (response.code === 200) {
                    this.usageList = response.data.list || []
                    this.pagination.total = (response.data.pagination && response.data.pagination.total) || 0
                } else {
                    this.$message.error(response.msg || '获取使用记录失败')
                }
                this.loading = false
            }).catch(() => {
                this.loading = false
            })
        },

        // 搜索
        search() {
            this.pagination.pageIndex = 1
            this.getUsageList()
        },

        // 重置
        reset() {
            this.query = {
                productName: this.productName || '',
                productCategory: '',
                storeName: '',
                usageTimeRange: [],
                productId: this.productId,
                storeId: '',
                relatedConsumeId: '',
                currentPage: 1,
                pageSize: 20
            }
            this.pagination.pageIndex = 1
            this.getUsageList()
        },

        // 分页大小改变
        handleSizeChange(val) {
            this.pagination.pageSize = val
            this.pagination.pageIndex = 1
            this.getUsageList()
        },

        // 当前页改变
        handleCurrentChange(val) {
            this.pagination.pageIndex = val
            this.getUsageList()
        },

        // 添加使用记录
        addUsageRecord() {
            // this.visible = false
            this.addUsageRecordVisible = true
            this.$nextTick(() => {
                this.$refs.AddUsageRecordForm.init(this.productId, this.productName)
            })
        },

        // 作废使用记录
        cancelUsageRecord(row) {
            this.$confirm('确定要作废这条使用记录吗？作废后库存数量将恢复。', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                cancelInventoryUsage(row.Id).then(response => {
                    if (response.code === 200) {
                        this.$message.success('作废成功')
                        this.getUsageList()
                    } else {
                        this.$message.error(response.msg || '作废失败')
                    }
                })
            })
        },

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

        // 关闭弹窗
        closeDialog() {
            this.visible = false
            this.usageList = []
            this.query = {
                productName: '',
                productCategory: '',
                storeName: '',
                usageTimeRange: [],
                productId: '',
                storeId: '',
                relatedConsumeId: '',
                currentPage: 1,
                pageSize: 20
            }
            this.pagination = {
                pageIndex: 1,
                pageSize: 20,
                total: 0
            }
        }
    }
}
</script>

<style scoped>
.usage-record-container {
    /* padding: 20px; */
}

.search-section {
    margin-bottom: 20px;
    padding: 15px;
    background: #f5f7fa;
    border-radius: 4px;
}

.search-form .el-form-item {
    margin-bottom: 10px;
}

.table-section {
    margin-bottom: 20px;
}

.pagination-section {
    text-align: right;
    margin-top: 20px;
}

.dialog-footer {
    text-align: right;
}
</style>

