<template>
    <div style="margin-bottom: 10px">
        <el-config-provider :locale="zhCn">
            <el-row>
                <UploadExcelPart></UploadExcelPart>
            </el-row>
            <el-row style="margin-top: 10px;">
                <el-input v-model="queryKey" style="width: 256px; margin-right: 10px;" placeholder="零件号" />
                <el-button type="primary" @click="search()">搜索</el-button>
                <el-button type="warning" @click="reset()">重置</el-button>
                <el-button type="success" @click="search()">刷新</el-button>
                <el-button type="success" @click="exportExcel()">导出信息</el-button>
            </el-row>
            <br />
            <el-table :data="partInfos" stripe border v-loading="loading" class="table-class" max-height="650px"
                highlight-current-row @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.material" v-model="material">&nbsp;</el-radio>
                    </template>
                </el-table-column>
                <el-table-column prop="material" label="零件号" fixed="left" sortable min-width="120px" />
                <el-table-column prop="itemDesc" label="描述" fixed="left" min-width="120px" />
                <el-table-column prop="category" label="零件类型" fixed="left" sortable min-width="120px" />
                <el-table-column prop="categoryRemark" label="策略" min-width="120px" />
                <el-table-column prop="unloadPlace" label="卸货点" min-width="120px" />
                <el-table-column prop="kittingPoint" label="配料点" min-width="120px" />
                <el-table-column prop="property" label="可用性" min-width="120px" />
                <el-table-column prop="vendorId" label="供应商代码" min-width="120px" />
                <el-table-column prop="dataOwner" label="数据负责人" min-width="120px" />
                <el-table-column prop="partWeight" label="重量" min-width="120px" />
                <el-table-column prop="storageLocation" label="库位" min-width="120px" />
                <el-table-column prop="storageType" label="存储类型" min-width="120px" />
                <el-table-column prop="storageBin" label="BIN位" min-width="120px" />
                <el-table-column prop="vendorNameEN" label="供应商名称（英文）" min-width="120px" />
                <el-table-column prop="vendorNameCN" label="供应商名称（中文）" min-width="120px" />
                <el-table-column prop="vendorCountry" label="供应商国家/地区" min-width="120px" />
                <el-table-column prop="SLED" label="SLED" min-width="120px" />
                <el-table-column prop="updateDate" label="更新日期" min-width="120px" />
                <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">
                <el-form ref="goodsFormRef" :model="goodsFormEntity" :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="material">
                                <el-input v-model="goodsFormEntity.material" disabled />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="描述" prop="itemDesc">
                                <el-input v-model="goodsFormEntity.itemDesc" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16">
                        <el-col :span="12" :offset="0">
                            <el-form-item label="零件类型" prop="category">
                                <el-input v-model="goodsFormEntity.category" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="策略" prop="categoryRemark">
                                <el-input v-model="goodsFormEntity.categoryRemark" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16">
                        <el-col :span="12" :offset="0">
                            <el-form-item label="卸货点" prop="unloadPlace">
                                <el-input v-model="goodsFormEntity.unloadPlace" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="配料点" prop="kittingPoint">
                                <el-input v-model="goodsFormEntity.kittingPoint" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16">
                        <el-col :span="12" :offset="0">
                            <el-form-item label="可用性" prop="property">
                                <el-input v-model="goodsFormEntity.property" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="供应商代码" prop="vendorId">
                                <el-input v-model="goodsFormEntity.vendorId" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16">
                        <el-col :span="12" :offset="0">
                            <el-form-item label="数据负责人" prop="dataOwner">
                                <el-input v-model="goodsFormEntity.dataOwner" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="重量" prop="partWeight">
                                <el-input v-model="goodsFormEntity.partWeight" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16">
                        <el-col :span="12" :offset="0">
                            <el-form-item label="库位" prop="storageLocation">
                                <el-input v-model="goodsFormEntity.storageLocation" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="存储类型" prop="storageType">
                                <el-input v-model="goodsFormEntity.storageType" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16">
                        <el-col :span="12" :offset="0">
                            <el-form-item label="BIN位" prop="storageBin">
                                <el-input v-model="goodsFormEntity.storageBin" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="供应商名称（英文）" prop="vendorNameEN">
                                <el-input v-model="goodsFormEntity.vendorNameEN" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16">
                        <el-col :span="12" :offset="0">
                            <el-form-item label="供应商名称（中文）" prop="vendorNameCN">
                                <el-input v-model="goodsFormEntity.vendorNameCN" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="供应商国家/地区" prop="vendorCountry">
                                <el-input v-model="goodsFormEntity.vendorCountry" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16">
                        <el-col :span="12" :offset="0">
                            <el-form-item label="SLED" prop="SLED">
                                <el-input-number v-model.number="goodsFormEntity.SLED" clearable controls-position="right"
                                    :min="0" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="更新日期" prop="updateDate">
                                <el-input v-model="goodsFormEntity.updateDate" clearable />
                            </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="submitGoodsInfo(goodsFormEntity)">
                            确定
                        </el-button>
                    </span>
                </template>
            </el-dialog>
        </el-config-provider>
    </div>
</template>

<script setup>
import { getPartInfo, updatePartInfo, deleteCurrentPartInfo } from '@/api/goods.js'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { ElMessage } from 'element-plus'
import { ref, reactive } from 'vue'
import { dateFormatter } from '@/utils/formatter.js'
import UploadExcelPart from '@/excel/UploadExcelPart.vue'
import { downloadMaterialExcel } from '@/api/excel.js'
</script>
<script>
export default {
    name: 'goods',
    data() {
        return {
            partInfos: [],
            pageInfo: {},
            currentPage: 1,
            pageSize: 10,
            total: 0,
            queryKey: '',
            loading: true,
            dialogVisible: false,
            material: '',
            goodsFormEntity: reactive({}),
            labelPosition: 'top',
            goodsFormRef: ref(),
            rules: reactive({})
        }
    },
    mounted() {
        this.search()
    },
    methods: {
        search() {
            this.loading = true
            this.pageInfo.pageNum = this.currentPage
            this.pageInfo.pageSize = this.pageSize
            const tableRequest = {
                page: this.pageInfo,
                param: {
                    material: this.queryKey.trim()
                },
            }
            getPartInfo(tableRequest).then(res => {
                const tableResponse = res.data
                if (tableResponse.code != 0) {
                    console.log(tableResponse.code + ':' + tableResponse.message)
                    ElMessage.error(tableResponse.message)
                }
                this.partInfos = tableResponse.rows
                this.total = tableResponse.total
            }).catch(err => {
                ElMessage.error('查询物料错误' + err.message)
            })
            this.loading = false
        },
        dateFormat: (row, column, cellValue, index) => {
            return dateFormatter(cellValue)
        },
        reset() {
            this.queryKey = ''
            this.search
        },
        // getCurrentPageGoods() {
        //     this.currentGoods = this.displayGoods.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
        // },
        editCurrentRowGoods(row) {
            this.goodsFormEntity = row
            this.dialogVisible = true
        },
        deleteCurrentRowGoods(row) {
            this.material = row.material
            const goods = {
                material: row.material
            }
            deleteCurrentPartInfo(goods).then(res => {
                if (res.data.code == 0) {
                    ElMessage({
                        message: '删除零件信息成功',
                        type: 'success',
                    })
                    this.search()
                } else {
                    ElMessage.error(res.data.message)
                }
            }).catch(err => {
                ElMessage.error('删除零件信息失败:' + err)
            })
        },
        submitGoodsInfo(formData) {
            updatePartInfo(formData).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.error('更新零件信息失败')
            })
        },
        getCurrentRow(row) {
            this.goodsId = row.goodsId
        },
        exportExcel() {
        downloadMaterialExcel().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
            })
        })
    },
    },
    // watch: {
    //     currentPage() {
    //         this.getCurrentPageGoods()
    //     },
    //     pageSize() {
    //         this.getCurrentPageGoods()
    //     }
    // }
}
</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;
}
</style>