<template>
    <div>

        <el-form :model="formData" :rules="formRules" ref="dataForm">
            <el-button-group style="display: flex">
                <!--                <el-button-->
                <!--                    type="primary"-->
                <!--                    @click.native="submit('1')"-->
                <!--                    style="margin: -50px 0 10px auto; height: 35px"-->
                <!--                >保存订单-->
                <!--                </el-button-->
                <!--                >-->
                <el-button
                    type="primary"
                    @click.native="submit('0')"
                    style="margin: -50px 60px 10px auto; height: 35px"
                >提交订单
                </el-button
                >
            </el-button-group>

            <el-row :gutter="20">
                <el-col :span="2">
                    <div class="ao-text">
                        <span>入库单号：</span>
                    </div>
                </el-col>
                <el-col :span="8">
                    <el-form-item prop="corpOrderId">
                        <el-input v-model="formData.corpOrderId" auto-complete="off"
                                  :disabled="corpOrderIdDisabled"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="2">
                    <div class="ao-text">
                        <span>日期：</span>
                    </div>
                </el-col>
                <el-col :span="8">
                    <el-form-item prop="actDate">
                        <el-date-picker
                            v-model="formData.actDate"
                            type="datetime"
                            placeholder="日期"
                            :disabled="true"
                            style="width: 100%; "
                        >
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="2">
                    <div class="ao-text">
                        <span>往来信息：</span>
                    </div>
                </el-col>
                <el-col :span="8">
                    <el-form-item class="query-form-item" prop="fromCorp"
                                  v-if="curAction.corpType ==0">
                        <el-select
                            v-model="formData.fromCorp"
                            filterable
                            remote
                            clearable="true"
                            reserve-keyword
                            placeholder="请输入往来单位"
                            :remote-method="findMethod"
                            :loading="loading"
                            @change="unitChange"
                        >
                            <el-option
                                v-for="item in fromOptions"
                                :key="item.name"
                                :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.fromCorp"
                            filterable
                            remote
                            clearable="true"
                            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-form-item>
                    <el-form-item class="query-form-item" prop="fromCorp" v-if="curAction.corpType ==2">
                        <el-input v-model="formData.fromCorp" auto-complete="off"
                                  clearable
                                  placeholder="请输入病人住院号"
                        ></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="2">
                    <div class="ao-text">
                        <span>单据类型：</span>
                    </div>
                </el-col>
                <el-col :span="8">
                    <el-form-item class="query-form-item" prop="billType">
                        <el-select v-model="formData.action" placeholder="请选择单据类型"
                                   @change="actionChange">
                            <el-option
                                v-for="item in busTypes"
                                :key="item.name"
                                :label="item.name"
                                :value="item.action">
                                <span style="float: left">{{ item.name }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <!--            :disabled="actionEnable"/-->
            <el-row :gutter="20">

                <el-col :span="2">
                    <div class="ao-text">
                        <span>当前仓库：</span>
                    </div>
                </el-col>

                <el-col :span="8">
                    <el-form-item prop="locStorageCode">
                        <!--<el-select v-model="formData.billType" style="width: 100%" placeholder="业务类型" :disabled="true">-->
                        <!--<el-option label="送货单" value="deliveryNote"></el-option>-->
                        <!--</el-select>-->
                        <el-select v-model="formData.locStorageCode" placeholder="当前仓库信息">
                            <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-row>

            <el-row :gutter="20">
                <el-col :span="2">
                    <div class="ao-text">
                        <span>条码：</span>
                    </div>
                </el-col>
                <el-col :span="16">
                    <el-form-item prop="code">
                        <el-input
                            @focus="getInputFocus($event)"
                            @keypress.enter.native="addCode()"
                            v-model="formData.code"
                            auto-complete="off"
                            ref='inputRef'
                        ></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="2">
                    <el-button
                        type="primary"
                        size="small"
                        @click.native.stop="addCode()"
                        style="height: 31px; margin-left: 20px"
                    >添加
                    </el-button
                    >
                </el-col>

                <div class="text item" style="margin-left: 30px"> 已扫码条码：{{ total }}
                </div>
            </el-row>

            <el-table v-loading="loading" :data="codeArray" style="width: 100%;" max-height="350" height="350"
                      ref="multipleTable">
                <el-table-column
                    type="selection"
                    width="55">
                </el-table-column>
                <el-table-column label="序号" type="index" width="100"></el-table-column>
                <el-table-column
                    label="条码"
                    prop="code"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    label="扫码数量"
                    prop="count"
                    width="200"
                    show-overflow-tooltip
                ></el-table-column>

                <el-table-column label="操作" fixed="right" width="250">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            size="small"
                            @click.native.stop="deleteCode(scope.$index, scope.row)"
                        >删除
                        </el-button
                        >
                    </template>
                </el-table-column>
            </el-table>

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

<script>
import {
    errorCodeList, addOrderWeb, deleteCodesTempById, submitOrderWeb
} from "../../api/inout/order";
import {getBussinessType} from "../../api/basic/bussinessType";
import draggable from "vuedraggable";
import {parseTime} from "../../filtres/index";
import store from "../../store";
import {getBasicUnitMaintains} from "../../api/basic/basicUnitMaintain"
import {filterAll, filterAllByUser} from "@/api/basic/invWarehouse";
import {getLocalBusType, getLocalJoinBusType, getLocalJoinByUser} from "../../api/basic/busLocalType";

export default {
    name: "idQuery",
    props: {
        closeDialog: {
            type: Function,
            required: true,
        },
        idQuery: {
            type: Object,
            required: true,
        },
    },
    data() {
        return {
            codeQuery: {
                code: "",
            },
            query: {
                code: "",
                corpOrderId: "",
                page: 1,
                limit: 10,
            },
            busTypes: [],
            billAction: null,
            actionEnable: false,
            formData: {
                corpOrderId: "",
                code: "",
                actor: "",
                fromCorpId: "",
                fromCorp: null,
                fromType: 2,
                actDate: new Date(),
                action: null,
                locStorageCode: null,
            },
            storageList: [],
            formRules: {
                temp: [
                    {required: true, message: "请输入条码", trigger: "blur"}
                ],
            },
            corpOrderIdDisabled: false,
            codeArray: [],
            total: 0,
            loading: false,
            index: null,
            formLoading: false,
            formVisible: false,
            deleteLoading: false,
            orderNo: null,
            fromOptions: [],
            fromStorageOptions: [],
            curAction: {
                corpType: 0,
                genUnit: false,
            },
        };
    },
    components: {
        draggable,
    },
    methods: {
        submit(formName) {
            if (this.total < 1) {
                this.$message.error('未添加条码');
                return;
            }
            let tQuery = {
                orderId: this.idQuery.id,
                locStorageCode: this.formData.locStorageCode,
                action: this.formData.action,
                fromCorp: this.formData.fromCorp,
                fromCorpId: this.formData.fromCorpId,
            }
            submitOrderWeb(tQuery)
                .then((response) => {
                    console.log(response)
                    if (response.code === 20000) {
                        this.$message.success("提交成功");
                        this.closeDialog();
                    } else {
                        this.$message.error(response.message);
                    }
                    this.loading = false;
                });
        },
        // 刷新表单
        resetForm() {
            if (this.$refs["dataForm"]) {
                // 清空验证信息表单
                this.$refs["dataForm"].clearValidate();
                // 刷新表单
                this.$refs["dataForm"].resetFields();
                this.getList();
            }
        },
        addCode() {
            this.formData.corpOrderId = this.formData.corpOrderId.trim();
            this.actionEnable = true;

            if (this.$isBlank(this.formData.action)) {
                this.$message.warning("请选择单据类型！");
                return;
            }

            if (this.$isBlank(this.formData.corpOrderId)) {
                let date = new Date();
                this.formData.corpOrderId = parseTime(date, '{y}{m}{d}{h}{i}{s}') + Math.ceil(Math.random() * 89 + 10);
            }
            this.formData.code = this.formData.code.trim();
            if (this.$isBlank(this.formData.code)) return;
            this.loading = true;

            let tQuery = Object.assign(JSON.parse(JSON.stringify(this.formData)));
            tQuery.orderId = this.idQuery.id;
            tQuery.actDate = parseTime(this.formData.actDate, '{y}-{m}-{d} {h}:{i}:{s}');
            tQuery.action = this.formData.action;
            console.log(tQuery.action);
            addOrderWeb(tQuery).then((response) => {
                if (response.code === 20000) {
                    this.idQuery.id = response.data;
                    this.corpOrderIdDisabled = true;
                    this.getCodeList();
                } else {
                    this.$alert(response.message, '提示', {
                        confirmButtonText: '确定',
                        type: 'warning',
                        closeOnClickModal: true,
                        callback: action => {
                            this.$refs.inputRef.focus();
                        }
                    });
                    // this.$message.error(response.message);
                }
                this.loading = false;
            });
        },

        unitChange(row) {
            console.log(row);
            this.formData.fromCorpId = row.erpId;
            this.formData.fromCorp = row.name;
        },
        storageChange(row) {
            console.log(row);
            this.formData.fromCorpId = row.code;
            this.formData.fromCorp = row.name;
        },

        deleteCode(index, row) {
            console.log(row.id)
            this.$confirm("是否删除?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                this.loading = true;
                let tQuery = {
                    id: row.id
                }
                deleteCodesTempById(tQuery)
                    .then((response) => {
                        if (response.code === 20000) {
                            this.getCodeList();
                        } else {
                            this.$message.error(response.message);
                        }
                        this.loading = false;
                    });
            }).catch(() => {
            });
        },
        getInputFocus(event) {
            event.currentTarget.select();
        },
        tableSelection() {
            this.$refs.multipleTable.clearSelection();
            this.$refs.multipleTable.toggleAllSelection();
        },
        handleSizeChange(val) {
            this.query.limit = val;
            this.getCodeList();
        },
        handleCurrentChange(val) {
            this.query.page = val;
            this.getCodeList();
        },
        getCodeList() {
            this.loading = true;
            this.query.orderId = this.idQuery.id;
            errorCodeList(this.query) //查找该单号下的所有条码
                .then((response) => {
                    this.codeArray = response.data.list || [];
                    this.total = response.data.total || 0;
                    for (let i = 0; i < this.codeArray.length; i++) {
                        this.codeArray[i].fromType = this.formData.fromType;
                        this.codeArray[i].billType = this.formData.billType;
                    }
                    this.tableSelection();
                    this.loading = false;
                })
                .catch(() => {
                    this.loading = false;
                    this.list = [];
                    this.total = 0;
                });
        },
        intentBack() {
            this.$router.go(-1);
        },
        getBusType() {
            let query = {
                enabled: true,
            };
            getLocalJoinByUser(query)
                .then((response) => {
                    this.busTypes = response.data.list || [];
                    this.filterQuery.billAction = this.busTypes[0].action;
                })
                .catch(() => {
                });
        },

        geActionName(action) {
            this.busTypes.forEach((obj) => {
                if (obj.action == action) {
                    return obj.name;
                }
            });
        },


        findMethod(query) {
            console.log(query);
            this.fromOptions = [];
            let cQuery = {
                key: query,
            };
            getBasicUnitMaintains(cQuery)
                .then((response) => {
                    this.loading = false;
                    this.fromOptions = response.data.page.list || [];
                })
                .catch(() => {
                    this.loading = false;
                });
        },

        findStorageMethod(query) {
            console.log(query);
            this.fromStorageOptions = [];
            let cQuery = {
                key: query,
            };
            filterAllByUser(cQuery)
                .then((response) => {
                    this.fromStorageOptions = response.data || [];
                })
                .catch(() => {
                });
        },
        getStorage(event) {
            // let query = {
            //   advanceType: this.getActionName(event),
            // };
            this.storageList = [];
            // this.formData.locStorageCode = null;
            filterAllByUser()
                .then((response) => {
                    this.storageList = response.data || [];
                    this.fromStorageOptions = response.data || [];
                })
                .catch(() => {
                });
        },
        getActionName(action) {
            for (let i = 0; i < this.busTypes.length; i++) {
                if (this.busTypes[i].action === action) {
                    return this.busTypes[i].advanceType;
                }
            }
        },
        getActionItem(action) {
            for (let i = 0; i < this.busTypes.length; i++) {
                if (this.busTypes[i].action === action) {
                    return this.busTypes[i];
                }
            }
        },
        actionChange(item) {
            this.curAction = this.getActionItem(item);
            this.formData.locStorageCode = this.curAction.storageCode;
        },
    },
    filters: {},
    mounted() {
        document.body.ondrop = function (event) {
            event.preventDefault();
            event.stopPropagation();
        };
    },
    created() {
        this.formData.code = '';
        this.formData.actDate = new Date();
        this.codeArray = [];
        // this.formData.fromCorp = store.getters.customerId === 110 ? '医院' : store.getters.companyName;
        // this.formData.customerId = store.getters.customerId;
        this.getBusType();
        this.getStorage(this.formData.billType);
        if (this.$isNotBlank(this.idQuery.id)) {
            this.formData.actDate = new Date(this.idQuery.actDate);
            this.formData.corpOrderId = this.idQuery.corpOrderId;
            this.corpOrderIdDisabled = true;
            console.log(this.idQuery.fromCorp)
            this.formData.action = this.idQuery.action;
            this.formData.fromCorp = this.idQuery.fromCorp;
            this.formData.fromCorpId = this.idQuery.fromCorpId;
            this.formData.locStorageCode = this.idQuery.locStorageCode;
            this.actionEnable = true;
            this.getCodeList();
        } else {
            this.corpOrderIdDisabled = false;
            if (JSON.stringify(this.$route.query) === '{}') {
                // this.formData.corpOrderId = new Date().getTime() + (Math.ceil(Math.random() * 10 + 10) + '');
                let date = new Date();
                this.formData.corpOrderId = parseTime(date, '{y}{m}{d}{h}{i}{s}') + Math.ceil(Math.random() * 89 + 10);
            } else {
                // 将参数拷贝进查询对象
                let query = this.$route.query;
                this.orderNo = query.id;

                this.query = Object.assign(this.query, query);
                this.query.limit = parseInt(this.query.limit);
                this.query.corpOrderId = query.id;

                // 加载表格数据
                // this.getCodeList();
            }
        }
    },
};
</script>
<style>

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

</style>



