<template>
    <div class="app-container">
        <div class="head-container">
            <div class="row_wrap">
                <div class="row">
                    <el-input v-model="query.name" size="small" clearable placeholder="商品名称"
                        @keyup.enter.native="getTableData" />
                    <!-- <el-input v-model="query.num" placeholder="库存数量：少于多少xx" /> -->
                    <div style="width: 300px;">
                        <el-select v-model="query.categoryId" placeholder="商品分类" style="width: 100%;">
                            <el-option :label="item.name" :value="item.id" v-for="item in categorys" :key="item.id" />
                        </el-select>
                    </div>
                    <div style="width: 300px;">
                        <el-select v-model="query.isStock" placeholder="库存开关" style="width: 100%;">
                            <el-option label="开" :value="1">开</el-option>
                            <el-option label="关" :value="0">关</el-option>
                        </el-select>
                    </div>
                    <div style="width: 300px;">
                        <el-select v-model="query.sort" placeholder="排序">
                            <el-option label="默认排序" value="false" />
                            <el-option label="库存降序" value="true" />
                        </el-select>
                    </div>
                    <el-button type="primary" @click="getTableData">查询</el-button>
                    <el-button @click="resetHandle">重置</el-button>
                    <el-button @click="Uppop()">库存预警:{{ warnLine }}</el-button>
                </div>
                <div class="row">
                    <el-button icon="el-icon-download" :loading="downloadLoading" @click="protHandle">导出库存</el-button>
                    <el-button icon="el-icon-upload2" :loading="uploadLoading"
                        @click="dialogVisible = true">导入库存</el-button>
                </div>
            </div>
        </div>
        <div class="head-container">
            <el-table :data="tableData.list" v-loading="tableData.loading" row-key="id" lazy :load="load"
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                <el-table-column width="30">
                    <template v-slot="scope">
                        <i class="" v-if="scope.row.hasChildren == false"></i>
                        <!-- <div v-if="scope.row.iskaiguans == 1" style="padding-left: 20px;"></div> -->
                    </template>
                </el-table-column>
                <el-table-column label="商品信息" width="200px">
                    <template v-slot="scope">
                        <div class="shop_info">
                            <el-image :src="scope.row.img" class="cover" v-if="scope.row.iskaiguans != 1">
                                <div class="img_error" slot="error">
                                    <i class="icon el-icon-document-delete"></i>
                                </div>
                            </el-image>
                            <div class="info">
                                <span>{{ scope.row.name }}</span>
                                <div v-if="scope.row.iskaiguans != 1">
                                    <el-tag type="primary">{{ scope.row.type }}</el-tag>
                                </div>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="规格" prop="number">
                    <template v-slot="scope">
                        <div v-if="scope.row.iskaiguans">
                            {{ scope.row.specSnap }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="库存" prop="number">
                    <template v-slot="scope">
                        <span v-if="!scope.row.isStock"
                            :class="[scope.row.stockNumber <= warnLine ? 'colorStyle' : '']">
                            <span v-if="scope.row.stockNumber < 0"
                                style="font-weight: 700;color: #999;font-size: 14px;">-</span>
                            <span>
                                <span> {{ Math.abs(scope.row.stockNumber) }}</span>
                                <span> {{ scope.row.unitName }}</span>
                            </span>

                        </span>
                        <span v-else :class="[scope.row.stockNumber <= warnLine ? 'colorStyle' : '']">
                            {{ `${scope.row.stockNumber} ${scope.row.unitName}` }}
                        </span>
                    </template>
                </el-table-column>

                <el-table-column label="库存开关">
                    <template v-slot="scope">
                        <el-switch v-model="scope.row.isStock" :active-value="1" :inactive-value="0"
                            v-if="scope.row.hasChildren || scope.row.hasChildren == false"
                            @change="showChange($event, scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="共享库存">
                    <template v-slot="scope">
                        <el-switch v-model="scope.row.isDistribute" :active-value="1" :inactive-value="0"
                            v-if="scope.row.hasChildren || scope.row.hasChildren == false"
                            @change="showChanges($event, scope.row, 'proId', 'distribute')"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="售罄">
                    <template v-slot="scope">
                        <el-switch v-model="scope.row.isPauseSale" :active-value="1" :inactive-value="0"
                            @change="showChangess($event, scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="上架">
                    <template v-slot="scope">
                        <el-switch v-model="scope.row.isGrounding" :active-value="true" :inactive-value="false"
                            v-if="!scope.row.hasChildren" @change="showChangesss($event, scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="240px">
                    <template v-slot="scope">
                        <el-button type="text" size="mini"
                            @click="$refs.invoicingDetail.show(scope.row)">库存记录</el-button>
                        <template v-if="!scope.row.hasChildren">
                            <el-button type="text" size="mini" style="margin-left: 10px !important;"
                                @click="$refs.AddStockTakin.show(scope.row)">库存盘点</el-button>
                        </template>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="head-container">
            <el-pagination @size-change="paginationSizeChange" :total="tableData.total"
                :current-page="tableData.page + 1" :page-size="tableData.size" @current-change="paginationChange"
                layout="total, sizes, prev, pager, next, jumper"></el-pagination>
        </div>
        <invoicingDetail ref="invoicingDetail" />
        <!-- 导入库存弹窗 -->
        <el-dialog title="导入库存" :visible.sync="dialogVisible">
            <UploadExcel :beforeUpload="excelSuccessUpload" />
        </el-dialog>
        <!-- 预存弹窗组件 -->
        <el-dialog title="" :visible.sync="dialogTableVisible" width="350px">
            <el-form>
                <el-form-item label="库存预存设置" label-width="120px">
                    <el-input v-model="montey" type="number" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogTableVisible = false; montey = ''">取 消</el-button>
                <el-button type="primary" @click="sumbit()">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 新增库存盘点 -->
        <AddStockTakin ref="AddStockTakin" @success="resetHandle" />
    </div>
</template>

<script>
import { stock, stockdownload, stockdoImport, stockStatewarnLine, stockStateChanges, stocks, stockStateChangess } from '@/api/invoicing'
import { tbShopCategoryGet } from '@/api/shop'
import settings from '@/settings'
import invoicingDetail from './components/invoicingDetail'
import AddStockTakin from './components/addStockTakin'
import UploadExcel from '@/components/UploadExcel/'
import { downloadFile } from "@/utils/index";
export default {
    components: {
        invoicingDetail,
        UploadExcel,
        AddStockTakin
    },
    data() {
        return {
            dialogVisible: false,
            dialogTableVisible: false,
            montey: "",
            categorys: [],
            query: {
                sort: "false", // 排序
                name: '',
                isStock: '',
                num: '',
                categoryId: ''
            },
            resetQuery: '',
            downloadLoading: false,
            uploadLoading: false,
            warnLine: null, // 警戒线
            tableData: {
                page: 0,
                size: 10,
                total: 0,
                sort: 'id',
                loading: false,
                list: []
            }
        }
    },
    mounted() {
        this.resetQuery = { ...this.query }
        this.tbShopCategoryGet()
        this.getTableData()
    },
    methods: {
        Uppop() {
            this.dialogTableVisible = true
        },
        async sumbit() {
            try {
                const res = await stockStatewarnLine({
                    shopId: localStorage.getItem("shopId"),
                    warnLine: this.montey
                })

                this.$message({ type: 'success', message: '修改成功!' });
                setTimeout(() => {
                    this.dialogTableVisible = false
                    this.montey = ''
                    this.getTableData()
                }, 500);

            } catch (error) {
                console.log(error);
            }
        },
        async load(tree, treeNode, resolve) {
            const res = await stocks({
                productId: tree.proId,
            })
            res.forEach(ele => ele.iskaiguans = 1)
            setTimeout(() => {
                resolve(res)
            }, 50);
        },
        async excelSuccessUpload(file) {
            console.log(file);
            try {
                this.uploadLoading = true
                this.dialogVisible = false
                const res = await stockdoImport(file)
                this.uploadLoading = false
                this.$notify.success('导入成功')
                this.tableData.list = []
                this.getTableData()
            } catch (error) {
                this.dialogVisible = false
                this.uploadLoading = false
                console.log(error);
            }
        },
        // 导出库存
        async protHandle() {
            try {
                this.downloadLoading = true;
                const file = await stockdownload({
                    name: this.query.name,
                    isStock: this.query.isStock,
                    num: this.query.num,
                })
                downloadFile(file, "商品库存", "xlsx");
                this.downloadLoading = false;
            } catch (error) {
                this.downloadLoading = false;
                console.log(error);
            }
        },
        // 状态切换
        async showChange(e, row) {
            await stockStateChanges({
                "updateKey": 'stock',
                "updateValue": row.isStock,
                "targetId": row.proId,
                shopId: localStorage.getItem('shopId')

            })

        },
        // 共享库存
        async showChanges(e, row, name, value) {
            await stockStateChanges({
                "updateKey": value,
                "updateValue": row.isDistribute,
                "targetId": row[name],
                shopId: localStorage.getItem('shopId')

            })
            this.tableData.list = []
            this.getTableData()

        },
        // 售罄
        async showChangess(e, row) {
            if (row.hasChildren || row.hasChildren == false) {
                await stockStateChanges({
                    "updateKey": 'pauseSale',
                    "updateValue": row.isPauseSale,
                    "targetId": row.proId,
                    shopId: localStorage.getItem('shopId')

                })
            } else {
                await stockStateChanges({
                    "updateKey": 'pauseSaleSku',
                    "updateValue": row.isPauseSale,
                    "targetId": row.skuId,
                    shopId: localStorage.getItem('shopId')

                })
            }

        },
        // 下架
        async showChangesss(e, row) {
            await stockStateChangess({
                "isGrounding": row.isGrounding,
                skuId: row.skuId,
                shopId: localStorage.getItem('shopId')
            })
            this.$message({
                type: "success",
                message: "修改成功"
            })
        },
        async getTableData() {
            this.tableData.loading = true
            try {
                const res = await stock({
                    page: this.tableData.page,
                    size: this.tableData.size,
                    name: this.query.name,
                    isStock: this.query.isStock,
                    num: this.query.num,
                    categoryId: this.query.categoryId,
                    sort: this.query.sort,
                    shopId: localStorage.getItem('shopId')
                })
                this.tableData.loading = false
                this.tableData.total = res.totalElements
                // 多规格数据处理
                res.content.forEach(element => {
                    if (element.type == '多规格' && element.isDistribute == 0) {
                        element.hasChildren = true
                    } else {
                        element.hasChildren = false
                    }
                });
                this.warnLine = res.warnLine
                this.tableData.list = res.content
                console.log(this.tableData.list);
            } catch (error) {
                console.log(error);
            }
        },
        // 获取商品分类列表
        async tbShopCategoryGet() {
            try {
                const res = await tbShopCategoryGet({
                    shopId: localStorage.getItem('shopId'),
                    page: 0,
                    size: 100,
                    sort: 'id'
                })
                let categorys = []
                for (let item of res.content) {
                    categorys.push({
                        name: `|----${item.name}`,
                        id: item.id
                    })
                    if (item.childrenList.length) {
                        for (let val of item.childrenList) {
                            categorys.push({
                                name: `|----|----${val.name}`,
                                id: val.id
                            })
                        }
                    }
                }
                this.categorys = categorys
            } catch (error) {
                console.log(error)
            }
        },
        // 每页条数改变是回调
        paginationSizeChange(e) {
            console.log(e);
            this.tableData.size = e
            this.tableData.page = 0
            this.getTableData()
        },
        // 分页回调
        paginationChange(e) {
            console.log(e)
            this.tableData.page = e - 1
            this.tableData.list = []
            this.getTableData()
        },
        // 重置查询
        resetHandle() {
            this.query = { ...this.resetQuery }
            this.tableData.page = 0;
            this.tableData.list = []
            this.getTableData()
        }
    }
}
</script>

<style scoped lang="scss">
::v-deep .cell {
    display: flex;
    align-items: center;
    /* flex-direction: row-reverse; */
}

.shop_info {
    display: flex;
    align-items: center;

    .cover {
        $size: 50px;
        width: $size;
        height: $size;
        border-radius: 2px;
        background-color: #efefef;
    }

    .info {
        display: flex;
        flex-direction: column;
        padding-left: 10px;
        justify-content: space-between;
    }
}

.row_wrap {
    display: flex;
    justify-content: space-between;

    .row {
        display: flex;
        align-items: center;
        gap: 10px;
    }
}

.colorStyle {
    color: rgb(231, 42, 42);
    font-weight: 700;
}
</style>
