<template>
    <div>

        <el-form :model="formData" :rules="formRules" ref="dataForm">
            <el-row type="flex" justify="end" v-if="editType == 1">
                <el-button-group style="display: flex;margin-bottom: 15px; margin-right: 50px">
                    <el-button
                        type="primary"
                        @click.native="saveOrder('3')"
                        :loading="loading"
                    >审核通过
                    </el-button
                    >
                    <el-button
                        type="primary"
                        @click.native="saveOrder('4')"
                        :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-date-picker
                                v-model="formData.billDate"
                                type="datetime"
                                placeholder="选择日期" :disabled="true"
                                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="locStorageCode">
                            <el-select v-model="formData.locStorageCode" placeholder="采购仓库信息" @change="locInChange"
                                       style="width: 50%" :disabled="true"
                                       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-select v-model="formData.invWarehouseCode" placeholder="采购分库信息" style="width: 50%"
                                       :disabled="true" 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-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.auditRemark" auto-complete="off" type="textarea"
                                      autosize></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">

                    <el-col :span="3">
                        <div class="ao-text">
                            <span>采购说明：</span>
                        </div>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item prop="billNo">
                            <el-input v-model="formData.remark" :disabled="true" auto-complete="off" type="textarea"
                                      autosize></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                    </el-col>
                    <el-col :span="7">
                        <el-form-item>
                            <el-checkbox v-model="formData.autoPurchase">是否生成采购入库单</el-checkbox>
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-row :gutter="20" style="margin-top: -10px" v-show="formData.autoPurchase">


                    <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.targetSubInv" placeholder="入库仓库信息" style="width: 100%"

                                       @change="targetInvChange"
                                       clearable>
                                <el-option
                                    v-for="item in tarSubList"
                                    :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 class="query-form-item" prop="targetBillAction">
                            <el-select v-model="formData.targetBillAction" placeholder="请选择单据类型"
                                       style="width: 100%"
                            >
                                <el-option
                                    v-for="item in busTypes"
                                    :key="item.localName"
                                    :label="item.localName"
                                    :value="item.localAction">
                                    <span style="float: left">{{ item.localName }}</span>
                                </el-option>
                            </el-select>
                        </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 label="序号" type="index" width="50"></el-table-column>
                    <el-table-column
                        label="产品通用名"
                        prop="productName"
                        show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                        label="规格型号"
                        prop="spec"
                        show-overflow-tooltip
                    ></el-table-column>

                    <el-table-column
                        label="计量单位"
                        prop="measname"
                        show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                        label="生产厂家"
                        prop="manufactory"
                        show-overflow-tooltip
                    ></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 label="操作" fixed="right" width="150">
                        <template slot-scope="scope">
                            <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="deleteCodeArray(scope.$index, scope.row)"
                            >删除
                            </el-button
                            >
                        </template>
                    </el-table-column> -->
                </el-table>
            </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"
                :purType="1"
            ></stockOrderNewSelectProduct>
        </el-dialog>
    </div>
</template>

<script>
import draggable from "vuedraggable";
import stockOrderNewSelectProduct from "../warehouse/stockOrderNewSelectProduct";
import {auditOrder, delApplyDetail, listApplyDetail} from "@/api/purchase/purPlan";
import {filterAllByUser} from "@/api/basic/invWarehouse";
import {filterSubByInv} from "@/api/basic/invSubWarehouse";
import {getLocalJoinByUser} from "@/api/basic/busLocalType";

export default {
    name: "idQuery",
    props: {
        closeDialog: {
            type: Function,
            required: true,
        },
        idQuery: {
            type: Object,
            required: true,
        },
        editType: {
            type: Object,
            required: true,
        },
    },
    data() {
        return {
            code: "",
            query: {
                orderIdFk: "",
                page: 1,
                limit: 10,
            },
            formData: {
                id: null,
                billNo: null,
                billDate: "",
                remark: "",
                deptCode: null,
                locStorageCode: null,
                invWarehouseCode: null,
                auditRemark: null,
                autoPurchase: false,
                targetInv: 1000,
                targetSubInv: null,
                targetBillAction: null,
            },
            formRules: {},
            codeArray: [],
            total: 0,
            loading: false,
            index: null,
            formLoading: false,
            formVisible: false,
            deleteLoading: false,
            orderNo: null,
            statusMap: {
                1: "草稿",
                2: "未审核",
                3: "已审核",
            },
            typeMap: {
                1: "预入库",
                2: "普通采购",
            },
            orderEditor: true,
            sOptions: [],
            sValue: [],
            sList: [],
            sLoading: false,
            busTypes: [],
            currentRow: {},
            selectedIndex: "",
            selectProductVisible: false,
            thisData: {},
            storageList: [],
            subInvList: [],
            tarSubList: [],
            invQueryData: {},


        };
    },
    components: {
        draggable,
        stockOrderNewSelectProduct,
    },
    methods: {
        saveOrder(status) {
            let tip = "";
            if (status == "3") {
                tip = "是否确定通过该采购计划？";
            } else {
                tip = "是否确定拒绝该采购计划？";
            }
            this.$confirm(tip, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                this.submitFunction(status);
            }).catch(() => {
                this.loading = false;
            });
        },
        submitFunction(status) {
            let tMessage = status === '1' ? '保存' : '提交';
            this.loading = true;
            let tQuery = {
                editStatus: status,
                purPlanEntity: this.formData,
                subErpOrders: this.codeArray,
            }
            auditOrder(tQuery)
                .then(response => {
                    this.loading = false;
                    if (response.code === 20000) {
                        this.$message.success(tMessage + "成功");
                        this.closeDialog(true);
                    } else {
                        this.$message.error(response.message);
                    }
                })
                .catch(() => {
                    this.loading = false;
                })
        },
        selectProductFunction() {
            this.selectProductVisible = true;
        },
        closeDialogC2(rData) {
            this.selectProductVisible = 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;
            }
        },
        rowChange(val) {
            this.currentRow = val;
            this.selectedIndex = val.index;
        },
        tableCountChange(row) {
            if (this.$isNotBlank(row)) {
                // row.count = row.reCount;
            }
        },
        tableRowClassName({row, rowIndex}) {
            row.index = rowIndex;
        },
        // 刷新表单
        resetForm() {
            if (this.$refs["dataForm"]) {
                // 清空验证信息表单
                this.$refs["dataForm"].clearValidate();
                // 刷新表单
                this.$refs["dataForm"].resetFields();
                this.getList();
            }
        },
        deleteCodeArray(index, row) {
            this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                this.$refs.multipleTable.setCurrentRow();
                this.currentRow = {};
                this.selectedIndex = "";

                if (this.orderEditor) {
                    this.detailLoading = true;
                    if (this.$isNotBlank(row.id)) {
                        delApplyDetail(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(() => {

            });
        },
        getStockOrderDetailList() {
            this.loading = true;
            listApplyDetail(this.query) //查找该单号下的所有条码
                .then((response) => {
                    console.log(response)
                    this.codeArray = response.data.list || [];
                    this.total = response.data.total || 0;
                    this.loading = false;
                })
                .catch(() => {
                    this.loading = false;
                    this.list = [];
                    this.total = 0;
                });
        },


        getStorage() {
            this.storageList = [];
            filterAllByUser()
                .then((response) => {
                    this.storageList = response.data || [];
                    if (this.storageList != null && this.storageList.length == 1) {
                        this.formData.locStorageCode = this.storageList[0].code;
                    }
                    this.findSubInvs();

                })
                .catch(() => {
                });
        },
        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;
                    }
                })
                .catch(() => {
                });
        },

        findTargetSubInvs() {
            this.tarSubList = [];
            let query = {
                pcode: 1000
            };
            filterSubByInv(query)
                .then((response) => {
                    this.tarSubList = response.data || [];
                    if (this.tarSubList != null && this.tarSubList.length == 1) {
                        this.formData.targetSubInv = this.tarSubList[0].code;
                        this.targetInvChange();
                    }
                })
                .catch(() => {
                });
        },
        targetInvChange() {
            let query = {
                code: this.formData.targetSubInv,
                enabled: true,
                spUse: true,
            };
            getLocalJoinByUser(query)
                .then((response) => {
                    this.busTypes = response.data.list || [];
                    // this.formData.targetBillAction = this.busTypes[0].localAction;
                })
                .catch(() => {
                });
        },

        locInChange(item) {
            if (this.formData.invWarehouseCode != null) {
                this.formData.invWarehouseCode = "";
            }
            this.formData.locStorageCode = item;
            this.findSubInvs();
        },
    },
    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.formData.targetInv = 1000;
            this.orderEditor = true;
            this.sValue = this.formData.corpName;
            this.getStockOrderDetailList();
        } else {
            this.formData = {
                id: null,
                billNo: null,
                billDate: "",
                remark: "",
                deptCode: null,
                locStorageCode: null,
                invWarehouseCode: null,
                auditRemark: null,
                autoPurchase: false,
                targetInv: 1000,
                targetSubInv: null,
                targetBillAction: null,
            };
            this.orderEditor = false;
        }
        this.getStorage();
        this.findTargetSubInvs();
        this.codeArray = [];
    },
};
</script>
<style>

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

</style>



