<template>
    <div>
        <el-form :model="formData" :rules="formRules" 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 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-col :span="3">
                    <div class="ao-text">
                        <span>当前分库：</span>
                    </div>
                </el-col>

                <el-col :span="8">
                    <el-form-item prop="invWarehouseCode">
                        <el-select v-model="formData.invWarehouseCode" placeholder="当前分库信息" @change="findSubStorageMethod"
                        >
                            <el-option
                                v-for="item in subInvList"
                                :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.warehouseName }}</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.fromSubInvCode" placeholder="请选择分库" clearable="true" @change="getFormStorageCode"
                        >
                            <el-option
                                v-for="item in fromSubStorageOptions"
                                :key="item.code"
                                :label="item.name"
                                :value="item.code">
                                <span style="float: left">{{ item.name }}</span>
                                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.warehouseName }}</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">
                        <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"
                  @selection-change="changeFun"
                  style="width: 100%; margin-top: 20px;">
            <el-table-column label="产品通用名" width="200" prop="productName"></el-table-column>
            <el-table-column label="包装规格" width="200" prop="spec"></el-table-column>
            <el-table-column label="批次号" width="100" prop="batchNo"></el-table-column>

            <el-table-column label="生产日期" width="120" prop="productDate"></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 {getBasicUnitMaintains} from "@/api/basic/basicUnitMaintain";
import {parseTime} from "@/filtres";
import {getLocalJoinByUser} from "@/api/basic/busLocalType";
import {submitOrderWeb} from "@/api/warehouse/order";
import {stockOrderChange, stockOrderDetail} from "@/api/warehouse/stockOrder";
import {filterSubByInv} from "@/api/basic/invSubWarehouse";
import {isBlank} from "@/utils/strUtil";

export default {
    name: "DialogcChangeNewOrder",
    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,
                fromSubInvCode: null,
                invWarehouseCode: 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.invWarehouseCode)) {
                this.$message.error("当前分库不能为空");
                return;
            }
            if (this.curAction.corpType === 1 && this.$isBlank(this.formData.fromSubInvCode)) {
                this.$message.error('往来单位分库不能为空');
                return;
            }
            if (this.detailList.length == 0) {
                this.$message.error("产品列表不能为空");
                return;
            }

            if (this.formData.locStorageCode === this.formData.fromCorp || this.formData.invWarehouseCode === this.formData.fromSubInvCode) {
                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,
                invWarehouseCode: this.formData.invWarehouseCode,
                fromSubInvCode: this.formData.fromSubInvCode,

                products: products
            };
            stockOrderChange(tQuery)
                .then((response) => {
                    if (response.code === 20000) {
                        this.$message.success("提交成功");
                        this.closeDialog();
                    } else {
                        this.$message.error(response.message);
                    }
                    this.loading = false;
                });
        },
        getFormStorageCode(subInvId){
            this.fromSubStorageOptions.forEach(item => {
                if (subInvId === item.code) {
                    this.formData.fromCorp = item.warehouseName;
                }
            });
        },

        locCHange() {

            if (this.$isNotBlank(this.formData.invWarehouseCode)) {
                this.formData.invWarehouseCode = "";
            }
            this.findStorageMethod();
            this.findSubInvByInv(this.formData.locStorageCode);
        },


        findSubInvByInv(invCode) {
            this.subInvList = [];
            let query = {
                pcode: invCode,
                filter:3
            };
            filterSubByInv(query)
                .then((response) => {
                    this.subInvList = response.data || [];
                })
                .catch(() => {
                });
        },

        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() {
            this.formData.locStorageCode= this.subInvList.find(item => item.code == this.formData.invWarehouseCode).parentId
            let cQuery = {
                code: this.formData.invWarehouseCode,
                filter: 2,
            };
            filterSubByInv(cQuery)
                .then((response) => {
                    this.fromSubStorageOptions = response.data || [];
                })
                .catch(() => {
                });
            this.getBusType()
            this.formData.action="";
        },
        findMethod(query) {
            this.fromOptions = [];
            let cQuery = {
                key: query,
                corpType: null,
                outType: null,
            };
            if (this.curAction.corpType == 3) {//特殊往来
                cQuery.corpType = 4;
                this.formData.fromCorpId = 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.fromCorpId) {
                                this.formData.fromCorp = this.fromOptions[i].name;
                            }
                        }
                    }
                })
                .catch(() => {
                    this.loading = false;
                });
        },

        storageChange(row) {
            this.formData.fromCorpId = row.code;
            this.formData.fromCorp = row.name;
            if (isBlank(this.formData.fromCorp)) {
                this.fromSubStorageOptions = [];
                this.formData.fromSubInvCode = null;
            } else {
                this.findSubStorageMethod();
            }
        },

        unitChange(row) {
            this.formData.fromCorpId = row.erpId;
            this.formData.fromCorp = row.name;
        },
        actionChange(item) {
            this.curAction = this.getActionItem(item);
            this.formData.fromCorp = null;
            this.formData.fromSubInvCode = null;
            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 = {
                enabled: true,
                code:this.formData.invWarehouseCode
            };
            getLocalJoinByUser(query)
                .then((response) => {
                    this.busTypes = response.data.list || [];
                    this.filterQuery.billAction = this.busTypes[0].action;
                })
                .catch(() => {
                });
        },
        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.list || [];
                })
                .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.getBusType();
        this.findSubInvByInv(this.formData.locStorageCode);
        this.getStorage();
        this.getStockOrderDetailList(this.curRow.id);
    }
}
</script>

<style scoped>

</style>
