<template>
    <div style="margin-bottom: 10px">
        <el-config-provider :locale="zhCn">
            <el-row>
                <el-input v-model="goodsIdQuery" style="width: 256px; margin-right: 10px;" placeholder="物料编号"
                    :suffix-icon="Search" />
                <el-button type="primary" @click="search()">搜索</el-button>
                <el-button type="warning" @click="reset()">重置</el-button>
                <el-button type="success" @click="exportExcel()">导出表格</el-button>
            </el-row>
            <br />
            <el-table id="stock-table" :data="displayStocks" stripe border v-loading="loading" class="table-class"
                max-height="650px" highlight-current-row @row-click="getCurrentRow" :row-style="rowStyle"
                :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
                <el-table-column width="65px" fixed="left">
                    <template v-slot="scope">
                        <el-radio :label="scope.row.stockId" v-model="stockId">&nbsp;</el-radio>
                    </template>
                </el-table-column>
                <el-table-column prop="goodsId" label="物料号" fixed="left" min-width="120px" show-overflow-tooltip />
                <el-table-column prop="goodsName" label="物料名称" fixed="left" min-width="120px" show-overflow-tooltip />
                <el-table-column prop="remainNum" label="剩余数量" min-width="120px" />
                <el-table-column prop="totalNum" label="入库数量" min-width="120px" />
                <el-table-column prop="vehicleId" label="载具号" min-width="120px" show-overflow-tooltip />
                <el-table-column prop="locationId" label="库位" :formatter="locationFormat" min-width="120px" show-overflow-tooltip />
                <el-table-column prop="isInventory" label="是否盘点" min-width="120px" />
                <el-table-column prop="createTime" label="上架时间" :formatter="timeFormat" min-width="120px" show-overflow-tooltip />
                <el-table-column prop="goodsStatus" label="物料状态" :formatter="goodsStatusFormat" min-width="120px" />
                <el-table-column prop="stockStatus" label="库存状态" :formatter="stockStatusFormat" fixed="right"
                    min-width="120px" />
                <!-- <el-table-column fixed="right" label="操作" width="120px" v-if="selStock == null">
                    <template v-slot="scope">
                        <el-button plain type="primary" @click="editCurrentRowStock(scope.row)">编辑</el-button>
                    </template>
                </el-table-column> -->
            </el-table>
            <br />
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 25, 50]"
                :small="false" :disabled="false" :background="false" :default-page-size="10" @size-change="search"
                @current-change="search" layout="total, sizes, prev, pager, next, jumper" :total="total" />
            <el-dialog v-model="dialogVisible" title="库存信息" width="40%" draggable :show-close="false">
                <el-form ref="stockFormRef" :model="stockFormEntity" :label-position="labelPosition" label-width="100px"
                    style="max-width: 100%" :rules="rules" status-icon>
                    <el-row :gutter="16">
                        <el-col :span="12" :offset="0">
                            <el-form-item label="型号" prop="goodsType">
                                <el-input v-model="stockFormEntity.goodsType" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="规格" prop="specification">
                                <el-input v-model="stockFormEntity.specification" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16">
                        <el-col :span="12" :offset="0">
                            <el-form-item label="条码号" prop="barcode">
                                <el-input v-model="stockFormEntity.barcode" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="批次号" prop="batchNo">
                                <el-input v-model="stockFormEntity.batchNo" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16">
                        <el-col :span="12" :offset="0">
                            <el-form-item label="入库数量" prop="originNum">
                                <el-input-number v-model.number="stockFormEntity.originNum" clearable
                                    controls-position="right" :min="0" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="实际数量（为0时删除库存）" prop="realNum">
                                <el-input-number v-model.number="stockFormEntity.realNum" controls-position="right"
                                    :min="0" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16">
                        <el-col :span="12" :offset="0">
                            <el-form-item label="库位" prop="locationId">
                                <el-input v-model="stockFormEntity.locationId" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="订单号" prop="orderId">
                                <el-input v-model="stockFormEntity.orderId" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16">
                        <el-col :span="12" :offset="0">
                            <el-form-item label="库存状态" prop="stockStatus">
                                <el-select-v2 v-model="stockFormEntity.stockStatus" placeholder="请选择库存状态"
                                    :options="stockStatusOptions"></el-select-v2>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="物料状态" prop="goodsStatus">
                                <el-select-v2 v-model="stockFormEntity.goodsStatus" placeholder="请选择物料状态"
                                    :options="goodsStatusOptions"></el-select-v2>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="submitStockInfo(stockFormEntity)">
                            确定
                        </el-button>
                    </span>
                </template>
            </el-dialog>
        </el-config-provider>
    </div>
</template>

<script setup>
import { getAllStocks, updateStockInfo } from '@/api/stock.js'
import { downloadStockExcel } from '@/api/excel.js'
import { dateFormatter, locationFormatter, timeFormatter } from '@/utils/formatter.js'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { Search } from '@element-plus/icons-vue'
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
// import FileSaver from 'file-saver';
// import * as XLSX from 'xlsx';
</script>
<script>
export default {
    name: 'stock',
    props: ['selStock'],
    emits: ['update:selStock'],
    data() {
        return {
            displayStocks: [],
            currentPage: 1,
            pageSize: 10,
            total: 0,
            queryKey: '',
            goodsIdQuery: '',
            loading: true,
            stockId: '',
            stockFormRef: ref(),
            stockFormEntity: reactive({}),
            rules: reactive({}),
            labelPosition: 'top',
            dialogVisible: false,
            goodsStatusOptions: [
                {
                    value: 0,
                    label: '合格'
                },
                {
                    value: 1,
                    label: '不合格'
                },
                {
                    value: 2,
                    label: '延期'
                },
                {
                    value: 3,
                    label: '过期'
                },
                {
                    value: 5,
                    label: '长时间未使用'
                }
            ],
            stockStatusOptions: [
                {
                    value: 0,
                    label: '库存正常'
                },
                {
                    value: 1,
                    label: '出库中'
                },
                {
                    value: 2,
                    label: '盘点中'
                },
                {
                    value: 3,
                    label: '移库中'
                },
                {
                    value: 9,
                    label: '库存锁定'
                }
            ],
        }
    },
    mounted() {
        this.search()
    },
    methods: {
        locationFormat: (row, column, cellValue, index) => {
            return locationFormatter(cellValue)
        },
        dateFormat: (row, column, cellValue, index) => {
            return dateFormatter(cellValue)
        },
        timeFormat: (row, column, cellValue, index) => {
            return timeFormatter(cellValue)
        },
        goodsStatusFormat: (row, column, cellValue, index) => {
            if (cellValue === 0) {
                return '合格'
            } else if (cellValue === 1) {
                return '不合格'
            } else if (cellValue === 2) {
                return '延期'
            } else if (cellValue === 3) {
                return '过期'
            } else if (cellValue === 5) {
                return '长时间未使用'
            }
        },
        stockStatusFormat: (row, column, cellValue, index) => {
            switch (cellValue) {
                case 0:
                    return '库存正常'
                case 1:
                    return '出库中'
                case 2:
                    return '盘点中'
                case 3:
                    return '移库中'
                case 9:
                    return '库存锁定'
                default:
                    return '异常'
            }
        },
        rowStyle: ({ row, rowIndex }) => {
            if (row.goodsStatus == 3) {
                return { "color": "red" }
            }
            if (row.goodsStatus == 5) {
                return { "color": "yellow" }
            }
        },
        search() {
            this.loading = true
            const request = {
                pageNo: this.currentPage,
                pageSize: this.pageSize,
                goodsId: this.goodsIdQuery.trim(),
                userName: store.getters.getUserName
            }
            getAllStocks(request).then(res => {
                const tableResponse = res.data
                if (tableResponse.code == 0) {
                    this.displayStocks = tableResponse.returnData.lists
                    this.total = tableResponse.returnData.total
                } else {
                    ElMessage.error(tableResponse.message)
                }
            }).catch(err => {
                console.log(err)
                ElMessage.error('查询库存错误')
            })
            this.loading = false
        },
        reset() {
            this.queryKey = ''
            this.search()
        },
        getCurrentRow(row) {
            this.stockId = row.stockId
            this.$emit('update:selStock', row)
        },
        exportExcel() {
            const params = {
                goodsId: this.goodsIdQuery.trim
            }
            downloadStockExcel(params).then(res => {
                const link = document.createElement('a');//创建a标签
                try {
                    // let blob = new Blob([res.data],{type: 'application/vnd.ms-excel'});    //如果后台返回的不是blob对象类型，先定义成blob对象格式，该type导出为xls格式，
                    let blob = res.data    //如果后台返回的直接是blob对象类型，直接获取数据
                    // let _fileName = res.headers['content-disposition'].split(';')[1].split('=')[1]; //拆解获取文件名，如果后端有给返回文件名的话
                    let _fileName = "库存报表" + dateFormatter(new Date) + ".xlsx"
                    link.style.display = 'none'//隐藏

                    // 兼容不同浏览器的URL对象
                    const url = window.URL || window.webkitURL || window.moxURL
                    link.href = url.createObjectURL(blob)
                    link.setAttribute('download', _fileName.substring(_fileName.lastIndexOf('_') + 1))
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link)
                    url.revokeObjectURL(link.href)//移除url对象
                } catch (e) {
                    ElMessage({
                        message: '下载文件失败：: ' + e,
                        type: 'error',
                        showClose: true
                    })
                }
            }).catch(err => {
                ElMessage({
                    message: '导出失败：: ' + err,
                    type: 'error',
                    showClose: true
                })
            })
        },
        editCurrentRowStock(row) {
            this.stockFormEntity = {
                stockId: row.stockId,
                locationId: row.locationId,
                vehicleId: row.vehicleId,
                stockStatus: row.stockStatus,
                createTime: row.createTime,
                lastUpdateTime: row.lastUpdateTime,
                lastUpdateUser: row.lastUpdateUser,
                isInventory: row.isInventory,
                inventoryTaskId: row.inventoryTaskId,
                noUseDays: row.noUseDays,
                goodsRelated: {
                    goodsId: row.goodsId,
                    goodsName: row.goodsName,
                    goodsStatus: row.goodsStatus,
                    remainNum: row.remainNum,
                    totalNum: row.totalNum
                }
            }
            this.stockFormEntity = row
            this.dialogVisible = true
        },
        submitStockInfo(stockFormEntity) {
            updateStockInfo(stockFormEntity).then(res => {
                if (res.data.code == 0) {
                    this.dialogVisible = false
                    ElMessage({
                        message: '更新库存成功',
                        type: 'success'
                    })
                    this.search()
                } else {
                    ElMessage.error(res.data.message)
                }
            }).catch(err => {
                ElMessage({
                    message: '更新料箱信息失败: ' + err,
                    type: 'error',
                    showClose: true
                })
            })
        }
    },
}
</script>

<style scoped>
.el-pagination {
    padding-left: 5px;
}

.el-row .el-button {
    width: 72px;
    margin-left: 0px;
    margin-right: 5px;
}

.table-class {
    width: 100%;
}

.el-row .el-form-item .el-select-v2 {
    width: 100% !important;
}

.el-row .el-form-item .el-input-number {
    width: 100% !important;
}
</style>