<template>
    <div style="margin-bottom: 10px; height: 100%; padding-left: 1%; padding-right: 1%;">
        <el-config-provider :locale="zhCn">
            <div style="display: flex;justify-content: space-between;">
                <el-row>
                    <el-input v-model="goodsIdQuery" style="width: 158px; margin-right: 10px;" placeholder="料号"
                        :suffix-icon="Search" />
                    <el-button type="primary" @click="search()">搜索</el-button>
                    <el-button type="warning" @click="reset()">重置</el-button>
                </el-row>
                <el-row>
                    <el-button style="background-color: #00CED1; color: #000;"
                        @click="uploadDialogVisible = true">导入</el-button>
                    <el-button style="background-color: #32CD32; color: #000;" @click="exportExcel()">导出</el-button>
                </el-row>
            </div>
            <br />
            <el-table :data="goodsList" stripe border v-loading="loading" class="table-class" highlight-current-row
                max-height="650px" @row-click="getCurrentRow" :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.goodsId" v-model="goodsId">&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="goodsDescription" label="物料描述" min-width="120px" show-overflow-tooltip />
                <el-table-column prop="vendorName" label="供应商" min-width="120px" show-overflow-tooltip />
                <el-table-column prop="putArea" label="优先存放区域" min-width="120px" show-overflow-tooltip />
                <el-table-column prop="firstImportTime" label="初次导入时间" :formatter="timeFormat" min-width="120px" show-overflow-tooltip />
                <el-table-column prop="firstImportUser" label="初次导入用户" min-width="120px" show-overflow-tooltip />
                <el-table-column prop="lastUpdateTime" label="最近更新时间" :formatter="timeFormat" min-width="120px" show-overflow-tooltip />
                <el-table-column prop="lastUpdateUser" label="最近更新用户" min-width="120px" show-overflow-tooltip />
                <el-table-column fixed="right" label="操作" width="240px">
                    <template v-slot="scope">
                        <el-button plain type="primary" @click="editCurrentRowGoods(scope.row)">编辑</el-button>
                        <el-button plain type="danger" @click="deleteCurrentRowGoods(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"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="search"
                @current-change="search" />
            <el-dialog v-model="dialogVisible" title="物料信息" width="40%" draggable :show-close="false">
                <div
                    style="max-width: 100%; max-height: 500px; overflow: auto; display: flex; justify-content: center;">
                    <el-form ref="goodsFormRef" :model="goodsFormEntity" :label-position="labelPosition"
                        label-width="100px" style="width: 95%;" :rules="rules" status-icon>
                        <el-row :gutter="16">
                            <el-col :span="12" :offset="0">
                                <el-form-item label="料号" prop="goodsId">
                                    <el-input v-model="goodsFormEntity.goodsId" disabled />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="描述" prop="goodsName">
                                    <el-input v-model="goodsFormEntity.goodsName" clearable />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="16">
                            <el-col :span="12" :offset="0">
                                <el-form-item label="单位" prop="goodsUnit">
                                    <el-input v-model="goodsFormEntity.goodsUnit" clearable />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="物料分类" prop="goodsType">
                                    <el-input v-model="goodsFormEntity.goodsType" clearable />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="16">
                            <el-col :span="12" :offset="0">
                                <el-form-item label="供应商分类" prop="providerType">
                                    <el-input v-model="goodsFormEntity.providerType" clearable />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="重量" prop="weight">
                                    <el-input-number v-model.number="goodsFormEntity.weight" controls-position="right"
                                        :precision="3" :step="0.1" :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="weightUnit">
                                    <el-input v-model="goodsFormEntity.weightUnit" clearable />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="每盒数量" prop="quantityPerBox">
                                    <el-input-number v-model.number="goodsFormEntity.quantityPerBox"
                                        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="unpackingType">
                                    <el-input v-model="goodsFormEntity.unpackingType" clearable />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="料箱类型" prop="vehicleType">
                                    <el-input v-model="goodsFormEntity.vehicleType" clearable />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="16">
                            <el-col :span="12" :offset="0">
                                <el-form-item label="热度" prop="heat">
                                    <el-input v-model="goodsFormEntity.heat" clearable />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="卸货点" prop="releasePoint">
                                    <el-input v-model="goodsFormEntity.releasePoint" clearable />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="16">
                            <el-col :span="12" :offset="0">
                                <el-form-item label="补料方式" prop="feedingType">
                                    <el-input v-model="goodsFormEntity.feedingType" clearable />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="补货点" prop="feedingValue">
                                    <el-input-number v-model.number="goodsFormEntity.feedingValue"
                                        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="vehicleTypeDescription">
                                    <el-input v-model="goodsFormEntity.vehicleTypeDescription" clearable />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="料箱类型2" prop="goodsInVehicleType">
                                    <el-input v-model="goodsFormEntity.goodsInVehicleType" clearable />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="16">
                            <el-col :span="12" :offset="0">
                                <el-form-item label="数据来源" prop="dataSource">
                                    <el-input v-model="goodsFormEntity.dataSource" clearable />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="submitGoodsInfo(goodsFormEntity)">
                            确定
                        </el-button>
                    </span>
                </template>
            </el-dialog>
            <el-dialog v-model="uploadDialogVisible" title="导入物料" width="40%" draggable :show-close="true">
                <fieldset class="title-area">
                    <legend>导入物料基本信息</legend>
                    <UploadExcelBaseGoods></UploadExcelBaseGoods>
                </fieldset>
                <fieldset class="title-area">
                    <legend>导入看板</legend>
                    <UploadExcelKanban></UploadExcelKanban>
                </fieldset>
            </el-dialog>
        </el-config-provider>
    </div>
</template>

<script setup>
import store from '@/store'
import { getGoodsInfoByPage, deleteGoodsInfo, updateGoodsInfo } from '@/api/goods.js'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { ElMessageBox, ElMessage } from 'element-plus'
import { ref, reactive } from 'vue'
import { dateFormatter, timeFormatter } from '@/utils/formatter.js'
import { errorBox } from '@/utils/myMessageBox.js'
// import UploadExcelGoods from '@/excel/UploadExcelGoods.vue'
import UploadExcelBaseGoods from '@/excel/UploadExcelBaseGoods.vue'
import UploadExcelKanban from '@/excel/UploadExcelKanban.vue'
import { downloadGoodsExcel } from '@/api/excel.js'
import { Search } from '@element-plus/icons-vue'
</script>
<script>
export default {
    name: 'goods',
    data() {
        return {
            goodsList: [],
            goodsInfo: {},
            currentPage: 1,
            pageSize: 10,
            total: 0,
            goodsIdQuery: '',
            loading: true,
            dialogVisible: false,
            uploadDialogVisible: false,
            goodsId: '',
            goodsFormEntity: reactive({}),
            labelPosition: 'top',
            goodsFormRef: ref(),
            rules: reactive({})
        }
    },
    mounted() {
        this.search()
    },
    methods: {
        search() {
            this.loading = true
            const request = {
                pageNo: this.currentPage,
                pageSize: this.pageSize,
                goodsId: this.goodsIdQuery.trim(),
                userName: store.getters.getUserName
            }
            getGoodsInfoByPage(request).then(res => {
                console.log(res)
                const tableResponse = res.data
                if (tableResponse.code == 0) {
                    this.goodsList = tableResponse.data.lists
                    this.total = tableResponse.data.total
                } else {
                    errorBox(tableResponse.message)
                }
            }).catch(err => {
                console.log(err)
                errorBox('查询物料错误')
            })
            this.loading = false
        },
        dateFormat: (row, column, cellValue, index) => {
            return dateFormatter(cellValue)
        },
        timeFormat: (row, column, cellValue, index) => {
            return timeFormatter(cellValue)
        },
        reset() {
            this.goodsIdQuery = ''
            this.search()
        },
        editCurrentRowGoods(row) {
            this.goodsId = row.goodsId
            this.goodsFormEntity = {
                goodsId: row.goodsId,
                goodsName: row.goodsName,
                goodsUnit: row.goodsUnit,
                goodsType: row.goodsType,
                providerType: row.providerType,
                weight: row.weight,
                weightUnit: row.weightUnit,
                quantityPerBox: row.quantityPerBox,
                unpackingType: row.unpackingType,
                vehicleType: row.vehicleType,
                vehicleTypeDescription: row.vehicleTypeDescription,
                goodsInVehicleType: row.goodsInVehicleType,
                feedingType: row.feedingType,
                feedingValue: row.feedingValue,
                dataSource: row.dataSource,
                heat: row.heat,
                releasePoint: row.releasePoint,
            }
            this.dialogVisible = true
        },
        deleteCurrentRowGoods(row) {
            this.goodsId = row.goodsId
            ElMessageBox.confirm(
                '该操作会删除选择的物料数据。\n是否继续',
                '警告',
                {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                const params = {
                    goodsId: this.goodsId,
                    userName: store.getters.getUserName
                }
                deleteGoodsInfo(params).then(res => {
                    if (res.data.code == 0) {
                        ElMessage.success('删除物料信息成功')
                        this.search()
                    } else {
                        errorBox(res.data.message)
                    }
                }).catch(err => {
                    console.log(err)
                    errorBox('删除物料信息失败')
                })
            }).catch(() => {
                ElMessage.info('操作取消')
            })
        },
        submitGoodsInfo(formData) {
            const request = {
                goodsId: formData.goodsId,
                goodsName: formData.goodsName,
                goodsUnit: formData.goodsUnit,
                goodsType: formData.goodsType,
                providerType: formData.providerType,
                weight: formData.weight,
                weightUnit: formData.weightUnit,
                quantityPerBox: formData.quantityPerBox,
                unpackingType: formData.unpackingType,
                vehicleType: formData.vehicleType,
                vehicleTypeDescription: formData.vehicleTypeDescription,
                goodsInVehicleType: formData.goodsInVehicleType,
                feedingType: formData.feedingType,
                feedingValue: formData.feedingValue,
                heat: formData.heat,
                releasePoint: formData.releasePoint,
                dataSource: formData.dataSource,
                userName: store.getters.getUserName
            }
            updateGoodsInfo(request).then(res => {
                if (res.data.code == 0) {
                    this.dialogVisible = false
                    ElMessage.success('更新物料信息成功')
                    this.search()
                } else {
                    errorBox(res.data.message)
                }
            }).catch(err => {
                errorBox('更新物料信息失败')
            })
        },
        getCurrentRow(row) {
            this.goodsId = row.goodsId
        },
        exportExcel() {
            const params = {
                goodsId: this.goodsIdQuery.trim(),
                userName: store.getters.getUserName
            }
            downloadGoodsExcel(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) {
                    console.log(e)
                    errorBox('下载文件失败')
                }
            }).catch(err => {
                console.log(err)
                errorBox('导出失败')
            })
        },
    },
}
</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 {
    width: 10% inherit;
    justify-content: center;
}

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

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

.el-row .el-form-item .el-button {
    margin: auto;
}

.title-area {
    display: flex;
    /* min-height: 10%; */
    max-height: max-content;
    margin-bottom: 10px;
    min-width: inherit;
    border: solid 1px;
    border-radius: 10px;
    box-shadow: 0px 15px 10px -15px #000;
    overflow: auto;
    flex-direction: column;
    padding: 10px;
}
</style>