<template>
    <div>
        <el-form :model="formData" ref="dataForm">
            <el-button-group style="display: flex;margin: -50px 0 10px 80%; height: 35px">
                <el-button
                    type="primary"
                    @click.native="saveDeviceCollectOrder()"
                >保存
                </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.createTime" auto-complete="off" :disabled="true"></el-input>
                    </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 prop="deptCode">
                        <el-select v-model="formData.deptCode" placeholder="领用部门"
                                   :disabled="detailList.length >0 "
                                   @change="deptChange"
                                   clearable>
                            <el-option
                                v-for="item in deptList"
                                :key="item.name"
                                :label="item.name"
                                :value="item.code">
                                <span style="float: left">{{ item.name }}</span>
                                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.code }}</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="collectUser">
                        <el-select v-model="formData.collectUser" placeholder="领用人"
                                   :disabled="detailList.length >0 "
                                   clearable>
                            <el-option
                                v-for="item in userList"
                                :key="item.employeeName"
                                :label="item.employeeName"
                                :value="item.employeeName">
                                <span style="float: left">{{ item.employeeName }}</span>
                                <span style="float: right; color: #8492a6; font-size: 13px">{{
                                        item.employeeName
                                    }}</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
                            style="height: 31px; margin-left: 20px"
                            type="primary"
                            :disabled="this.detailList.length > 0"
                            @click.native="selectInvProduct()"
                        >手动添加
                        </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"> 领用产品数量：{{ detailList.length }}
                    </div>
                </el-col>
            </el-row>

            <el-table v-loading="loading" :data="detailList" 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 label="条码" width="180" prop="originCode" show-overflow-tooltip></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 label="序列号" width="200" prop="serialNo">
                    <template slot-scope="scope">
                        <el-input :disabled="scope.$index !== currentIndex" v-model="scope.row.serialNo"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="领用仓库" prop="invWarehouseName"></el-table-column>
                <el-table-column label="领用货位" prop="invSpaceName"></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"
                            v-if="scope.row.editSerialNo"
                            @click.stop="true"
                            @click.native="editOrderDetail(scope.$index, scope.row)"
                        >编辑
                        </el-button
                        >
                        <el-button
                            type="text"
                            size="small"
                            @click.stop="true"
                            @click.native="updateOrderDetail(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-form :inline="true" :model="filterQuery" size="mini">
                <el-row>
                    <el-form-item class="query-form-item">
                        <el-select v-model="filterQuery.invWarehouseCode" placeholder="领用仓库信息"
                                   :disabled="detailList.length >0 "
                                   @change="warehouseChange"
                                   clearable>
                            <el-option
                                v-for="item in warehouseList"
                                :key="item.name"
                                :label="item.name"
                                :value="item.code">
                                <span style="float: left">{{ item.name }}</span>
                                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.parentName }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item class="query-form-item" prop="invSpaceCode">
                        <el-select v-model="filterQuery.invSpaceCode" placeholder="领用货位信息"
                                   :disabled="detailList.length >0 "
                                   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-form-item class="query-form-item">
                        <el-input v-model="filterQuery.nameCode" placeholder="产品标识DI" clearable></el-input>
                    </el-form-item>
                    <el-form-item class="query-form-item">
                        <el-input v-model="filterQuery.cpmctymc" placeholder="产品名称" clearable></el-input>
                    </el-form-item>
                    <el-form-item class="query-form-item">
                        <el-input v-model="filterQuery.batchNo" placeholder="批次号" clearable></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"
                      :row-key="getRowKeys"
                      @selection-change="handleSelectionChange"
                      ref="multipleTable">
                <el-table-column
                    type="selection"
                    :reserve-selection="true"
                    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" width="120"></el-table-column>
                <el-table-column label="失效日期" prop="expireDate" width="120"></el-table-column>
            </el-table>

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

<script>
import { getInvWarehouseList} from "@/api/basic/invSubWarehouse";
import {getSpaceCodeList} from "@/api/inventory/invSpace";
import {
    addCollectOrder,
    updateCollectOrder,
    updateCollectOrderDetail,
    addCollectOrderDetail,
    getCollectOrderDetailList,
    deleteCollectOrderDetail,
    checkCode
} from "@/api/inventory/deviceCollectOrder";
import {getMAInvProducts} from "@/api/inventory/InvProducts";
import {isBlank} from "@/utils/strUtil";
import {filterDepts} from "@/api/auth/authDept";
import {authAdminList} from "@/api/auth/authAdmin";
import {userInfo} from "@/api/auth/login";

export default {
    props: {
        deviceCollectOrder: {
            type: Object,
            required: true,
        },
        closeDialog: {
            type: Function,
            required: true,
        },
    },

    data() {
        return {
            filterQuery: {
                nameCode: null,
                cpmctymc: null,
                batchNo: null,
                invWarehouseCode: null,
                invSpaceCode: null,
                cplb: "设备",
                page: 1,
                limit: 10
            },
            productList: [],
            productTotal: 0,
            warehouseList: [],
            spaceList: [],
            formData: {
                orderId: null,
                createTime: null,
                deptCode: null,
                status: 0,
                code: null,
                collectUser: null
            },
            detailList: [],
            loading: false,
            scanText: "扫码录入：",
            currentIndex: -1,
            selectInvProductVisible: false,
            multiProduct: [],
            deptList: [],
            userList: []
        }
    },
    methods: {
        getAllWarehouse() {
            let userId = null;
            if (!isBlank(this.formData.collectUser)) {
                this.userList.forEach(item => {
                    if (item.name === this.formData.collectUser) {
                        userId = item.id;
                    }
                });
            } else {
                userId = this.$store.getters.adminId;
            }
            let params = {userId: userId};
            getInvWarehouseList(params).then((res) => {
                if (res.code === 20000) {
                    this.warehouseList = res.data || [];
                }
            });
        },
        warehouseChange() {
            this.filterQuery.invSpaceCode = null;
            this.spaceList = [];
            let params = {invWarehouseCode: this.filterQuery.invWarehouseCode};
            getSpaceCodeList(params).then((res) => {
                this.spaceList = res.data || [];
            });
        },
        selectInvProduct() {
            if (isBlank(this.formData.deptCode)) {
                this.$message.error("请选择领用部门！")
                return;
            } else if (isBlank(this.formData.collectUser)) {
                this.$message.error("请选择领用人！")
                return;
            }
            userInfo().then((res) => {
                if (res.code === 20000) {
                    if (!isBlank(res.data.locInvCode)) {
                        this.filterQuery.invWarehouseCode = res.data.locSubInvCode;
                        this.getAllWarehouse();
                        this.warehouseChange();
                    }
                    this.getList();
                }
            }).catch((error) => {
            });
            //保存或更新养护记录仓库信息
            this.saveOrder();
            this.filterQuery = {
                nameCode: null,
                cpmctymc: null,
                batchNo: null,
                invWarehouseCode: null,
                cplb: "设备",
                invSpaceCode: null,
                page: 1,
                limit: 10
            };
            this.productList = [];
            this.productTotal = 0;
            this.selectInvProductVisible = true;
        },
        saveDeviceCollectOrder() {
            this.saveOrder();
            this.closeDialog();
        },
        saveOrder(code) {
            if (isBlank(this.formData.deptCode)) {
                this.$message.warning("请选择领用部门！");
                return;
            }
            if (!isBlank(this.formData.orderId)) {
                //更新单据
                updateCollectOrder(this.formData).then((res) => {
                }).catch((error) => {
                    this.$message.error(error.message);
                })
            } else {
                addCollectOrder(this.formData).then((res) => {
                    if (res.code === 20000) {
                        this.formData.id = res.data.id;
                        this.formData.orderId = res.data.orderId;
                        this.formData.createTime = res.data.createTime;
                    } else {
                        this.$message.error(res.message);
                    }
                });
            }
        },
        getInputFocus(event) {
            event.currentTarget.select();
        },
        enterKey(event) {
            this.addCode();
            this.$refs.inputRef.focus();
            this.$refs.inputRef.select();
        },
        addCode() {
            if (isBlank(this.formData.deptCode)) {
                this.$message.warning("请先选择养护仓库！");
                return;
            }
            if (isBlank(this.formData.orderId)) {
                this.saveOrder(this.formData.code);
                return;
            }

            //校验条码是否符合规则
            let checkParams = {
                code: this.formData.code
            }
            checkCode(checkParams).then((res) => {
                if (res.code === 20000) {
                    this.addDeviceCollectOrderDetail();
                } else {
                    if (res.code === 3) {
                        this.$message.error(res.message);
                    } else if (res.code === 7) {
                        this.$confirm(res.message + "，是否继续添加？", "提示", {
                            confirmButtonText: "确定",
                            cancelButtonText: "取消",
                            type: "warning"
                        }).then(() => {
                            this.addDeviceCollectOrderDetail();
                        }).catch(() => {
                        });
                    }
                }
            }).catch((error) => {
            });
        },
        addDeviceCollectOrderDetail() {
            //扫码添加库存养护记录详情
            let params = {
                orderIdFk: this.formData.orderId,
                code: this.formData.code
            }
            addCollectOrderDetail(params).then((res) => {
                if (res.code === 20000) {
                    this.$message.success("添加成功！");
                    this.getList();
                } else {
                    this.$message.error(res.message);
                }
            });
        },
        deleteOrderDetail(index, row) {
            this.$confirm('是否确认从此设备领用记录中删除此产品？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let params = {id: row.id};
                deleteCollectOrderDetail(params).then((res) => {
                    if (res.code === 20000) {
                        this.$message.success("删除成功");
                        this.getList();
                    }
                })
            }).catch(() => {
            });
        },
        getList() {
            let params = {orderIdFk: this.formData.orderId};
            getCollectOrderDetailList(params).then((res) => {
                if (res.code === 20000) {
                    this.detailList = res.data.list || [];
                }
            })
        },
        updateOrderDetail(row) {
            updateCollectOrderDetail(row).then((res) => {
                if (res.code === 20000) {
                    this.currentIndex = -1;
                    this.$message.success("更新成功！")
                    this.getList();
                }
            })
        },
        editOrderDetail(index, row) {
            this.currentIndex = index;
        },
        onReset() {
            this.filterQuery = {
                nameCode: null,
                cpmctymc: null,
                batchNo: null,
                invWarehouseCode: null,
                invSpaceCode: null,
                cplb: "设备",
                page: 1,
                limit: 10
            };
            this.multiProduct = [];
            this.queryInvProducts();
        },
        handleCurrentChange(val) {
            this.filterQuery.page = val;
            this.queryInvProducts();
        },
        queryInvProducts() {
            if (isBlank(this.filterQuery.invWarehouseCode)) {
                this.$message.success("请选择领用仓库！");
                return;
            }
            getMAInvProducts(this.filterQuery).then((res) => {
                if (res.code === 20000) {
                    this.productList = res.data.list || [];
                    this.productTotal = res.data.total || 0;
                } else {
                    this.$message.error(res.message);
                    this.productList = [];
                    this.productTotal = 0;
                }
            }).catch((error) => {
                this.$message.error(error.message);
                this.productList = [];
                this.productTotal = 0;
            });
        },
        combine() {
            if (this.multiProduct.length === 0) {
                this.$message.error("请选择领用产品！");
                return;
            }
            let invProductIds = [];
            this.multiProduct.forEach(item => {
                invProductIds.push(item.id);
            });
            let params = {
                orderIdFk: this.formData.orderId,
                invProductIds: invProductIds
            };
            addCollectOrderDetail(params).then((res) => {
                if (res.code === 20000) {
                    this.selectInvProductVisible = false;
                    this.$message.success("添加成功！");
                    this.getList();
                } else {
                    this.$message.error(res.message);
                }
            }).catch((error) => {
                this.$message.error(error.message);
            })
        },
        getRowKeys(row) {
            return row.id;
        },
        handleSelectionChange(selectedRows) {
            this.multiProduct = [];
            selectedRows.forEach(item => {
                this.multiProduct.push(item);
            });
        },
        getDepts() {
            filterDepts().then((res) => {
                this.deptList = res.data.list || [];
            })
        },
        deptChange() {
            //查询此部门下的用户
            this.userList = [];
            this.formData.collectUser = null;
            let params = {
                deptCode: this.formData.deptCode
            };
            authAdminList(params).then((res) => {
                this.userList = res.data.list || [];
            });
        },
    },
    created() {
        this.getDepts();
        if (null !== this.deviceCollectOrder) {
            this.formData.id = this.deviceCollectOrder.id;
            this.formData.orderId = this.deviceCollectOrder.orderId;
            this.formData.deptCode = this.deviceCollectOrder.deptCode;
            this.formData.createTime = this.deviceCollectOrder.createTime;
            this.formData.invWarehouseCode = this.deviceCollectOrder.invWarehouseCode;
            this.formData.collectUser = this.deviceCollectOrder.collectUser;
            this.getList();
        }
    },
};
</script>

