<template>
    <div>
        <el-form :model="formData" ref="dataForm">

            <el-button-group style="display: flex;margin: -40px 0 20px 80%; height: 35px">

                <el-button
                    type="primary"
                    @click.native="submit('0')"
                >生成单据
                </el-button
                >
            </el-button-group>

            <el-row :gutter="20">
                <el-col :span="3">
                    <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="true"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="3">
                    <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="3">
                    <div class="ao-text">
                        <span>当前仓库：</span>
                    </div>
                </el-col>

                <el-col :span="8">
                    <el-form-item prop="locStorageCode">
                        <el-select v-model="formData.locStorageCode" placeholder="当前仓库信息" @change="locCHange">
                            <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="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>
            <el-row :gutter="20">


                <el-col :span="3">
                    <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-row>
        </el-form>

        <el-table v-loading="detailLoading"
                  :data="detailList"
                  style="width: 100%; margin-top: 20px;">
            <el-table-column label="产品通用名" width="200" prop="coName"></el-table-column>
            <el-table-column label="包装规格" width="200" prop="packSpec"></el-table-column>
            <el-table-column label="批次号" width="100" prop="lotno"></el-table-column>
            <el-table-column label="生产日期" width="120" prop="produceDate"></el-table-column>
            <el-table-column label="失效日期" width="120" prop="expireDate"></el-table-column>
            <el-table-column label="单据数量" width="100" prop="count"></el-table-column>
            <el-table-column label="实际数量" width="100" prop="reCount"></el-table-column>
            <el-table-column label="价格" width="120" prop="price"></el-table-column>
            <el-table-column label="销售清单号（第二票）" width="180" prop="secSalesListNo"></el-table-column>
            <el-table-column label="销售发票号（第一票）" width="180" prop="firstSalesInvNo"></el-table-column>
            <el-table-column label="销售发票号（第二票）" width="180" prop="secSalesInvNo"></el-table-column>
            <el-table-column label="发票日期" width="150" prop="invoiceDate"></el-table-column>
            <el-table-column label="操作" width="100" prop="price" fixed="right">
                <template slot-scope="scope">
                    <el-button
                        type="text"
                        size="small"
                        @click="deleteOrderDetail(scope.$index, scope.row)"
                    >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script>
import {filterAllByLoc, filterAllByUser} from "@/api/basic/invWarehouse";
import {parseTime} from "@/filtres";
import {stockOrderChange, stockOrderDetail} from "@/api/warehouse/stockOrder";
import {getBusTypeByUser} from "@/api/warehouse/BusRole";
import {unitListBykey} from "@/api/warehouse/unit";
import {isBlank} from "@/utils/strUtil";

export default {
    name: "DialogChangeNewOrder",
    props: {
        closeDialog: {
            type: Function,
            required: true,
        },
        curRow: {
            type: Object,
            required: true,
        },
    },
    data() {
        return {
            formData: {
                corpOrderId: "",
                code: "",
                actor: "",
                fromCorpId: "",
                fromCorp: null,
                fromType: 2,
                actDate: new Date(),
                action: null,
                locStorageCode: null,
                mainAction: null
            },
            fromStorageOptions: [],
            fromSubStorageOptions: [],
            curAction: {
                corpType: 0,
                genUnit: false,
            },
            busTypes: [],
            fromOptions: [],
            loading: false,
            detailList: [],
            storageList: [],
            detailLoading: false,
            subInvList: [],

        }
    },
    methods: {

        submit() {
            if (this.$isBlank(this.formData.action)) {
                this.$message.warning("请选择单据类型！");
                return;
            }
            if (this.$isBlank(this.formData.locStorageCode)) {
                this.$message.error('当前仓库不能为空');
                return;
            }
            if (this.$isBlank(this.formData.fromCorp)) {
                this.$message.error('当前往来单位不能为空');
                return;
            }
            if (this.detailList.length == 0) {
                this.$message.error("产品列表不能为空");
                return;
            }
            let products = [];
            this.detailList.forEach(item => {
                let product = {
                    relId: item.relId,
                    batchNo: item.batchNo
                };
                products.push(product);
            });

            this.busTypes.forEach(item => {
                if (item.action === this.formData.action) {
                    this.formData.mainAction = item.mainAction;
                }
            })
            let tQuery = {
                stockOrderId: this.curRow.id,
                locStorageCode: this.formData.locStorageCode,
                action: this.formData.action,
                mainAction: this.formData.mainAction,
                fromCorp: this.formData.fromCorp,
                fromCorpId: this.formData.fromCorpId,
                products: products
            };
            stockOrderChange(tQuery)
                .then((response) => {
                    if (response.code === 20000) {
                        this.$message.success("提交成功");
                        this.closeDialog();
                    } else {
                        this.$message.error(response.message);
                    }
                    this.loading = false;
                });
        },


        locCHange() {
            this.findStorageMethod();
            this.formData.action = null;
            this.getBusType();
        },
        findStorageMethod(query) {
            if (this.formData.locStorageCode == null)
                return;
            this.fromStorageOptions = [];
            let cQuery = {
                locInvCode: this.formData.locStorageCode,
            };
            filterAllByLoc(cQuery)
                .then((response) => {
                    this.fromStorageOptions = response.data || [];
                })
                .catch(() => {
                });
        },
        findSubStorageMethod() {
            let cQuery = {
                pcode: this.formData.fromCorpId,
                filter: 2,
            };
            filterSubByInv(cQuery)
                .then((response) => {
                    this.fromSubStorageOptions = response.data || [];
                })
                .catch(() => {
                });
        },
        findMethod(query) {
            this.fromOptions = [];
            let cQuery = {
                key: query,
                corpType: null,
                outType: null,
                page: 1,
                limit: 100
            };

            unitListBykey(cQuery)
                .then((response) => {
                    this.loading = false;
                    this.fromOptions = response.data.list || [];
                    if (this.curAction.corpType == 3) {
                        for (let i = 0; i < this.fromOptions.length; i++) {
                            if (this.fromOptions[i].erpId == this.formData.fromCorpId) {
                                this.formData.fromCorp = this.fromOptions[i].name;
                            }
                        }
                    }
                })
                .catch(() => {
                    this.loading = false;
                });
        },

        storageChange(row) {
            this.formData.fromCorpId = row.code;
            this.formData.fromCorp = row.name;
            this.findSubStorageMethod();
        },

        unitChange(row) {
            this.formData.fromCorpId = row.erpId;
            this.formData.fromCorp = row.name;
        },
        actionChange(item) {
            this.curAction = this.getActionItem(item);
            this.findMethod();
        },
        getActionItem(action) {
            for (let i = 0; i < this.busTypes.length; i++) {
                if (this.busTypes[i].action === action) {
                    return this.busTypes[i];
                }
            }
        },
        getBusType() {
            let query = {};
            if (!isBlank(this.formData.locStorageCode)) {
                query.locInvCode = this.formData.locStorageCode;
            }
            getBusTypeByUser(query).then((res) => {
                this.busTypes = res.data.list || [];
                this.filterQuery.billAction = this.busTypes[0].action;
            }).catch((error) => {
            });
        },
        getStorage() {
            this.storageList = [];
            filterAllByUser()
                .then((response) => {
                    this.storageList = response.data || [];
                })
                .catch(() => {
                });
        },
        getStockOrderDetailList(orderId) {
            let query = {
                orderIdFk: orderId
            }
            stockOrderDetail(query)
                .then((response) => {
                    this.detailLoading = false;
                    this.detailList = response.data || [];
                })
                .catch(() => {
                    this.detailLoading = false;
                    this.detailList = [];
                });
        },
        deleteOrderDetail(index) {
            for (let i = 0; i < this.detailList.length; i++) {
                if (index === i) {
                    this.detailList.splice(index, 1);
                    break
                }
            }
        }
    },
    created() {
        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.getStorage();
        this.getStockOrderDetailList(this.curRow.orderId);
    }
}
</script>

<style scoped>

</style>
