<template>
    <div>

        <el-form :model="formData" :rules="formRules" ref="dataForm">
            <el-row type="flex" justify="end">
                <el-button-group style="display: flex;margin-bottom: 15px; margin-right: 50px">
                    <el-button
                        type="primary"
                        @click.native="saveOrder('1')"
                        :loading="loading"
                    >草稿保存
                    </el-button
                    >
                    <el-button
                        type="primary"
                        @click.native="saveOrder('2')"
                        :loading="loading"
                    >未配货提交
                    </el-button
                    >

                    <el-button
                        type="primary"
                        @click.native="saveOrder('3')"
                        :loading="loading"
                    >已配货提交
                    </el-button
                    >
                </el-button-group>
            </el-row>

            <el-card style="margin-top: -5px;">
                <el-row :gutter="20" style="margin-top: 10px;">
                    <el-col :span="3">
                        <div class="ao-text">
                            <span>单据号：</span>
                        </div>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item prop="billNo">
                            <el-input v-model="formData.billNo" 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"></el-input>-->
                            <el-date-picker
                                v-model="formData.billdate"
                                type="datetime"
                                placeholder="选择日期"
                                style="width: 100%"
                                :clearable="false"
                                value-format="yyyy-MM-dd HH:mm:ss"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20" style="margin-top: -10px">
                    <el-col :span="3">
                        <div class="ao-text">
                            <span>业务类型：</span>
                        </div>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item prop="billType">
                            <el-select v-model="formData.billType" placeholder="请选择业务类型" :disabled="codeArray.length>0"
                                       @change="actionChange">
                                <el-option
                                    v-for="item in busTypes"
                                    :key="item.localAction"
                                    :label="item.localName"
                                    :value="item.localAction">
                                    <span style="float: left">{{ item.localName }}</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 class="query-form-item" prop="corpName"
                                      v-if="curAction.corpType ==0 || curAction.corpType == 3 || (curAction.corpType == 2 && !curAction.genUnit)">
                            <el-select
                                v-model="formData.corpName"
                                filterable
                                remote :disabled="codeArray.length>0"
                                clearable="true"
                                reserve-keyword
                                placeholder="请输入往来单位"
                                :remote-method="findMethod"
                                :loading="loading"
                                @focus="findMethod('')"
                                @change="selectOne"
                            >
                                <el-option
                                    v-for="item in fromOptions"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item"
                                >
                                    <span style="float: left">{{ item.name }}</span>
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item class="query-form-item" prop="fromCorp"
                                      v-if="curAction.corpType ==1">
                            <el-select
                                v-model="formData.corpName"
                                filterable
                                remote
                                clearable="true" :disabled="codeArray.length>0"
                                reserve-keyword
                                placeholder="请输入仓库信息"
                                :remote-method="findStorageMethod"
                                :loading="loading"
                                @change="storageChange"
                            >
                                <el-option
                                    v-for="item in fromStorageOptions"
                                    :key="item.value"
                                    :label="item.code"
                                    :value="item">
                                    <span style="float: left">{{ item.name }}</span>
                                    <span style="float: right; color: #8492a6; font-size: 13px">{{
                                            item.code
                                        }}</span>
                                </el-option>
                            </el-select>

                            <el-select v-model="formData.fromSubInvCode" placeholder="请选择分库" clearable="true"
                                       :disabled="codeArray.length>0"
                            >
                                <el-option
                                    v-for="item in fromSubStorageOptions"
                                    :key="item.code"
                                    :label="item.name" :disabled="codeArray.length>0"
                                    :value="item.code">
                                    <span style="float: left">{{ item.name }}</span>
                                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.code }}</span>
                                    <!--<span style="float: right; color: #8492a6; font-size: 13px">{{ item.action }}</span>-->
                                </el-option>
                            </el-select>

                        </el-form-item>
                        <el-form-item class="query-form-item" prop="fromCorp"
                                      v-if="curAction.corpType ==2 && curAction.genUnit">
                            <el-input v-model="formData.corpName" auto-complete="off" :disabled="codeArray.length>0"
                                      clearable
                                      placeholder="请输入病人住院号"
                            ></el-input>
                        </el-form-item>
                    </el-col>

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

                    <el-col :span="7">
                        <el-form-item prop="locStorageCode">
                            <el-select v-model="formData.locStorageCode" 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" style="margin-top: -10px;">
                    <el-col :span="3">
                        <div class="ao-text">
                            <span></span>
                        </div>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item prop="type" style="margin-right: 20px;"
                                      v-if="!(curAction.mainAction=='WareHouseIn' && curAction.corpType == 0)">
                            <el-checkbox v-model="formData.noInvOut" :disabled="codeArray.length>0">允许无库存出库
                            </el-checkbox>
                        </el-form-item>
                    </el-col>
                </el-row>

            </el-card>

            <el-card>
                <el-button-group style="display: flex">
                    <el-button
                        type="primary"
                        size="small"
                        @click.native.stop="selectProductFunction()"
                        style="margin: 0px 60px 10px auto; height: 35px"
                        :loading="loading"
                    >产品录入
                    </el-button
                    >
                </el-button-group>

                <el-table v-loading="loading" :data="codeArray" style="width: 100%;"
                          :row-class-name="tableRowClassName"
                          max-height="300" height="300" ref="multipleTable">
                    <!--                    <el-table-column-->
                    <!--                        type="selection"-->
                    <!--                        width="55">-->
                    <!--                    </el-table-column>-->
                    <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="spec"
                                     show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column width="150" label="批次号">
                        <template slot-scope="scope">
                            <el-input size="small" v-model="scope.row.batchNo"
                                      :disabled="scope.row.index !== selectedIndex"
                                      @input="scope.row.batchNo =scope.row.batchNo.replace(/[\W]/g, '')"
                                      ref='inputBatchNoRef'
                                      placeholder="请输入批次号" style="width: 80%"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column width="180" label="生产日期(yyMMdd)">
                        <template slot-scope="scope">

                            <el-input v-model="scope.row.productDate" auto-complete="off"
                                      oninput="if(value.length>6)value=value.slice(0,6)"
                                      :disabled="scope.row.index !== selectedIndex"
                                      type="number"
                            ></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column width="180" label="失效日期(yyMMdd)">
                        <template slot-scope="scope">

                            <el-input v-model="scope.row.expireDate" auto-complete="off"
                                      oninput="if(value.length>6)value=value.slice(0,6)"
                                      :disabled="scope.row.index !== selectedIndex"
                                      type="number"
                            ></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column width="150" label="单据数量">
                        <template slot-scope="scope">
                            <el-input size="small" v-model="scope.row.count"
                                      placeholder="请输入数量" style="width: 80%"
                                      type='number'
                                      @change="tableCountChange(scope.row)"
                                      :disabled="scope.row.index !== selectedIndex"
                                      oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column width="150" label="价格">
                        <template slot-scope="scope">
                            <el-input size="small" v-model="scope.row.price"
                                      type='number'
                                      :disabled="scope.row.index !== selectedIndex"
                                      placeholder="请输入价格" style="width: 80%"
                            ></el-input>
                        </template>
                    </el-table-column>

                    <el-table-column width="150"
                                     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">

                            <!--                            v-if="orderEditor && scope.row.index !== selectedIndex"-->
                            <el-button
                                type="text"
                                size="small"
                                :disabled="scope.row.index === selectedIndex"
                                @click.stop="true"
                                @click.native="rowChange(scope.row)"
                            >编辑
                            </el-button
                            >
                            <el-button
                                type="text"
                                size="small"
                                @click.stop="true"
                                @click.native="copyDetail(scope.row)"
                            >复制
                            </el-button
                            >
                            <el-button
                                type="text"
                                size="small"
                                @click.stop="true"
                                @click.native="deleteCodeArray(scope.$index, scope.row)"
                            >删除
                            </el-button
                            >
                        </template>
                    </el-table-column>
                </el-table>

                <!--                <div class="block" v-if="orderEditor">-->
                <!--                    <el-pagination-->
                <!--                        @current-change="handleCurrentChange"-->
                <!--                        layout="prev, pager, next"-->
                <!--                        :page-size="query.limit"-->
                <!--                        :total="total">-->
                <!--                    </el-pagination>-->
                <!--                </div>-->
            </el-card>
        </el-form>

        <el-dialog
            title="产品录入"
            :visible.sync="selectProductVisible"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="85%"
            v-if="selectProductVisible"
            :append-to-body='true'
        >
            <stockOrderNewSelectProduct
                :closeDialog="closeDialogC2"
                :data="thisData"
            ></stockOrderNewSelectProduct>
        </el-dialog>

        <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'
        >
            <dialogInvProduct
                :closeDialog="closeDialogC2"
                :data="thisData"
                :invQueryData="invQueryData"
            ></dialogInvProduct>
        </el-dialog>
    </div>
</template>

<script>
import {
    stockOrderDetail,
    submitStockOrder,
    stockOrderGenerateBillNo,
    getStockOrderDetailInstrument,
    insertStockOrderWeb,
    deleteStockOrderDetailById,
    addStockOrderDetailFromCode,
    uploadStockOrderDetail,
    stockOrderDetailQueryProduct,
    getStockOrderDetailInstrumentById, stockOrderDetail2
} from "../../api/warehouse/stockOrder";
import draggable from "vuedraggable";
import {saveAs} from "file-saver";
import {parseTime} from "../../filtres/index";
import store from "../../store";
import stockOrderNewSelectProduct from "./stockOrderNewSelectProduct";
import {getBasicUnitMaintains, getBasicUnitMaintains2} from "../../api/basic/basicUnitMaintain";
import {getBussinessType} from "../../api/basic/bussinessType";
import {getLocalBusType, getLocalJoinBusType, getLocalJoinByUser} from "../../api/basic/busLocalType";
import {filterAll, filterAllByLoc, filterAllByUser} from "@/api/basic/invWarehouse";
import dialogInvProduct from "../inventory/DialogInvProduct"
import {filterSubByInv} from "@/api/basic/invSubWarehouse";
import {isBlank} from "@/utils/strUtil";

export default {
    name: "idQuery",
    props: {
        closeDialog: {
            type: Function,
            required: true,
        },
        idQuery: {
            type: Object,
            required: true,
        },
        closeConfirmFunction: {
            type: Function,
            required: true,
        },
    },
    data() {
        return {
            code: "",
            query: {
                orderIdFk: "",
                page: 1,
                limit: 10,
            },
            formData: {
                noInvOut: false,
                locStorageCode: null,
                invWarehouseCode: null,
                fromSubInvCode: null,
                billNo: null,
                billdate: "",
                customerId: store.getters.customerId,
                billType: "",
                type: null,
                corpName: "",
                corpId: "",
            },
            formRules: {
                corpName: [
                    {required: true, message: "请输入供应商", trigger: "blur"}
                ],
                billdate: [
                    {required: true, message: "请输入单据日期", trigger: "blur"}
                ],
                billType: [
                    {required: true, message: "请选择业务类型", trigger: "blur"}
                ],
                locStorageCode: [
                    {required: true, message: "请选择当前仓库", trigger: "blur"}
                ],

                invWarehouseCode: [
                    {required: true, message: "请选择当前分库", trigger: "blur"}
                ],
            },
            codeArray: [],
            fromOptions: [],
            fromStorageOptions: [],
            fromSubStorageOptions: [],
            total: 0,
            loading: false,
            index: null,
            formLoading: false,
            formVisible: false,
            deleteLoading: false,
            orderNo: null,
            statusMap: {
                101: "未处理",
                102: "已处理",
                201: "未配货",
                202: "已配货",
                301: "已打印",
                401: "异常",
                501: "未提交",
                502: "已提交",
            },
            typeMap: {
                1: "预入库",
                2: "普通采购",
            },
            curAction: {
                corpType: 0,
                genUnit: false,
            },
            orderEditor: true,
            iCount: 0,
            sOptions: [],
            sValue: [],
            sList: [],
            sLoading: false,
            busTypes: [],
            currentRow: {},
            selectedIndex: "",
            selectProductVisible: false,
            selectInvProductVisible: false,
            thisData: {},
            storageList: [],
            invQueryData: {},
            subInvList: [],
        };
    },
    components: {
        draggable,
        stockOrderNewSelectProduct,
        dialogInvProduct,
    },
    methods: {
        saveOrder(status) {

            this.code = "";
            this.$refs.multipleTable.setCurrentRow();
            this.currentRow = {};
            this.selectedIndex = "";
            this.iCount = 0;
            this.$refs["dataForm"].validate(valid => {
                if (valid) {
                    if (this.codeArray.length < 1) {
                        this.$message.warning('未添加产品');
                        return;
                    }

                    for (let i = 0; i < this.codeArray.length; i++) {
                        if (!this.$isBlank(this.codeArray[i].productDate) && this.codeArray[i].productDate.length != 6) {
                            return this.$message.error('生产日期格式错误');
                        }
                        if (!this.$isBlank(this.codeArray[i].expireDate) && this.codeArray[i].expireDate.length != 6) {
                            return this.$message.error('失效日期格式错误');
                        }

                    }

                    if (status === '3') {
                        for (let i = 0; i < this.codeArray.length; i++) {
                            if (this.$isBlank(this.codeArray[i].count) || this.codeArray[i].count == "0") {
                                return this.$message.error('单据数量不能为0');
                            }
                            // if (this.$isBlank(this.codeArray[i].batchNo)) {
                            //     if (!this.codeArray[i].allowNoBatch) {
                            //         return this.$message.error('批次号不能为空');
                            //     }
                            // }
                            if (this.$isBlank(this.codeArray[i].productDate) && this.$isBlank(this.codeArray[i].expireDate)) {
                                return this.$message.error('生产日期与失效日期不能全部为空');
                            }
                            // if (this.$isBlank(this.codeArray[i].expireDate)) {
                            //     return this.$message.error('失效日期不能为空');
                            // }


                        }
                    }
                    if (status === '2') {
                        for (let i = 0; i < this.codeArray.length; i++) {
                            if (this.$isBlank(this.codeArray[i].count) || this.codeArray[i].count == "0") {
                                return this.$message.error('单据数量不能为0');
                            }

                            // if (!this.$isBlank(this.codeArray[i].productDate && this.codeArray[i].productDate.length != 6)) {
                            //     return this.$message.error('生产日期格式错误');
                            // }
                            // if (!this.$isBlank(this.codeArray[i].expireDate && this.codeArray[i].expireDate.length != 6)) {
                            //     return this.$message.error('失效日期不能为空');
                            // }

                        }
                    }


                    if (status === '501') {
                        this.submitFunction(status);
                    } else {

                        if (status == "1") {
                            this.submitFunction(status);
                        } else {
                            let tip = "是否确定提交订单?";
                            if (status == "2") {
                                tip = "是否确定提交单据为未配货？";
                            } else if (status == "3") {
                                tip = "是否确定提交单据为已配货？";
                            }
                            this.$confirm(tip, "提示", {
                                confirmButtonText: "确定",
                                cancelButtonText: "取消",
                                type: "warning",
                            }).then(() => {
                                this.submitFunction(status);
                            }).catch(() => {
                                this.loading = false;
                            });
                        }


                    }
                }
            });
        },
        storageChange(row) {
            if (this.formData.fromSubInvCode != null)
                this.formData.fromSubInvCode = "";
            this.formData.corpId = row.code;
            this.formData.corpName = row.name;
            this.findSubStorageMethod();

        },
        getStorage(event) {
            this.storageList = [];
            filterAllByUser()
                .then((response) => {
                    this.storageList = response.data || [];
                    this.findSubInvs();
                })
                .catch(() => {
                });
        },

        getActionName(action) {
            for (let i = 0; i < this.busTypes.length; i++) {
                if (this.busTypes[i].action === action) {
                    return this.busTypes[i].advanceType;
                }
            }
        },
        findStorageMethod(query) {
            if (this.formData.locStorageCode == null)
                return;
            this.fromStorageOptions = [];
            let cQuery = {
                locInvCode: this.formData.locStorageCode,
            };
            filterAllByLoc(cQuery)
                .then((response) => {
                    let temp = response.data || [];
                    for (let i = 0; i < temp.length; i++) {
                        if (temp[i].code != this.formData.locStorageCode) {
                            this.fromStorageOptions.push(temp[i]);
                        }
                    }

                })
                .catch(() => {
                });
        },

        findSubStorageMethod() {
            let cQuery = {
                pcode: this.formData.corpId,
                filter: 2,
            };
            filterSubByInv(cQuery)
                .then((response) => {
                    this.fromSubStorageOptions = response.data || [];
                })
                .catch(() => {
                });
        },

        findSubInvByInv(invCode) {
            this.subInvList = [];
            let query = {
                pcode: invCode
            };
            filterSubByInv(query)
                .then((response) => {
                    this.subInvList = response.data || [];
                    if (this.subInvList != null && this.subInvList.length == 1) {
                        this.formData.invWarehouseCode = this.subInvList[0].code;
                        this.getBusType();
                    }
                })
                .catch(() => {
                });
        },


        submitFunction(status) {
            let tMessage = status === '501' ? '保存' : '提交';
            this.loading = true;
            let tQuery = this.formData;
            tQuery.status = status;
            // if (!this.orderEditor) {
            tQuery.subErpOrders = this.codeArray;
            if (status == '3') {
                tQuery.subErpOrders.forEach((obj) => {
                    obj.reCount = obj.count;
                });
            }


            insertStockOrderWeb(tQuery)
                .then(response => {
                    this.loading = false;
                    if (response.code === 20000) {
                        this.$message.success(tMessage + "成功");
                        this.formData.billNo = response.data;
                        this.closeDialog(true);
                    } else {
                        this.$message.error(response.message);
                    }
                })
                .catch(() => {
                    this.loading = false;
                })
        },
        submit(formName) {
            if (this.total < 1) {
                this.$message.warning('未添加产品');
                return;
            }
            this.$confirm("是否提交？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                let tQuery = {
                    id: this.idQuery.id
                }
                this.loading = true;
                submitStockOrder(tQuery)
                    .then((response) => {
                        this.loading = false;
                        if (response.code === 20000) {
                            this.$message.success("提交成功");
                            this.closeDialog(true);
                        } else {
                            this.$message.error(response.message);
                        }
                    });
            }).catch(() => {
                this.loading = false;
            });
        },
        selectProductFunction(event) {

            if (event == null) {
                // this.$refs.inputRef.focus();
            } else {
                event.target.select();
            }
            if (this.$isBlank(event)) {

                if (this.$isBlank(this.formData.corpName) || this.$isBlank(this.formData.billType)) {
                    this.$message.error("往来信息和单据类型不能为空！")
                    return;
                }
                if (this.$isBlank(this.formData.locStorageCode) || this.$isBlank(this.formData.invWarehouseCode)) {
                    this.$message.error("当前仓库和当前分库不能为空！");
                    return;
                }
                this.code = "";
                this.$refs.multipleTable.setCurrentRow();
                this.currentRow = {};
                this.selectedIndex = "";
                this.iCount = 0;
                this.thisData.code = "";
                this.thisData.orderEditor = this.orderEditor;
                this.thisData.orderId = "";
                if (this.orderEditor) {
                    this.thisData.orderId = this.formData.id
                }
                this.thisData.stockOrderLists = this.codeArray;
                this.thisData.formData = this.formData;
                let item = this.getActionItem(this.formData.billType);
                if (item.mainAction == 'WareHouseOut' && this.formData.noInvOut != true) {
                    this.invQueryData = {
                        locStorageCode: this.formData.locStorageCode,
                    };
                    this.selectInvProductVisible = true;
                } else if (item.mainAction == "WareHouseIn" && this.curAction.corpType == 1 && this.formData.noInvOut != true) {

                    this.invQueryData = {
                        locStorageCode: this.formData.corpId,
                    };
                    this.selectInvProductVisible = true;
                } else {
                    this.selectProductVisible = true;
                }
                return;
            }
            this.code = this.code.trim();

            if (this.code.length > 13) {
                let tStr = this.code.substring(0, 2);
                tStr = tStr.replace('m', 'M');
                tStr = tStr.replace('a', 'A');
                if (tStr.indexOf("MA") !== -1) {
                    this.code = tStr + this.code.substring(2, this.code.length);
                }
            }

            this.loading = true;
            let tQuery = {
                code: this.code,
                customerId: store.getters.customerId,
            };

            stockOrderDetailQueryProduct(tQuery).then((response) => {
                this.loading = false;
                if (response.code === 20000) {
                    if (response.data.getType === "1") {
                        this.loading = true;

                        let ids = [response.data.getId];
                        let tQuery2 = {
                            ids: ids,
                            udiEntity: response.data
                        };
                        getStockOrderDetailInstrumentById(tQuery2).then((response) => {
                            this.loading = false;
                            if (response.code === 20000) {
                                this.closeDialogC2(response.data);
                            } else {
                                this.$message.error(response.message);
                            }
                        }).catch(() => {
                            this.loading = false;
                        });
                    } else {
                        this.thisData = response.data;
                        this.thisData.code = this.code;
                        this.thisData.orderEditor = this.orderEditor;
                        this.thisData.orderId = "";
                        if (this.orderEditor) {
                            this.thisData.orderId = this.formData.id
                        }
                        this.thisData.stockOrderLists = this.codeArray;
                        this.selectProductVisible = true;
                    }
                } else {
                    this.$message.warning(response.message);
                    // this.focusNext('inputRef');
                    if (this.$isNotBlank(event)) {
                        event.target.select();
                    }
                    // event.target.select();
                    // event.currentTarget.select();
                }
            });


        },
        closeDialogC2(rData) {
            this.selectProductVisible = false;
            this.selectInvProductVisible = false;
            this.thisData = {};

            if (this.$isNotBlank(rData)) {
                this.codeArray = [];
                rData.forEach((obj, index) => {
                    this.codeArray.unshift(obj);
                });
                this.$refs.multipleTable.setCurrentRow(this.codeArray[0]);
                this.currentRow = this.codeArray[0];
                this.selectedIndex = 0;
                this.focusNext('iCount');
                this.closeConfirmFunction(true);
            }
        },
        rowChange(val) {
            this.currentRow = val;
            this.selectedIndex = val.index;
            this.iCount = val.count;

            this.focusNext('iCount');

            // let sc = this.selectedIndex + 'reCount';
            // const _this = this;
            // this.$nextTick(() => {
            //     setTimeout(function() {
            //         console.log(sc);
            //         console.log(_this.$refs[sc]);
            //         console.log(_this.$refs[sc].focus());
            //         _this.$refs[sc].focus();
            //     }, 1)
            //     // this.$refs['inputBatchNoRef'][0].focus()
            // })
        },
        iCountChange() {
            // console.log(this.iCount)
            // this.currentRow.count = this.iCount;
            // this.currentRow.reCount = this.iCount;
        },
        iCountEnterFunction() {
            if (this.$isNotBlank(this.currentRow)) {
                this.currentRow.count = this.iCount;
                // this.currentRow.reCount = this.iCount;
            }
            this.focusNext('inputRef');
        },
        tableCountChange(row) {
            if (this.$isNotBlank(row)) {
                // row.count = row.reCount;
            }
        },
        tableRowClassName({row, rowIndex}) {
            row.index = rowIndex;
        },
        focusNext(nextRef) {
            this.$refs[nextRef].focus()
        },
        focusNextToTable(nextRef) {
            this.$refs[nextRef][0].focus()
        },
        // 刷新表单
        resetForm() {
            if (this.$refs["dataForm"]) {
                // 清空验证信息表单
                this.$refs["dataForm"].clearValidate();
                // 刷新表单
                this.$refs["dataForm"].resetFields();
                this.getList();
            }
        },
        addCode() {
            this.code = this.code.trim();
            if (this.$isBlank(this.code)) {
                this.$message.warning('请输入条码');
                return;
            }
            if (this.iCount <= 0) {
                this.$message.warning('请输入数量');
                return;
            }
            this.loading = true;
            let tQuery = {
                orderId: this.formData.id,
                count: this.iCount,
                code: this.code,
            };
            if (this.orderEditor) {
                addStockOrderDetailFromCode(tQuery).then((response) => {
                    this.loading = false;
                    if (response.code === 20000) {
                        this.getStockOrderDetailList();
                    } else {
                        this.$alert(response.message, '提示', {
                            confirmButtonText: '确定',
                            type: 'warning',
                            closeOnClickModal: true,
                            callback: action => {
                                this.$refs.inputRef.focus();
                            }
                        });
                    }
                });
            } else {
                getStockOrderDetailInstrument(tQuery).then((response) => {
                    this.loading = false;
                    if (response.code === 20000) {
                        for (let i = 0; i < this.codeArray.length; i++) {
                            if (this.codeArray[i].productId === response.data.productId) {
                                this.$alert("已添加", '提示', {
                                    confirmButtonText: '确定',
                                    type: 'warning',
                                    closeOnClickModal: true,
                                    callback: action => {
                                        this.$refs.inputRef.focus();
                                    }
                                });
                                break;
                            }
                            if (i + 1 === this.codeArray.length) {
                                this.codeArray.push(response.data);
                            }
                        }
                        if (this.codeArray.length === 0) {
                            this.codeArray.push(response.data);
                        }
                    } else {
                        this.$alert(response.message, '提示', {
                            confirmButtonText: '确定',
                            type: 'warning',
                            closeOnClickModal: true,
                            callback: action => {
                                this.$refs.inputRef.focus();
                            }
                        });
                    }
                });
            }
        },
        saveCodeArray(index, row) {
            if (this.$isBlank(row.batchNo)) {
                return this.$message.error('批次号不能为空');
            }
            // if (this.$isBlank(row.productDate)) {
            //     return this.$message.error('生产日期不能为空');
            // }
            // if (this.$isBlank(row.expireDate)) {
            //     return this.$message.error('失效日期不能为空');
            // }

            this.$refs.multipleTable.setCurrentRow();
            this.currentRow = {};
            this.selectedIndex = "";
            this.iCount = 0;

            this.detailLoading = true;
            // row.count = row.reCount;
            let tQuery = row;
            uploadStockOrderDetail(tQuery).then((response) => {
                this.detailLoading = false;
                if (response.code === 20000) {
                    this.$message.success("修改完成");
                    this.getStockOrderDetailList();
                    this.$refs.inputRef.focus();
                } else {
                    this.$message.error(response.message);
                }
            });
        },
        deleteCodeArray(index, row) {
            this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                this.$refs.multipleTable.setCurrentRow();
                this.currentRow = {};
                this.selectedIndex = "";
                this.iCount = 0;

                if (this.orderEditor) {
                    this.detailLoading = true;
                    if (this.$isNotBlank(row.id)) {
                        deleteStockOrderDetailById({id: row.id})
                            .then(response => {
                                this.detailLoading = false;
                                if (response.code === 20000) {
                                    this.$message.success(response.data);
                                    // this.getStockOrderDetailList();
                                    this.codeArray.splice(index, 1);
                                } else {
                                    this.$message.error(response.message);
                                }
                            })
                            .catch(() => {
                                this.detailLoading = false;
                            })
                    } else {
                        this.$message.success('删除成功');
                        this.codeArray.splice(index, 1);
                    }
                } else {
                    this.$message.success('删除成功');
                    this.codeArray.splice(index, 1);
                }
            }).catch(() => {

            });
        },
        copyDetail(row) {
            this.$confirm("是否复制该记录?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                // let tQuery = {
                //     id: row.id
                // }
                // this.detailLoading = true;
                // copyStockOrderDetail(tQuery)
                //     .then((response) => {
                //         this.detailLoading = false;
                //         if (response.code === 20000) {
                //             this.$message.success("复制成功");
                //             this.getStockOrderDetailList();
                //         } else {
                //             this.$message.error(response.message);
                //         }
                //     });

                let rData = JSON.parse(JSON.stringify(row));
                rData.id = null;
                if (this.codeArray.length === 0) {
                    this.codeArray.push(rData);
                    this.$refs.multipleTable.setCurrentRow(this.codeArray[0]);
                    this.currentRow = this.codeArray[0];
                    this.selectedIndex = 0;
                } else {
                    this.codeArray.unshift(rData);
                    this.$refs.multipleTable.setCurrentRow(this.codeArray[0]);
                    this.currentRow = this.codeArray[0];
                    this.selectedIndex = 0;
                }
                this.$message.success("复制成功");
                this.iCount = this.currentRow.count;
                this.focusNext('iCount');
            }).catch(() => {
            });
        },
        getInputFocus(event) {
            event.currentTarget.select();
        },
        tableSelection() {
            this.$refs.multipleTable.clearSelection();
            this.$refs.multipleTable.toggleAllSelection();
        },
        handleSizeChange(val) {
            this.query.limit = val;
            this.getStockOrderDetailList();
        },
        handleCurrentChange(val) {
            this.query.page = val;
            this.getStockOrderDetailList();
        },
        getStockOrderDetailList() {
            this.loading = true;
            stockOrderDetail(this.query) //查找该单号下的所有条码
                .then((response) => {
                    this.codeArray = response.data.list || [];
                    this.total = response.data.total || 0;
                    this.loading = false;
                })
                .catch(() => {
                    this.loading = false;
                    this.list = [];
                    this.total = 0;
                });
        },
        intentBack() {
            this.$router.go(-1);
        },
        // generateBillNo() {
        //     let tQuery = {
        //         action: this.formData.billType
        //     }
        //     this.loading = true;
        //     stockOrderGenerateBillNo(tQuery)
        //         .then((response) => {
        //             this.loading = false;
        //             if (response.code === 20000) {
        //                 this.formData.billNo = response.data;
        //                 // this.formData.billdate = parseTime(new Date(), '{y}{m}{d}');
        //                 this.formData.billdate = new Date();
        //             } else {
        //                 this.closeDialog(true);
        //             }
        //         });
        // },
        getBusType() {
            let query = {
                code: this.formData.invWarehouseCode,
                enabled: true,
            };
            getLocalJoinByUser(query)
                .then((response) => {
                    this.busTypes = response.data.list || [];
                    if (this.$isNotBlank(this.formData.billType)) {
                        this.curAction = this.getActionItem(this.formData.billType);
                        if (this.curAction != null) {
                        } else {
                            this.curAction = {corpType: 0, genUnit: false, changeEnable: false,};
                            this.formData.billType = null;
                        }
                    }
                })
                .catch(() => {
                });
        },
        selectOne(event) {
            this.formData.corpName = event.name;
            this.formData.corpId = event.erpId;
            this.formData.unitIdFk = event.erpId;
        },
        findMethod(query) {
            this.fromOptions = [];
            let cQuery = {
                key: query,
                corpType: null,
                outType: null,
            };
            if (this.curAction.corpType == 3) {//特殊往来
                cQuery.corpType = 4;
                this.formData.corpId = this.curAction.defaultUnit;
            } else if (this.curAction.corpType == 2)//客户
            {
                cQuery.corpType = 4;
                cQuery.outType = 2;

            } else if (this.curAction.corpType == 0) {
                cQuery.corpType = 2;
            } else return;

            getBasicUnitMaintains(cQuery)
                .then((response) => {
                    this.loading = false;
                    this.fromOptions = response.data.page.list || [];
                    if (this.curAction.corpType == 3) {
                        for (let i = 0; i < this.fromOptions.length; i++) {
                            if (this.fromOptions[i].erpId == this.formData.corpId) {
                                this.formData.corpName = this.fromOptions[i].name;
                            }
                        }
                    }
                })
                .catch(() => {
                    this.loading = false;
                });
        },
        getActionItem(action) {
            for (let i = 0; i < this.busTypes.length; i++) {
                if (this.busTypes[i].localAction === action) {
                    return this.busTypes[i];
                }
            }
        },
        actionChange(item) {
            this.curAction = this.getActionItem(item);
            this.formData.corpName = '';

            if (this.$isNotBlank(this.formData.fromSubInvCode)) {
                this.formData.fromSubInvCode = '';
            }
            // '';
            this.locInChange();
            this.findMethod();
        },
        locInChange() {
            this.$forceUpdate();
            // this.getBusType();
            this.invChange();
            this.findStorageMethod();
        },

        subStorageChange() {
            this.getBusType();
        },
        invChange() {
            if (this.$isNotBlank(this.formData.invWarehouseCode))
                this.formData.invWarehouseCode = null;
            this.findSubInvs();
        },

        findSubInvs() {
            this.subInvList = [];
            let query = {
                pcode: this.formData.locStorageCode
            };
            filterSubByInv(query)
                .then((response) => {
                    this.subInvList = response.data || [];
                    if (this.subInvList != null && this.subInvList.length == 1) {
                        this.formData.invWarehouseCode = this.subInvList[0].code;
                        this.getBusType();
                    }
                })
                .catch(() => {
                });
        }


    },
    filters: {},
    mounted() {
        document.body.ondrop = function (event) {
            event.preventDefault();
            event.stopPropagation();
        };
    },
    created() {
        if (this.$isNotBlank(this.idQuery.id)) {
            this.query.limit = 100;
            this.query.orderIdFk = this.idQuery.id;
            this.formData = this.idQuery.formData;
            this.orderEditor = true;
            this.sValue = this.formData.corpName;
            this.getStockOrderDetailList();

        } else {
            this.formData = {
                billNo: null,
                billdate: "",
                customerId: store.getters.customerId,
                billType: "",
                type: "2",
                corpName: "",
                corpId: "",
                noInvOut: "",
                locStorageCode: store.getters.locInvCode,
                invWarehouseCode: store.getters.locSubInvCode,
            };
            this.iCount = 0;
            this.orderEditor = false;
            this.formData.billdate = new Date();
            // this.generateBillNo();
        }
        this.findMethod();
        this.getBusType();
        this.getStorage();
        this.findSubInvByInv();
        this.findSubStorageMethod();
        this.codeArray = [];
        this.closeConfirmFunction(false);
    },
};
</script>
<style>

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

/**
解决el-input输入框 type=number时，输入中文光标上移问题
 */
.el-input__inner {
    line-height: 1px !important;
}

</style>



