<template>
    <div>

        <el-form :model="formData" ref="dataForm">
            <el-button-group style="display: flex;margin: -50px 0 10px 80%; height: 35px">
                <el-button
                    v-if="countType != 2"
                    type="primary"
                    :disabled="this.codeArray.length > 0"
                    @click.native="startCount()"
                >开始盘点
                </el-button>
                <el-button
                    v-if="countType == 2"
                    type="primary"
                    :disabled="this.codeArray.length > 0"
                    @click.native="startCount()"
                >录入产品
                </el-button>
                <el-button
                    type="primary"
                    @click.native="saveOrder()"
                >保存
                </el-button>
            </el-button-group>

            <el-row :gutter="20" style="margin-top: 20px;">
                <el-col :span="3">
                    <div class="ao-text">
                        <span>盘点单号：</span>
                    </div>
                </el-col>
                <el-col :span="7">
                    <el-form-item prop="orderId">
                        <el-input v-model="formData.orderId" auto-complete="off" :disabled="true"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="3">
                    <div class="ao-text">
                        <span>盘点日期：</span>
                    </div>
                </el-col>
                <el-col :span="7">
                    <el-form-item prop="billDate">
                        <el-input v-model="formData.billDate" auto-complete="off" :disabled="true"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20" style="margin-top: 0px">
                <el-col :span="3">
                    <div class="ao-text">
                        <span>盘点仓库：</span>
                    </div>
                </el-col>

                <el-col :span="7">
                    <el-form-item prop="invStorageCode">
                        <el-select v-model="formData.invStorageCode" placeholder="盘点仓库信息"
                                   @change="locInChange"
                                   :disabled="codeArray.length>0"
                                   clearable>
                            <el-option
                                v-for="item in storageList"
                                :key="item.name"
                                :label="item.name"
                                :value="item.code">
                                <span style="float: left">{{ item.name }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="3">
                    <div class="ao-text">
                        <span>盘点分库：</span>
                    </div>
                </el-col>

                <el-col :span="7">
                    <el-form-item prop="invWarehouseCode">
                        <el-select v-model="formData.invWarehouseCode" placeholder="盘点分库信息"
                                   :disabled="codeArray.length>0"
                                   @change="subStorageChange"
                                   clearable>
                            <el-option
                                v-for="item in subInvList"
                                :key="item.name"
                                :label="item.name"
                                :value="item.code">
                                <span style="float: left">{{ item.name }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="3">
                    <div class="ao-text">
                        <span>盘点货位：</span>
                    </div>
                </el-col>
                <el-col :span="7">
                    <el-form-item class="query-form-item" prop="invSpaceCode">
                        <el-select v-model="formData.invSpaceCode" placeholder="盘点货位信息"
                                   :disabled="codeArray.length>0 || disableSpace"
                                   @change="invSpaceChange"
                                   clearable>
                            <el-option
                                v-for="item in spaceList"
                                :key="item.name"
                                :label="item.name"
                                :value="item.code">
                                <span style="float: left">{{ item.name }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20" style="margin-top: 12px">
                <el-col :span="2">
                    <div class="ao-text">
                        <el-link
                            target="_blank">{{ scanText }}
                        </el-link>
                    </div>
                </el-col>
                <el-col :span="16">
                    <el-form-item prop="code">
                        <el-input
                            id="inputer"
                            @focus="getInputFocus($event)"
                            @keypress.enter.native="enterKey($event)"
                            ref='inputRef'
                            style="ime-mode:disabled"
                            type="tel"
                            v-model="formData.code"
                        ></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="2">
                    <el-button-group style="display: flex">
                        <el-button
                            type="primary"
                            size="small"
                            @click.native.stop="addCode()"
                            style="height: 31px; margin-left: 20px"
                        >添加
                        </el-button
                        >
                    </el-button-group>

                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="11" style="margin-left: 40px">

                </el-col>
                <el-col :span="3">
                    <div class="text item" style="margin-left: 30px"> 盘点产品数量：{{ codeArray.length }}
                    </div>
                </el-col>
                <el-col :span="3">
                    <div class="text item" style="margin-left: 30px"> 条码数量：{{ codesNum }}
                    </div>
                </el-col>
            </el-row>

            <el-table v-loading="loading" :data="codeArray" style="width: 100%; margin-top: 10px;"
                      max-height="300" height="300" ref="multipleTable">
                <el-table-column label="序号" type="index" width="50"></el-table-column>
                <el-table-column width="150"
                                 label="产品通用名"
                                 prop="productName"
                                 show-overflow-tooltip
                ></el-table-column>
                <el-table-column width="150"
                                 label="规格型号"
                                 prop="ggxh"
                                 show-overflow-tooltip
                ></el-table-column>
                <el-table-column width="150" label="批次号" prop="batchNo">
                </el-table-column>
                <el-table-column width="150" label="库存数量" prop="invNum"
                                 show-overflow-tooltip></el-table-column>
                <el-table-column width="150" label="盘点数量" prop="countNum"
                                 show-overflow-tooltip></el-table-column>
                <el-table-column width="180" label="生产日期(yyMMdd)" prop="produceDate">
                </el-table-column>
                <el-table-column width="180" label="失效日期(yyMMdd)" prop="expireDate" show-overflow-tooltip>
                </el-table-column>
                <el-table-column width="250" label="注册/备案凭证号" prop="zczbhhzbapzbh" show-overflow-tooltip>
                </el-table-column>
                <el-table-column width="150" label="生产厂家" prop="ylqxzcrbarmc"
                                 show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" fixed="right" width="150">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            size="small"
                            @click.native.stop="showCodes(scope.row)"
                        >码详情
                        </el-button>
                        <el-button
                            type="text"
                            size="small"
                            @click.stop="true"
                            @click.native="deleteOrderDetail(scope.$index, scope.row)"
                        >删除
                        </el-button
                        >
                    </template>
                </el-table-column>
            </el-table>

        </el-form>

        <el-dialog
            title="库存产品录入"
            :visible.sync="selectInvProductVisible"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="85%"
            v-if="selectInvProductVisible"
            :append-to-body='true'
        >
            <el-card>
                <el-form :inline="true" :model="filterQuery" class="query-form" size="mini">
                    <el-row>
                        <el-form-item class="query-form-item">
                            <el-input v-model="filterQuery.nameCode" placeholder="产品标识DI"></el-input>
                        </el-form-item>
                        <el-form-item class="query-form-item">
                            <el-input v-model="filterQuery.cpmctymc" placeholder="产品名称"></el-input>
                        </el-form-item>
                        <el-form-item class="query-form-item">
                            <el-input v-model="filterQuery.batchNo" placeholder="批次号"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button-group>
                                <el-button type="primary" icon="el-icon-refresh" @click="onReset"></el-button>
                                <el-button type="primary" icon="search" @click="queryInvProducts"
                                >查询
                                </el-button
                                >
                                <el-button type="primary" icon="search" @click="combine">确定</el-button>
                            </el-button-group>
                        </el-form-item>
                    </el-row>
                </el-form>

                <el-table v-loading="loading" :data="productList" style="width: 100%"
                          highlight-current-row="false"
                          ref="multipleTable">
                    <el-table-column
                        type="selection"
                        width="55">
                    </el-table-column>
                    <el-table-column label="序号" type="index"></el-table-column>
                    <el-table-column label="产品标识" prop="nameCode"></el-table-column>
                    <el-table-column label="产品名称" prop="cpmctymc"></el-table-column>
                    <el-table-column label="规格型号" prop="ggxh"></el-table-column>
                    <el-table-column label="批次号" prop="batchNo"></el-table-column>
                    <el-table-column label="生产日期" prop="productionDate"></el-table-column>
                    <el-table-column label="失效日期" prop="expireDate"></el-table-column>
                    <el-table-column label="入库数量" prop="inCount"></el-table-column>
                    <el-table-column label="出库数量" prop="outCount"></el-table-column>
                    <el-table-column label="结余数量" prop="reCount">
                        <template slot-scope="scope">
                            {{ (scope.row.inCount - scope.row.outCount) }}
                        </template>
                    </el-table-column>
                </el-table>

                <el-pagination
                    :page-size="filterQuery.limit"
                    @current-change="handleCurrentChange"
                    layout="prev, pager, next"
                    :total="total"
                ></el-pagination>
            </el-card>
        </el-dialog>

        <el-dialog
            title="码详情"
            :visible.sync="codesVisible"
            width="70%"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            v-if="codesVisible"
            append-to-body
        >
            <countOrderCodes
                :codeQuery="codeQuery"
                :getCountOrderDetail="getCountOrderDetail"
            ></countOrderCodes>
        </el-dialog>
    </div>
</template>

<script>
import {filterSubByInv} from "@/api/basic/invSubWarehouse";
import {isBlank} from "@/utils/strUtil";
import {filterAllByUser} from "@/api/basic/invWarehouse";
import {getSpaceCodeList} from "@/api/inventory/invSpace";
import {filterProducts, getCountInvProductProduct} from "@/api/inventory/InvProducts";
import {
    saveCountOrder,
    getCountOrderDetailList,
    deleteCountOrderDetail,
    addCountOrderDetail
} from "@/api/inventory/invCountOrder";
import {addCode, getCodesNum} from "@/api/inventory/invCountCodes";
import countOrderCodes from "@/views/inventory/countOrderCodes";


export default {
    name: "closeDialog",
    props: {
        closeDialog: {
            type: Function,
            required: true
        },
        countOrder: {
            type: Object,
            required: true
        },
        countType: {
            type: Number,
            required: true
        },
        getCountOrderList: {
            type: Function,
            required: true
        }
    },
    data() {
        return {
            formData: {
                code: null,
                orderId: null,
                billDate: null,
                invStorageCode: null,
                invWarehouseCode: null,
                invSpaceCode: null,
                countType: this.countType
            },
            codeArray: [],
            total: 0,
            loading: false,
            index: null,
            selectInvProductVisible: false,
            storageList: [],
            subInvList: [],
            spaceList: [],
            filterQuery: {
                invStorageCode: null,
                invWarehouseCode: null,
                invSpaceCode: null,
                nameCode: null,
                cpmctymc: null,
                batchNo: null,
                page: 1,
                limit: 10
            },
            productList: [],
            scanText: "扫码录入：",
            codesList: [],
            detailQuery: {
                orderIdFk: null
            },
            detailTotal: 0,
            countProductList: [],
            codesNum: 0,
            codeQuery: {
                productId: null,
                orderIdFk: null,
                edit: true
            },
            codesVisible: false,
            disableSpace: false
        };
    },
    methods: {
        saveOrder(type) {
            let orderData = {
                orderId: this.formData.orderId,
                createTime: this.formData.billDate,
                invStorageCode: this.formData.invStorageCode,
                invWarehouseCode: this.formData.invWarehouseCode,
                invSpaceCode: this.formData.invSpaceCode,
                countType: this.countType
            };

            saveCountOrder(orderData).then((res) => {
                if (res.code === 20000) {
                    this.formData.orderId = res.data.orderId;
                    this.formData.billDate = res.data.createTime;
                    this.$message.success("保存成功");
                    if (type != null) {
                        //保存当前单据详情
                        this.countProductList.forEach(product => {
                            let detailData = {
                                orderIdFk: this.formData.orderId,
                                productId: product.relIdFk,
                                nameCode: product.nameCode,
                                batchNo: product.batchNo,
                                produceDate: product.productionDate,
                                expireDate: product.expireDate
                            };
                            addCountOrderDetail(detailData).then((result) => {
                                if (result.code === 20000) {
                                    this.getCountOrderDetail();
                                    this.getCountOrderList();
                                }
                            });
                        })
                    } else {
                        this.closeDialog();
                    }
                } else {
                    this.$message.error(res.message);
                }
            });
        },
        // 刷新表单
        handleCurrentChange(val) {
            this.filterQuery.page = val;
            this.getInvProducts();
        },
        locInChange() {
            this.formData.invWarehouseCode = null;
            this.formData.invSpaceCode = null;
            //查询分库
            this.getSubInvList();
        },
        getSubInvList() {
            let params = {pcode: this.formData.invStorageCode}
            filterSubByInv(params).then((res) => {
                this.subInvList = res.data || [];
            });
        },
        subStorageChange() {
            this.formData.invSpaceCode = null;
            this.spaceList = [];
            //查询货位
            this.getInvSpaceList();
        },
        getInvSpaceList() {
            let params = {
                invStorageCode: this.formData.invStorageCode,
                invWarehouseCode: this.formData.invWarehouseCode,
                status: true
            };
            getSpaceCodeList(params).then((res) => {
                this.spaceList = res.data || [];
            });
        },
        invSpaceChange() {
            this.$forceUpdate();
        },
        queryInvProducts() {
            this.filterQuery.page = 1;
            this.getInvProducts();
        },
        getInvProducts() {
            this.filterQuery.invStorageCode = this.formData.invStorageCode;
            this.filterQuery.invWarehouseCode = this.formData.invWarehouseCode;
            this.filterQuery.invSpaceCode = this.formData.invSpaceCode;
            getCountInvProductProduct(this.filterQuery).then((res) => {
                if (res.code === 20000) {
                    this.productList = res.data.list || [];
                    this.total = res.data.total || 0;
                } else {
                    this.productList = [];
                    this.total = 0;
                }
            })
        },
        getStorage() {
            filterAllByUser().then((res) => {
                if (res.code === 20000) {
                    this.storageList = res.data || [];
                }
            });

            if (this.countOrder.orderId != null) {
                this.getSubInvList();
                this.getInvSpaceList();
            }
        },
        onReset() {
            this.filterQuery = {
                invStorageCode: null,
                invWarehouseCode: null,
                nameCode: null,
                cpmctymc: null,
                batchNo: null,
                page: 1,
                limit: 10
            };
            this.countProductList = [];
            this.getInvProducts();
        },
        combine() {
            let selection = this.$refs.multipleTable.selection;
            if (selection.length === 0) {
                this.$message.warning("请选择产品");
                return;
            }
            selection.forEach(product => {
                this.countProductList.push(product);
            })
            if (this.codeArray.length === 0) {
                //添加第一个产品，先保存单据，再添加单据详情
                this.saveOrder(1);
            }
            this.selectInvProductVisible = false;
        },
        deleteOrderDetail(index, row) {
            this.$confirm('此操作将删除单据详情, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //此单据详情已经添加到数据库中，需要在数据库中
                let params = {id: row.id}
                deleteCountOrderDetail(params).then((res) => {
                    if (res.code === 20000) {
                        this.$message.success("删除成功");
                        let detailParam = {
                            orderIdFk: this.formData.orderId
                        }
                        getCountOrderDetailList(detailParam).then((result) => {
                            this.codeArray = result.data.list || [];
                        });
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
            }).catch(() => {
            });
        },
        showCodes(row) {
            this.codesVisible = true;
            this.codeQuery = {
                orderIdFk: row.orderIdFk,
                productId: row.productId,
                edit: true
            }
        },
        getInputFocus(event) {
            event.currentTarget.select();
        },
        enterKey(event) {
            if (this.codeArray.length === 0) {
                this.$message.error("请先录入盘点产品！");
                return;
            }
            this.addCode();
            this.$refs.inputRef.focus();
            this.$refs.inputRef.select();
        },
        getCountOrderDetail() {
            this.detailQuery.orderIdFk = this.formData.orderId;
            getCountOrderDetailList(this.detailQuery).then((res) => {
                if (res.code === 20000) {
                    this.codeArray = res.data.list || [];
                    this.detailTotal = res.data.total || 0;
                }
            });
            this.getCountOrderCodesNum();
        },
        addCode() {
            if (this.countType != 1) {
                if (isBlank(this.formData.invStorageCode) || isBlank(this.formData.invWarehouseCode)) {
                    this.$message.error("请先选择盘点仓库和分库信息")
                    return;
                }
            } else if (this.countType === 1) {
                if (isBlank(this.formData.invStorageCode) || isBlank(this.formData.invWarehouseCode) || isBlank(this.formData.invSpaceCode)) {
                    this.$message.error("请先选择盘点仓库和分库信息");
                    return;
                }
            }
            this.formData.code.trim();
            let params = {
                orderIdFk: this.formData.orderId,
                code: this.formData.code
            };
            addCode(params).then((res) => {
                if (res.code === 20000) {
                    this.getCountOrderCodesNum();
                    this.getCountOrderDetail();
                } else {
                    this.$message.error(res.message);
                }
            })
        },
        getCountOrderCodesNum() {
            if (isBlank(this.formData.orderId)) {
                this.codesNum = 0;
            } else {
                let params = {orderIdFk: this.formData.orderId}
                getCodesNum(params).then((res) => {
                    this.codesNum = res.data;
                });
            }
        },
        startCount() {
            this.countProductList = [];
            if (this.countType === 0) {
                if (isBlank(this.formData.invStorageCode) || isBlank(this.formData.invWarehouseCode)) {
                    this.$message.warning("请先选择盘点仓库");
                    return;
                }
                //拉取整个仓库的数据
                let params = {
                    invStorageCode: this.formData.invStorageCode,
                    invWarehouseCode: this.formData.invWarehouseCode
                };
                getCountInvProductProduct(params).then((res) => {
                    if (res.data.length !== 0) {
                        let invProductList = res.data.list;
                        for (let product of invProductList) {
                            this.countProductList.push(product);
                        }
                        this.saveOrder(1);
                    }
                });
            } else if (this.countType === 1) {
                if (isBlank(this.formData.invStorageCode) || isBlank(this.formData.invWarehouseCode) || isBlank(this.formData.invSpaceCode)) {
                    this.$message.warning("请先选择盘点仓库和货位");
                    return;
                }
                let params = {
                    invStorageCode: this.formData.invStorageCode,
                    invWarehouseCode: this.formData.invWarehouseCode,
                    invSpaceCode: this.formData.invSpaceCode
                };
                getCountInvProductProduct(params).then((res) => {
                    if (res.data.length !== 0) {
                        let invProductList = res.data.list;
                        for (let product of invProductList) {
                            this.countProductList.push(product);
                        }
                        this.saveOrder(1);
                    }
                });
            } else if (this.countType === 2) {
                if (isBlank(this.formData.invStorageCode) || isBlank(this.formData.invWarehouseCode)) {
                    this.$message.warning("请先选盘点仓库");
                    return;
                }
                this.selectInvProductVisible = true;
                this.queryInvProducts();
            }
        },
    },
    components: {
        countOrderCodes
    },
    created() {
        this.getStorage();
        this.formData = this.countOrder;
        this.formData.billDate = this.countOrder.createTime;
        if (!isBlank(this.formData.orderId)) {
            //拉取单据详情信息
            let params = {orderIdFk: this.formData.orderId};
            getCountOrderDetailList(params).then((res) => {
                if (res.code === 20000) {
                    this.codeArray = res.data.list || [];
                    this.total = res.data.total || 0;
                }
            });
            this.getCountOrderCodesNum();
        }
        if (this.countType == 0) {
            this.disableSpace = true;
        }
    },
};
</script>
<style>

.ao-text {
    width: 100%;
    font-size: 13px;
    font-family: "Microsoft YaHei";
    float: right;
    text-align: right;
    margin-top: 10px;
}

</style>
