<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="订单编号" prop="orderNo">
                <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="订单状态" prop="orderStatus">
                <el-select v-model="queryParams.orderStatus" placeholder="请选择支付状态" clearable>
                    <el-option v-for="dict in dict.type.purchase_order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" @click="addOrder" v-hasPermi="['order:purchaseGoods:add']">新增</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="orderLoading" :data="purchaseGoodsList" @selection-change="handleSelectionChange">
            <!--      <el-table-column type="selection" width="55" align="center" fixed="left"/>-->
            <el-table-column label="订单编号" align="center" prop="orderNo" width="250px" />
            <el-table-column label="进货总价（元）" align="center" prop="costTotalPrice" width="200px" />
            <el-table-column label="订单状态" align="center" prop="orderStatus" width="200px">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.purchase_order_status" :value="scope.row.orderStatus" />
                </template>
            </el-table-column>
            <el-table-column label="支付方式" align="center" prop="payType" width="200px">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.recharge_pay_type" :value="scope.row.payType" />
                </template>
            </el-table-column>
            <el-table-column label="下单时间" align="center" prop="createTime" width="200px" />
            <el-table-column label="支付时间" align="center" prop="payTime" width="200px" />
            <el-table-column label="发货时间" align="center" prop="sendTime" width="200px" />
            <el-table-column label="确认收货时间" align="center" prop="finishTime" width="200px" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
                <template slot-scope="scope">
                    <el-button type="text" icon="el-icon-chat-dot-square" @click="orderDetail(scope.row)">订单详情</el-button>
                    <el-button type="text" icon="el-icon-check" @click="confirmReceive(scope.row)" v-hasPermi="['order:purchaseGoods:edit']" v-if="scope.row.orderStatus == '3' || scope.row.orderStatus == '4'">确认收货</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!--新增-->
        <el-dialog :title="title" :visible.sync="open" size="70%" append-to-body>
            <el-card>
                <el-row :gutter="20">
                    <el-col :span="4">
                        <div class="list_title">{{ titleType }}</div>
                        <div class="head-container-two">
                            <el-tree :data="categoryList" :props="defaultProps" :expand-on-click-node="false" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick" />
                        </div>
                    </el-col>
                    <el-col :span="20">
                        <div class="head-column1">
                            <el-table :data="addGoodsList">
                                <el-table-column label="编号" align="center" prop="goodsSkuStoreId" />
                                <el-table-column label="材料名称" align="center" prop="goodsName" />
                                <el-table-column label="材料规格" align="center">
                                    <template slot-scope="scope">
                                        <div v-for="spec in scope.row.specVoList" :key="spec.id" style="height: 20px">
                                            <p style="text-align: center; margin-top: 1px">{{ spec.specName }}:{{ spec.specValue }}</p>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="数量" align="center">
                                    <template slot-scope="scope">
                                        <el-input-number v-if="scope.row.goodsSkuStoreId == vo.goodsSkuStoreId" v-for="vo in purchaseCountVOList" :key="vo.goodsSkuStoreId" v-model="vo.count" :step="1" :min="1" :max="getMaxCount(scope.row)" @change="countPrice" />
                                    </template>
                                </el-table-column>
                                <el-table-column label="价格" align="center" prop="purchasePrice" />
                                <!--            <el-table-column label="库存" align="center" prop="stock" />-->
                                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                                    <template slot-scope="scope">
                                        <el-button type="text" icon="el-icon-delete-solid" @click="deleteGoods(scope.row)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-col>
                    <el-col :span="20">
                        <div class="head-column1" style="margin-top: 20px">
                            <el-table v-loading="loading" fit highlight-current-row border stripe :data="goodsList">
                                <el-table-column label="编号" align="center" prop="goodsSkuStoreId" />
                                <el-table-column label="材料名称" align="center" prop="goodsName" />
                                <el-table-column label="材料规格" align="center">
                                    <template slot-scope="scope">
                                        <div v-for="spec in scope.row.specVoList" :key="spec.id" style="height: 20px">
                                            <p style="text-align: center; margin-top: 1px">{{ spec.specName }}:{{ spec.specValue }}</p>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="价格" align="center" prop="purchasePrice" />
                                <el-table-column label="库存" align="center" prop="stock" />
                                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                                    <template slot-scope="scope">
                                        <el-button type="text" icon="el-icon-s-shop" @click="addGoods(scope.row)">添加</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-col>
                </el-row>
                <el-row :gutter="10" class="box-shadow" style="margin-top: 10px">
                    <el-col :span="3">
                        <el-form label-width="100px" style="height: 100px; padding-top: 40px; text-align: right" :inline="true" size="small">
                            <el-form-item v-if="goodsType == '1' && userInfoVO.userType != '00'">
                                <el-checkbox v-model="isUserBalance">是否使用余额</el-checkbox>
                            </el-form-item>
                        </el-form>
                    </el-col>
                    <el-col :span="18">
                        <el-form label-width="135px" style="height: 100px; padding-top: 40px; text-align: right" :inline="true" size="small">
                            <el-form-item label="当前余额（元）：" v-if="goodsType == '1'">
                                <span style="color: #ff4949">{{ getNowBalanceValue }}</span>
                            </el-form-item>
                            <el-form-item label-width="100px" label="总件数:" prop="totalClothNum">
                                <span style="color: #ff4949">{{ calculateTotalCount }}</span>
                            </el-form-item>
                            <el-form-item label="总金额（元）:" prop="totalPrice">
                                <span style="color: #ff4949">{{ calculateTotalPrice }}</span>
                            </el-form-item>
                            <el-form-item label="抵扣金额（元）: " v-if="isUserBalance == true">
                                <span style="color: #ff4949">{{ getNowBalance }}</span>
                            </el-form-item>
                            <el-form-item label-width="155px" label="还需支付金额（元）: " v-if="isUserBalance == true">
                                <span style="color: #ff4949">{{ getNeedPayPrice }}</span>
                            </el-form-item>
                        </el-form>
                    </el-col>
                    <el-col :span="3">
                        <el-button type="primary" style="width: 50%; height: 40px; margin-top: 30px; text-align: center" icon="el-icon-shopping-cart-2" size="small" @click="submitForm">提交</el-button>
                    </el-col>
                </el-row>
            </el-card>
        </el-dialog>

        <!--    详情-->
        <el-dialog :title="detailTitle" :visible.sync="openDetail" size="80%">
            <el-card>
                <el-descriptions title="基本信息" v-show="detailView" :column="3" border :label-style="{ 'text-align': 'center' }" :contentStyle="{ 'text-align': 'center' }">
                    <el-descriptions-item label="订单状态">
                        <dict-tag :options="dict.type.purchase_order_status" :value="detailView.orderStatus" />
                    </el-descriptions-item>
                    <el-descriptions-item label="下单时间">{{ detailView.createTime ? detailView.createTime : '暂无信息' }}</el-descriptions-item>
                    <el-descriptions-item label="支付时间">{{ detailView.payTime ? detailView.payTime : '暂无信息' }}</el-descriptions-item>
                    <el-descriptions-item label="发货时间">{{ detailView.sendTime ? detailView.sendTime : '暂无信息' }}</el-descriptions-item>
                    <el-descriptions-item label="确认收货时间">{{ detailView.finishTime ? detailView.finishTime : '暂无信息' }}</el-descriptions-item>
                    <el-descriptions-item label="订单总价（元）">{{ costTotalPrice ? costTotalPrice : '暂无信息' }}</el-descriptions-item>
                    <el-descriptions-item label="物流公司">{{ detailView.deliveryCompany ? detailView.deliveryCompany : '暂无信息' }}</el-descriptions-item>
                    <el-descriptions-item label="物流单号" span="2">{{ detailView.deliveryNo ? detailView.deliveryNo : '暂无信息' }}</el-descriptions-item>
                    <el-descriptions-item label="收货地址" span="3">{{ detailView.province }}{{ detailView.city }}{{ detailView.area }}{{ detailView.address }}{{ detailView.addressDetail }}</el-descriptions-item>
                    <el-descriptions-item label="备注信息" span="3">{{ detailView.remark ? detailView.remark : '暂无信息' }}</el-descriptions-item>
                </el-descriptions>
            </el-card>
            <div class="head-column2">
                <el-table v-loading="loading" fit highlight-current-row border stripe :data="detailList">
                    <el-table-column label="分类" align="center" prop="goodsCategoryName" />
                    <el-table-column :label="goodsType == 0 ? '商品名称' : '材料名称'" align="center" prop="goodsName" width="250px" />
                    <el-table-column :label="goodsType == 0 ? '商品规格' : '材料规格'" align="center" width="250px">
                        <template slot-scope="scope">
                            <div style="text-align: center">{{ scope.row.skuName.replace(' ', '/') }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="数量" align="center" prop="buyNum" />
                    <el-table-column label="价格（元）" align="center" prop="costPrice" />
                    <el-table-column label="总和（元）" align="center">
                        <template slot-scope="scope">
                            <span>{{ (scope.row.buyNum * 10000 * parseFloat(scope.row.costPrice)) / 10000 }}</span>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <el-row :gutter="10" class="box-shadow" style="margin-top: 10px">
                <el-col :span="21">
                    <el-form label-width="130px" style="height: 80px; padding-top: 20px; text-align: right" :inline="true" size="small">
                        <el-form-item label="总金额（元）:">
                            {{ costTotalPrice }}
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
        </el-dialog>
    </div>
</template>

<script>
import { purchaseListSku } from '@/api/core/sku'
import { listCategory } from '@/api/core/category'
import { addPurchaseGoods, getPurchaseGoods, listPurchaseGoods, confirmReceiveGoodsByOrderGoods } from '@/api/order/purchaseGoods'
import { getFactoryInfo } from '@/api/system/factory'
import { getStoreInfo } from '@/api/system/store'
export default {
    name: 'goodsPurchase',
    dicts: ['purchase_order_status', 'recharge_pay_type'],
    data() {
        return {
            //
            orderLoading: true,
            // 遮罩层
            loading: false,
            detailLoading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 弹出层标题
            title: '',
            titleType: '',
            detailTitle: '',
            // 详情数据
            detailView: {},
            // 是否显示弹出层
            open: false,
            openDetail: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {},
            goodsType: null,
            // 商品订单表格数据
            purchaseGoodsList: [],
            // 分类id
            goodsCategoryId: null,
            // 可选商品集合
            goodsList: null,
            // 已选商品集合
            addGoodsList: [],
            // 左侧分类集合
            categoryList: null,
            //
            defaultProps: {
                label: 'categoryName'
            },
            // 自定义一个计算数量的临时对象集合
            purchaseCountVOList: [],
            // 总金额
            totalPrice: 0,
            // 总件数
            totalCount: 0,
            // 当前余额
            getNowBalance: 0,
            // 提交的参数对象
            submitGoodsOrderVO: {},
            // 详情数据
            detailList: [],
            // 详情总金额
            costTotalPrice: null,
            userInfoVO: null,
            isUserBalance: false,
            orgName: ''
        }
    },
    created() {
        this.handleUser()
        this.goodsType = this.getUrlParam('goodsType')
        this.getList()
    },
    computed: {
        calculateTotalCount() {
            this.totalCount = 0
            this.addGoodsList.forEach((vo) => {
                let number = this.purchaseCountVOList.find((item) => item.goodsSkuStoreId == vo.goodsSkuStoreId).count
                this.totalCount = this.totalCount + number
            })
            return this.totalCount
        },
        calculateTotalPrice() {
            this.totalPrice = 0
            this.addGoodsList.forEach((vo) => {
                let number = this.purchaseCountVOList.find((item) => item.goodsSkuStoreId == vo.goodsSkuStoreId).count
                this.totalPrice = this.totalPrice + number * vo.purchasePrice
            })
            return this.totalPrice
        },
        getNowBalanceValue() {
            return this.getNowBalance
        },
        getNeedPayPrice() {
            // 当订单金额 = 余额
            if (this.totalPrice == this.getNowBalance) {
                return 0
            }
            // 当订单金额 大于 余额
            if (this.totalPrice > this.getNowBalance) {
                return (parseFloat(this.totalPrice) * 10000 - parseFloat(this.getNowBalance) * 10000) / 10000
            }
            // 当订单金额 小于等于 余额
            return (parseFloat(this.getNowBalance) * 10000 - parseFloat(this.totalPrice) * 10000) / 10000
        }
    },
    methods: {
        handleUser() {
            this.userInfoVO = this.getUserInfo()
            if (this.userInfoVO.userType == '00') {
                this.orgName = '总部'
            }
            if (this.userInfoVO.userType == '01') {
                this.orgName = '工厂名称'
            }
            if (this.userInfoVO.userType == '02') {
                this.orgName = '门店名称'
            }
        },
        getCategoryList() {
            listCategory({ ...this.queryParams, ...{ goodsType: this.goodsType } }).then((response2) => {
                this.categoryList = response2.rows
            })
        },
        deleteGoods(row) {
            this.addGoodsList = this.addGoodsList.filter((item) => {
                return item.goodsSkuStoreId !== row.goodsSkuStoreId
            })
            this.purchaseCountVOList = this.purchaseCountVOList.filter((item) => {
                return item.goodsSkuStoreId !== row.goodsSkuStoreId
            })
        },
        addGoods(row) {
            // 非总部进货
            if (this.userInfoVO.userType != '00') {
                // 判断上级库存
                if (row.stock <= 0) {
                    this.$message.error('库存不足，无法添加')
                    return
                }
                // 如果已添加集合数量大于0， 需要判断当前添加的是否在已添加集合中
                // 在已添加集合中，直接添加数量+1
                if (this.addGoodsList.length > 0) {
                    let match = this.addGoodsList.findIndex((item) => item.goodsSkuStoreId == row.goodsSkuStoreId)
                    if (match != '-1') {
                        let purchaseVo = this.purchaseCountVOList.find((item) => item.goodsSkuStoreId == row.goodsSkuStoreId)
                        if (purchaseVo.count >= row.stock) {
                            this.$message.error('数量已超出')
                            return
                        }
                        this.purchaseCountVOList.find((item) => item.goodsSkuStoreId == row.goodsSkuStoreId).count++
                        this.$forceUpdate()
                        return
                    }
                }
                // 不在已添加集合中，直接加入集合中
                this.addGoodsList.push(row)
                this.purchaseCountVOList.push({
                    goodsSkuStoreId: row.goodsSkuStoreId,
                    goodsCategoryId: this.goodsCategoryId,
                    goodsCategoryName: this.categoryList.find((item) => item.id == this.goodsCategoryId).categoryName,
                    count: 1
                })
                this.$forceUpdate()
            } else {
                // 总部进货， 无需判断上级库存
                if (this.addGoodsList.length > 0) {
                    let match = this.addGoodsList.findIndex((item) => item.goodsSkuStoreId == row.goodsSkuStoreId)
                    if (match != '-1') {
                        this.purchaseCountVOList.find((item) => item.goodsSkuStoreId == row.goodsSkuStoreId).count++
                        this.$forceUpdate()
                        return
                    }
                }
                // 不在已添加集合中，直接加入集合中
                this.addGoodsList.push(row)
                this.purchaseCountVOList.push({
                    goodsSkuStoreId: row.goodsSkuStoreId,
                    goodsCategoryId: this.goodsCategoryId,
                    goodsCategoryName: this.categoryList.find((item) => item.id == this.goodsCategoryId).categoryName,
                    count: 1
                })
                this.$forceUpdate()
            }
        },
        getMaxCount(row) {
            if (this.userInfoVO.userType != '00') {
                return row.stock
            } else {
                return 99999
            }
        },
        countPrice() {
            this.totalPrice = 0
            this.totalCount = 0
            this.addGoodsList.forEach((vo) => {
                let number = this.purchaseCountVOList.find((item) => item.goodsSkuStoreId == vo.goodsSkuStoreId).count
                this.totalPrice = this.totalPrice + number * vo.purchasePrice
                this.totalCount = this.totalCount + number
            })
        },
        // 节点单击事件
        handleNodeClick(data) {
            this.goodsCategoryId = data.id
            this.getGoodsList()
        },
        getList() {
            this.orderLoading = true
            listPurchaseGoods({ ...this.queryParams, ...{ goodsType: this.goodsType } }).then((response) => {
                this.purchaseGoodsList = response.rows
                this.total = response.total
                this.orderLoading = false
            })
        },
        getGoodsList() {
            this.loading = true
            if (this.goodsCategoryId == null) {
                this.goodsList = []
                this.loading = false
                return
            }
            purchaseListSku(this.goodsCategoryId).then((response) => {
                this.goodsList = response.data
                this.loading = false
            })
        },
        addOrder() {
            this.open = true
            this.isUserBalance = false
            this.title = this.goodsType == '0' ? '商品进货' : '材料申请'
            this.titleType = this.goodsType == '0' ? '商品分类' : '材料分类'
            this.purchaseCountVOList = []
            this.addGoodsList = []
            this.addGoodsList = []
            this.goodsList = []
            this.getBalance()
            this.getCategoryList()
        },
        getBalance() {
            if (this.userInfoVO.userType == '01') {
                getFactoryInfo().then((response) => {
                    this.getNowBalance = response.data.balance
                })
            }
            if (this.userInfoVO.userType == '02') {
                getStoreInfo().then((response) => {
                    this.getNowBalance = response.row.balance
                })
            }
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        orderDetail(row) {
            this.openDetail = true
            this.detailTitle = '订单商品详情'
            this.detailLoading = true
            this.detailList = []
            this.detailView = {}
            const id = row.id
            getPurchaseGoods(id).then((response) => {
                this.detailView = response.data
                this.detailList = response.data.orderPurchaseGoodsVOList
                this.costTotalPrice = this.detailList[0].costTotalPrice
                this.detailLoading = false
            })
        },
        confirmReceive(row) {
            this.$confirm('是否确认收货？')
                .then(() => {
                    confirmReceiveGoodsByOrderGoods(row.id).then((response2) => {
                        this.$message.success('操作成功')
                        this.getList()
                    })
                })
                .catch(() => {})
        },
        checkClose(done) {
            this.$confirm('是否关闭表单，关闭后数据将丢失？')
                .then(function () {
                    done()
                })
                .then(() => {})
                .catch(() => {})
        },
        submitForm() {
            this.$confirm('是否确认下单？')
                .then(() => {
                    if (this.totalCount == 0) {
                        this.$message.error('商品数量为空，无法操作提交')
                    }
                    this.submitGoodsOrderVO.costTotalPrice = this.totalPrice
                    this.submitGoodsOrderVO.goodsType = this.goodsType
                    this.submitGoodsOrderVO.purchaseGoodsVOList = []
                    if (this.userInfoVO.userType != '00' && this.isUserBalance == true) {
                        this.submitGoodsOrderVO.isUserBalance = true
                    } else {
                        this.submitGoodsOrderVO.isUserBalance = false
                    }

                    this.addGoodsList.forEach((vo) => {
                        let purchaseVO = this.purchaseCountVOList.find((item) => item.goodsSkuStoreId == vo.goodsSkuStoreId)
                        let purchaseGoodsVO = {}
                        purchaseGoodsVO.skuId = vo.id
                        purchaseGoodsVO.goodsId = vo.goodsId
                        purchaseGoodsVO.goodsCategoryId = purchaseVO.goodsCategoryId
                        purchaseGoodsVO.goodsCategoryName = purchaseVO.goodsCategoryName
                        purchaseGoodsVO.costPrice = vo.purchasePrice
                        purchaseGoodsVO.buyNum = purchaseVO.count
                        purchaseGoodsVO.skuName = ''
                        vo.specVoList.forEach((spec) => {
                            purchaseGoodsVO.skuName = purchaseGoodsVO.skuName + spec.specName + ':' + spec.specValue + ' '
                        })
                        this.submitGoodsOrderVO.purchaseGoodsVOList.push(purchaseGoodsVO)
                    })

                    addPurchaseGoods(this.submitGoodsOrderVO).then((response) => {
                        this.$modal.msgSuccess('提交成功')
                        this.open = false
                        this.getList()
                    })
                })
                .catch(() => {})
        }
    }
}
</script>
<style>
.list_title {
    text-align: center;
    line-height: 40px;
}
.head-container-two {
    height: 500px;
    display: block;
    overflow-y: scroll;
}
.head-column1 {
    height: 300px;
    display: block;
    overflow-y: scroll;
}
.head-column2 {
    height: 600px;
    display: block;
    overflow-y: scroll;
}
.box-shadow .el-button--medium {
    font-size: 18px;
}
</style>
