<template>
    <div>
        <div class="customer-head">
            <div class="customer-back">
                <el-button type="danger" style="border: none;background: none;color: red" icon="el-icon-arrow-left"
                    @click="backToList(0)">返回列表
                </el-button>
            </div>
            <div class="add-customer-btn">
                <el-button class="el-button&#45;&#45;small-yh" style="margin-left: 6px;" type="primary" size="small"
                    v-if="editButton" @click="inEdit">编 辑
                </el-button>
                <el-button class="el-button--small-yh" v-else style="margin-left: 6px;" type="primary" size="small"
                    :disabled="isSaveBtn" @click="editCustomer(0)">保 存
                </el-button>
                <el-button class="el-button--small-yh" v-if="form.id && form.status == 0" style="margin-left: 6px;"
                    type="success" size="small" @click="editCustomer(1)" :disabled="form.status == 1">提 交
                </el-button>
                <el-dropdown v-if="form.status == 1">
                    <el-button style="margin-left: 6px;" type="success" size="small">
                        审 核<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="auditPlan(2)">通过</el-dropdown-item>
                        <el-dropdown-item @click.native="approve()">驳回</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
        </div>
        <div style="margin-top: 50px">
            <trade-card title="基础信息">
                <avue-form :option="optionForm" v-model="form" ref="form">
                    <template slot-scope="{row,index}" slot="contacts">
                        <!-- 联系人 -->
                        <el-select v-model="form.contacts" placeholder="请选择" size="small" style="width:60%" clearable
                            filterable allow-create default-first-option @change="contactsChange($event)"
                            :disabled="editButton || form.status == 2">
                            <el-option v-for="item in contactsOption" :key="item.cname" :label="item.cname"
                                :value="item.contacts" />
                        </el-select>
                    </template>
                    <tempalte slot="customerName">
                        <dic-select v-model="form.customerName" placeholder="货主" key="id" label="cname" res="records"
                            url="/blade-sales-part/corpsDesc/list?current=1&size=20&&enableOrNot=1" :filterable="true"
                            :remote="true" dataName="cname" @selectChange="dicChange('customerName', $event)"
                            :disabled="editButton || form.status == 2"></dic-select>
                    </tempalte>
                </avue-form>
            </trade-card>
            <trade-card title="明细信息">
                <el-tabs v-model="activeName" type="card">
                    <el-tab-pane label="商品明细" name="sale_detail">
                        <avue-crud :option="optionContacts" v-model="formContacts" ref="formContacts"
                            :data="form.planItemsList" :key="key" @row-save="rowSave" @row-update="rowUpdate"
                            @row-close="rowClose" :before-close="beforeClose" @selection-change="selectionContacts"
                            @resetColumn="resetColumnTwo('formContacts', 'optionContacts', 'optionContactsBack', 269.1)"
                            @saveColumn="saveColumnTwo('formContacts', 'optionContacts', 'optionContactsBack', 269.1)">
                            <template slot-scope="{scope,row}" slot="menuLeft">
                                <el-button type="primary" icon="el-icon-plus" size="small"
                                    :disabled="editButton || form.status == 2" @click="rowAdd(row)">添加商品
                                </el-button>
                                <el-button type="success" size="small" :disabled="editButton || form.status == 2"
                                    icon="el-icon-bottom" @click="excelDialogfun('code')">按Code导入
                                </el-button>
                                <el-button type="primary" icon="el-icon-printer" size="small" @click="handlePrint">打印
                                </el-button>
                                <el-button type="danger" plain size="small" @click="batchDelete"
                                    :disabled="editButton || form.status == 2 || selectionMultilist.length == 0">
                                    一键删除
                                </el-button>
                            </template>
                            <template slot="goodsId" slot-scope="{ row }">
                                <!--<el-select v-if="row.$cellEdit" v-model="row.goodsId" allow-create filterable default-first-option >-->
                                <!--    <el-option v-for="(item, index) in goodsIdoptions" :key="index" :label="item.cname"-->
                                <!--        :value="item.id"></el-option>-->
                                <!--</el-select>-->
                                <span>{{ row.goodsName }}</span>
                            </template>
                            <template slot="goodsNum" slot-scope="{ row }">
                                <el-input-number v-if="!mingxibaocun" size="small" v-model="row.goodsNum"
                                    :controls="false" :precision="numberDecimal" style="width: 100%"></el-input-number>
                                <span v-else>{{ row.goodsNum }}</span>
                            </template>
                            <template slot="price" slot-scope="{ row }">
                                <el-input v-if="!mingxibaocun" size="small" v-model="row.price"
                                    style="width: 100%"></el-input>
                                <span v-else>{{ row.price }}</span>
                            </template>
                            <template slot="rebatePrice" slot-scope="{ row }">
                                <el-input v-if="!mingxibaocun" size="small" v-model="row.rebatePrice"
                                    style="width: 100%"></el-input>
                                <span v-else>{{ row.rebatePrice }}</span>
                            </template>
                            <template slot="dot" slot-scope="{ row }">
                                <el-select v-if="!mingxibaocun && row.whether == '1'" v-model="row.dot" allow-create
                                    filterable default-first-option @focus="picihaolistfun(row.goodsId)">
                                    <el-option v-for="(item, index) in picihaolist" :key="index" :label="item.dot"
                                        :value="item.dot"></el-option>
                                </el-select>
                                <span v-else>{{ row.dot }}</span>
                            </template>

                            <template slot="subTotalMoney" slot-scope="{ row }">
                                {{ (row.goodsNum * row.price).toFixed(2) }}
                            </template>

                            <template slot="remarks" slot-scope="{ row }">
                                <el-input v-if="!mingxibaocun" size="small" v-model="row.remarks"
                                    style="width: 100%"></el-input>
                                <span v-else>{{ row.remarks }}</span>
                            </template>
                            <template slot-scope="{type,size,row,index,disabled}" slot="menu">
                                <el-button v-if="mingxibaocun" :size="size" :disabled="editButton || form.status == 2"
                                    :type="type" :icon="row.$cellEdit ? 'el-icon-plus' : 'el-icon-edit'"
                                    @click="hangeditBtn(row, index)">编辑
                                </el-button>
                                <el-button v-else :size="size" :disabled="editButton || form.status == 2" :type="type"
                                    :icon="row.$cellEdit ? 'el-icon-plus' : 'el-icon-edit'"
                                    @click="hangbaocun(row, index)">保存
                                </el-button>
                                <el-button icon="el-icon-delete" :size="size" :disabled="editButton || form.status == 2"
                                    :type="type" @click="rowDelBox(row, index, 'planItemsList')">删除
                                </el-button>
                            </template>
                        </avue-crud>
                    </el-tab-pane>
                    <el-tab-pane label="入库记录" name="outbound_records">
                        <avue-crud :option="optionOutboundRecords" v-model="formContacts" ref="outbound_records"
                            :data="form.outboundRecordsList" @row-save="rowSave" @row-update="rowUpdate"
                            @resetColumn="resetColumnTwo('outbound_records', 'optionOutboundRecords', 'optionOutboundRecordsBack', 269.3)"
                            @saveColumn="saveColumnTwo('outbound_records', 'optionOutboundRecords', 'optionOutboundRecordsBack', 269.3)">
                        </avue-crud>
                    </el-tab-pane>
                </el-tabs>
            </trade-card>
            <report-dialog :switchDialog="switchDialog" reportName="轮胎商城-采购订单" :reportId="form.id"
                @onClose="onClose()"></report-dialog>
        </div>
        <el-dialog title="导入明细" append-to-body :visible.sync="excelBox" v-if="excelBox" width="555px"
            :close-on-click-modal="false" v-dialog-drag>
            <avue-form :option="excelOption" v-model="excelForm" table-loading="excelLoading"
                :upload-before="uploadBefore" :upload-after="uploadAfter">
                <template slot="excelTemplate">
                    <el-button type="primary" @click="derivation">
                        点击下载<i class="el-icon-download el-icon--right"></i>
                    </el-button>
                </template>
            </avue-form>
            <p style="text-align: center;color: #DC0505">
                温馨提示 第一次导入时请先下载模板
            </p>
        </el-dialog>
        <el-dialog title="选择商品" append-to-body class="el-dialogDeep" :visible.sync="dialogVisible" width="80%"
            :close-on-click-modal="false" :destroy-on-close="true" :close-on-press-escape="false" @close="closeGoods">
            <el-row :style="{ height: rowHeight }">
                <el-col :span="5">
                    <div>
                        <el-scrollbar>
                            <basic-container>
                                <avue-tree style="height: 70vh;overflow-y: auto" :option="treeOption"
                                    :data="treeDataGoods" @node-click="nodeClick" />
                            </basic-container>
                        </el-scrollbar>
                    </div>
                </el-col>
                <el-col :span="19">
                    <basic-container>
                        <avue-crud :option="optionTwo" :table-loading="loading" :data="goodsListShow" ref="crud"
                            :search.sync="SelectSearch" @refresh-change="refreshChange"
                            @selection-change="selectionChange" @search-change="goodsSearch" :page.sync="page"
                            @on-load="onLoadfun">
                            <template slot="menuLeft">
                                <el-tabs v-model="activeNameTabs" @tab-click="tabHandle">
                                    <el-tab-pane label="查询结果" name="searchList" />
                                    <el-tab-pane label="已选定数据" name="importStaging" />
                                </el-tabs>
                            </template>
                            <template slot="goodsNum" slot-scope="{row}">
                                <el-input-number v-model="row.goodsNum" size="small" :controls="false"
                                    :precision="numberDecimal" @input="amountChange($event, row)" style="width: 100%" />
                            </template>
                            <template slot="price" slot-scope="{row}">
                                <el-input-number v-model="row.price" size="small" :controls="false"
                                    style="width: 100%" />
                                <!--<span v-else>{{ row.price }}</span>-->
                            </template>
                            <template slot-scope="scope" slot="menu">
                                <el-button type="text" icon="el-icon-edit" size="small"
                                    @click.stop="importStagList(scope.row, scope.index)"
                                    v-if="activeNameTabs == 'searchList'"
                                    :disabled="goodsListSave.findIndex(item => item.id == scope.row.id) !== -1">
                                    选择
                                </el-button>
                                <el-button type="text" icon="el-icon-delete" size="small"
                                    @click.stop="removeStagList(scope.row, scope.index)" v-else>移除
                                </el-button>
                            </template>
                        </avue-crud>
                    </basic-container>
                </el-col>
            </el-row>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false" :loading="saveLoading">取 消</el-button>
                <el-button type="primary" @click="importGoods" v-if="commodityData !== true"
                    :loading="saveLoading">导入</el-button>
            </span>
        </el-dialog>
        <el-dialog title="驳回数据" append-to-body :visible.sync="approveVisible" width="30%" :close-on-click-modal="false"
            v-dialog-drag>
            <span>
                <el-input type="textarea" :rows="5" placeholder="请输入驳回原因" v-model="auditMsg">
                </el-input>
            </span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="approveVisible = false" size="mini">取消</el-button>
                <el-button type="danger" @click="approveVisible = false; auditPlan(3)" size="mini">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getDetails as getCustom } from "@/api/tirePartsMall/basicData/customerInformation"
import { getDetails as getDetailsLT } from "@/api/tirePartsMall/basicData/commodityInformation/index"
import { dateFormat } from "@/util/date";
import { getToken } from "@/util/auth";
import { shortcutWarehousing } from "@/api/tirePartsMall/salesManagement/saleOrder";
import { dotList, goodsDetail } from "@/api/tirePartsMall/purchasingManagement/warehouseEntryOrder";
import reportDialog from "@/components/report-dialog/main";
import checkSchedule from "@/components/checkL/checkSchedule";
import check from "@/components/checkL/check";
import { getCorpType, getList } from "@/api/tirePartsMall/basicData/commodityInformation"
import { isProcurement } from "@/api/basicData/configuration";
import commodity from "../../configuration/commodity.json";
import { getDetails, submit, itemRemove, auditPlan } from "@/api/storehouse/plan.js";
import dicSelect from "@/components/dicSelect/main";

export default {
    name: "detailsPage",
    data() {
        return {
            auditMsg: null,
            approveVisible: false,
            excelBox: false,
            numberDecimal: 0,
            SelectSearch: {},
            // 编辑还是保存
            mingxibaocun: true,
            // 批次号请求到的数据
            picihaolist: [],
            // 添加商品弹窗
            dialogVisible: false,
            // 弹窗高度
            rowHeight: '',
            // 左侧选择搜索
            treeDataGoods: [],
            treeDeptId: '',
            page: {
                pageSize: 10,
                currentPage: 1,
                total: 0,
                pageSizes: [10, 50, 100, 300, 500]
            },
            pageList: {
                pageSize: 10,
                currentPage: 1,
                total: 0
            },
            // 左侧选择
            treeOption: {
                addBtn: false,
                menu: false,
                size: "small",
                props: {
                    labelText: "标题",
                    label: "title",
                    value: "value",
                }
            },
            // 表格需要的配置
            optionTwo: commodity,
            loading: false,
            // 商品列表数据合计
            goodsListShow: [],
            // 商品列表暂存
            goodsListSave: [],
            saveLoading: false,
            commodityData: false,
            surplusRouteQuantityOption: [],
            tableData: [],
            // tabs切换
            activeNameTabs: 'searchList',
            data: [],

            inventory: 0,
            isStatus: 1,
            // 商品名称
            goodsIdoptions: [],
            dataList: [],
            dicUrlWithCustomId: '',
            sharedCompanyId: 0,
            isAddBtn: false,

            viewDisabled: false, // 请核和大审批按钮是否禁用
            isApplySettlement: false, // 请核数据按钮是否禁用
            isRevocationRequest: true, // 撤销审核
            isExamineBtn: true,  // 审批
            isAdd: false,
            editButton: false, // 编辑按钮和保存按钮的显示隐藏
            isSaveBtn: false, // 保存的禁用
            isDisabledTask: false, // 生成，撤销任务按钮是否禁用
            buttonText: '生成任务',
            buttonColor: 'success', // 初始颜色为success
            isContacts: false, // 基础信息插槽禁用

            goods: [],
            isDisabled: false,

            //地址
            recAddressOption: [],
            contactsOption: [],

            checkData: {},

            checkScheduleDialog: false,

            isConfirmRefundBtn: true,


            checkDialog: false,
            checkId: '',
            batchNo: '',
            switchDialog: false,
            activeName: "sale_detail",
            disabled: false,
            key: 0,
            templateUrl: '/api/blade-sales-part/ship/export-item', // 模板url
            form: {
                planItemsList: [],
                outboundRecordsList: [],
                bsType: 'RP',
                status: 0,
            },
            excelOption: {
                submitBtn: false,
                emptyBtn: false,
                column: [
                    {
                        label: "模板下载",
                        prop: "excelTemplate",
                        formslot: true,
                        span: 24
                    },
                    {
                        label: "导入明细",
                        prop: "excelFile",
                        type: "upload",
                        drag: true,
                        loadText: "上传中，请稍等",
                        accept: '.xls,.xlsx',
                        span: 24,
                        propsHttp: {
                            res: "data"
                        },
                        tip: "请上传 .xls,.xlsx 标准格式文件",
                        action: "/api/blade-sales-part/ship/import-item"
                    }
                ]
            },
            optionForm: {
                menuBtn: false,
                span: 8,
                disabled: false,
                labelWidth: 100,
                column: [{
                    label: '货主',
                    prop: "customerName",
                    disabled: false,
                    rules: [{
                        required: true,
                        message: " ",
                        trigger: "blur"
                    }]
                }, {
                    label: '联系人',
                    type: "select",
                    prop: "contacts",
                    disabled: false,
                    allowCreate: true,
                    filterable: true,
                    props: {
                        label: 'address',
                        value: 'id'
                    },
                    dicUrl: '/api/blade-sales-part/corpsAddr/corpIdByAddr?pid={{key}}'
                }, {
                    label: '电话',
                    disabled: false,

                    prop: "phone",
                }, {
                    label: "制单人",
                    prop: "createUserName",
                    disabled: true,
                }, {
                    label: '仓库',
                    prop: "storageId",
                    type: 'select',
                    disabled: false,
                    props: {
                        label: 'cname',
                        value: 'id'
                    },
                    dicUrl: '/api/blade-sales-part/tire/center/warehouse/storage/storageSelectedList',
                    rules: [{
                        required: true,
                        message: " ",
                        trigger: "blur"
                    }]
                },
                {
                    label: '入库日期',
                    prop: "businesDate",
                    searchProp: "businesDateList",
                    disabled: false,
                    type: "datetime",
                    value: dateFormat(new Date(), 'yyyy-MM-dd'),
                    format: "yyyy-MM-dd",
                    valueFormat: "yyyy-MM-dd",
                    rules: [
                        {
                            required: true,
                            message: "",
                            trigger: "blur"
                        }
                    ]
                },
                {
                    label: '单据编号',
                    prop: "ordNo",
                    disabled: true,
                },
                {
                    label: '计划总数量',
                    prop: "goodsTotalNum",
                    disabled: true,
                },
                {
                    label: '司机姓名',
                    prop: "driverName"
                },
                {
                    label: '司机电话',
                    prop: "driverPhone"
                },
                {
                    label: '车牌号',
                    prop: "licensePlate"
                },
                {
                    label: '人员选择',
                    prop: "warehouseKeeper"
                },
                {
                    label: '车辆照片',
                    prop: "vehiclePhoto",
                    listType: "picture-card",
                    type: "upload",
                    span: 24,
                    propsHttp: {
                        url: 'link',
                        name: 'originalName',
                        res: 'data'
                    },
                    action: '/api/blade-resource/oss/endpoint/put-file',
                },
                {
                    label: '备注',
                    prop: "remarks",
                    type: 'textarea',
                    disabled: false,
                    span: 24,
                    minRows: 1
                }]
            },
            formContacts: {},
            optionContacts: {},
            optionContactsBack: {
                disabled: false,
                border: true,
                align: 'center',
                index: true,
                addBtnText: "添加商品",
                updateBtnText: '保存',
                refreshBtn: false,
                dialogDrag: true,
                addBtn: false,
                span: 8,
                height: 500,
                // 添加
                addRowBtn: false,
                // 保存按钮
                editBtn: false,
                // 航编辑开启
                cellBtn: true,
                rowKey: 'ids',
                delBtn: false,
                menuWidth: 140,
                dialogTop: 25,
                dialogWidth: "80%",
                summaryText: "合计",
                showSummary: true,
                selection: true,
                sumColumnList: [{
                    name: "goodsNum",
                    type: "sum"
                }, {
                    name: "price",
                    type: "sum",
                    decimals: 2
                }, {
                    name: "sendNum",
                    type: "sum",
                    decimals: 2
                }, {
                    name: "subTotalMoney",
                    type: "sum",
                    decimals: 2
                }, {
                    name: "returnsNumber",
                    type: "sum"
                }, {
                    name: "returnsAmount",
                    type: "sum"
                }],
                column: [{
                    label: '商品名称',
                    prop: 'goodsId',
                    width: 200,
                    disabled: false,
                    remote: true,
                    hide: true,
                    overHidden: true,
                    type: 'select',
                    // dicData: [],
                    props: {
                        label: 'cname',
                        value: 'id'
                    },
                    // dicUrl: '/api/blade-sales-part/goodsDesc/goodsListAll?cname={{key}}'
                    dicUrl: "/api/blade-sales-part/goodsDesc/list?current=1&size=10&cname={{key}}&enableOrNot=1"
                    // dicUrl: "/api/blade-sales-part/goodsDesc/goodsListXs?cname={{key}}"
                }, {
                    label: '商品名称',
                    prop: 'goodsName',
                    width: 200,
                    disabled: false,
                    remote: true,
                    overHidden: true,
                }, {
                    label: '数量',
                    prop: 'goodsNum',
                    overHidden: true,
                    disabled: false,
                    cell: true,
                    width: 100,
                    rules: [{
                        required: true,
                        message: " ",
                        trigger: "blur"
                    }, {
                        validator: (rule, value, callback) => {
                            console.log(this.formContacts.inventory);
                            if (value < 0) {
                                callback(new Error("数量不能小于0"));
                            } else {
                                callback();
                            }
                        },
                        trigger: "blur"
                    }]
                },
                {
                    label: '价格',
                    prop: 'price',
                    overHidden: true,
                    width: 100,
                    disabled: false,
                    cell: true,
                    rules: [{
                        required: true,
                        message: " ",
                        trigger: "blur"
                    }, {
                        validator: (rule, value, callback) => {
                            if (value < 0) {
                                callback(new Error("价格不能小于0"));
                            } else {
                                callback();
                            }
                        },
                        trigger: "blur"
                    }]
                },
                {
                    label: '批次号',
                    prop: 'dot',
                    cell: true,
                    width: 120,
                    type: "select",
                    disabled: true,
                    allowCreate: true,
                    filterable: true,
                    dicData: [],
                    props: {
                        label: "dot",
                        value: "dot"
                    },
                    dicUrl: "/api/blade-sales-part/stockDesc/dotList",
                    overHidden: true,
                }, {
                    label: '小计',
                    prop: 'subTotalMoney',
                    overHidden: true,
                    width: 100,
                    disabled: true,
                    editDisplay: false,
                    addDisplay: false
                }, {
                    label: '商品编码',
                    prop: 'goodsNo',
                    overHidden: true,
                    disabled: false,
                    width: 100
                },
                {
                    label: '品牌',
                    prop: 'brandName',
                    disabled: false,
                    width: 100,
                    overHidden: true,
                },
                {
                    label: '规格型号',
                    prop: 'propertyName',
                    overHidden: true,
                    disabled: false,
                    width: 100
                }, {
                    label: '花纹',
                    prop: 'pattern',
                    overHidden: true,
                    disabled: false,
                    width: 100
                }, {
                    label: '商品描述',
                    prop: 'goodsDescription',
                    disabled: false,
                    overHidden: true,
                    width: 100
                },
                {
                    label: '单位',
                    prop: 'units',
                    type: "select",
                    disabled: false,
                    props: {
                        label: "dictValue",
                        value: "dictValue"
                    },
                    dicUrl: "/api/blade-system/dict-biz/dictionary?code=unit",
                    overHidden: true,
                    width: 100
                },
                {
                    label: '备注',
                    prop: "remarks",
                    overHidden: true,
                    width: 100,
                    disabled: false,

                }
                ]
            },
            selectionMultilist: [], // 多选数据
            optionPaymentDetails: {},
            optionPaymentDetailsBack: {
                align: 'center',
                index: true,
                addBtnText: "录入明细",
                menu: false,
                refreshBtn: false,
                dialogDrag: true,
                addBtn: false,
                span: 8,
                height: 600,
                addRowBtn: false,
                editBtn: false,
                delBtn: false,
                menuWidth: 140,
                dialogTop: 25,
                dialogWidth: "80%",
                column: [{
                    label: '支付编号',
                    prop: 'serialNumber'
                }, {
                    label: '金额',
                    prop: 'amount'
                }, {
                    label: '类型',
                    prop: 'type'
                }, {
                    label: '支付时间',
                    prop: 'createTime'
                }]
            },
            optionOutboundRecords: {},
            optionOutboundRecordsBack: {
                align: 'center',
                index: true,
                menu: false,
                addBtnText: "录入明细",
                refreshBtn: false,
                dialogDrag: true,
                addBtn: false,
                span: 8,
                height: 600,
                addRowBtn: false,
                editBtn: false,
                delBtn: false,
                // menuWidth: 140,
                dialogTop: 25,
                dialogWidth: "80%",
                column: [{
                    label: '入库单号',
                    prop: 'billno'
                },
                // {
                //     label: '来源单号',
                //     prop: 'ordNo'
                // },
                {
                    label: '数量',
                    prop: 'goodsTotalNum'
                }, {
                    label: '实际数量',
                    prop: 'sendTotalNum'
                }, {
                    label: '业务类型',
                    prop: 'bizTypeName'
                }, {
                    label: '状态',
                    prop: 'statusName'
                }, {
                    label: '业务时间',
                    prop: 'createTime'
                }]
            }
        }
    },
    components: { reportDialog, check, checkSchedule, dicSelect },
    props: {
        onLoad: Object,
        detailData: Object
    },
    async created() {
        this.findObject(this.optionContactsBack.column, "goodsId").click = ({ value, column }) => {
            this.$refs.formContacts.dicInit()
        }
        this.findObject(this.optionContactsBack.column, "goodsId").change = ({ value, column }) => {
            if (this.formContacts.goodsId !== value) {
                goodsDetail({
                    id: value,
                    customId: this.dicUrlWithCustomId,
                    stock: this.form.storageId ? this.form.storageId : ''
                }).then(res => {
                    this.goods = res.data.data
                    this.formContacts.goodsNo = res.data.data.code
                    this.formContacts.brandId = res.data.data.brandId
                    this.formContacts.inventory = res.data.data.inventory
                    // this.formContacts.brandId = res.data.data.brandName
                    // this.formContacts.brandName = res.data.data.brandId

                    this.formContacts.propertyName = res.data.data.specificationAndModel
                    this.formContacts.pattern = res.data.data.brandItem
                    this.formContacts.goodsDescription = res.data.data.goodsDescription
                    this.formContacts.units = res.data.data.unit
                    this.formContacts.price = res.data.data.price
                    //
                    this.formContacts.sharedCompanyId = res.data.data.sharedCompanyId
                    console.log(res.data.data.sharedCompanyId);
                    console.log(res.data.data.sharedCompanyName);
                    this.form.sharedCompanyId = res.data.data.sharedCompanyId
                    this.form.sharedCompanyName = res.data.data.sharedCompanyName
                    this.sharedCompanyId = res.data.data.sharedCompanyId
                    console.log(res.data.data.sharedCompanyId);
                    console.log(this.form.planItemsList);
                    for (let i = 0; i < this.form.planItemsList.length; i++) {
                        console.log(Number(this.form.planItemsList[i].sharedCompanyId));
                        if (Number(this.form.planItemsList[i].sharedCompanyId) != Number(res.data.data.sharedCompanyId)) {
                            this.isStatus = 0
                        }
                    }
                    if (res.data.data.whether == 0) {
                        this.findObject(this.optionContactsBack.column, "dot").disabled = true
                    } else {
                        this.findObject(this.optionContactsBack.column, "dot").disabled = false
                        dotList({
                            storageId: this.form.storageId,
                            goodsId: this.formContacts.goodsId
                        }).then(res => {
                            this.findObject(this.optionContactsBack.column, "dot").dicData = res.data.data
                        })
                    }
                })
            }
        }
        this.optionContacts = await this.getColumnData(this.getColumnName(269.1), this.optionContactsBack);
        this.optionOutboundRecords = await this.getColumnData(this.getColumnName(269.3), this.optionOutboundRecordsBack);
        this.key++
        if (this.onLoad.id && this.detailData.id) {
            this.$set(this.optionForm, 'disabled', true)
            this.$set(this.optionContactsBack, 'disabled', true)
            this.editButton = true
            this.getDetail(this.onLoad.id, true)
        } else if (this.onLoad.id) {
            this.getDetail(this.onLoad.id, true)
        }
        isProcurement({ "param": "number.decimal" }).then(res => {
            this.numberDecimal = res.data.data ? Number(res.data.data) : 0
        })
    },
    mounted() {
        this.$nextTick(() => {
            // 监听浏览器高度变化，改变表格高度
            window.onresize = () => {
                this.rowHeight = (window.innerHeight - 130) + 'px'
            }
        })
    },
    methods: {
        inEdit() {
            if (this.form.status != 2) {
                this.editButton = false
                this.$set(this.optionForm, 'disabled', false)
                this.$set(this.optionContactsBack, 'disabled', false)
            }
        },
        dicChange(name, row) {
            if (name == 'customerName') {
                if (row) {
                    this.form.customerId = row.id
                    getCustom({ id: row.id }).then(res => {
                        if (res.data.data) {
                            this.dicUrlWithCustomId = res.data.data.id ? res.data.data.id : ''
                            // this.form.storageId = this.form.storageId ? this.form.storageId : res.data.data.deliveryWarehouseId
                            this.form.contacts = res.data.data.corpsAttnList[0].cname
                            this.form.phone = res.data.data.corpsAttnList[0].tel
                            this.contactsOption = res.data.data.corpsAddrList
                        }
                    })
                } else {
                    this.form.customerId = null
                    this.form.customerName = null
                    this.dicUrlWithCustomId = null
                    // this.form.storageId = null
                    this.form.contacts = null
                    this.form.phone = null
                }
            }
        },
        // 一键入库
        oneClickStorage() {
            if (this.form.planItemsList.length == 0) {
                this.$message.warning('请先添加采购明细')
                return
            }
            // 计算合计用于展示
            let goodsNumhe = 0
            let subTotalMoneyhe = 0
            for (let item of this.form.planItemsList) {
                goodsNumhe += Number(item.goodsNum)
                subTotalMoneyhe += Number(item.subTotalMoney)
            }
            this.$alert(`<div style="text-align: center"><span style="color: #d85542">一件采购入库不可撤销,请确认无误在操作</span><br><span>本次入库金额:${subTotalMoneyhe.toFixed(2)}</span><br><span>本次入库数量:${goodsNumhe}</span><br><span>是否要一件采购入库?</span></div>`, '提示', {
                dangerouslyUseHTMLString: true,
            }).then(() => {
                const loading = this.$loading({
                    lock: true,
                    text: '加载中',
                    spinner: 'el-icon-loading',
                    background: 'rgba(255,255,255,0.7)'
                });
                shortcutWarehousing(this.form).then(res => {
                    this.$message.success("保存成功");
                    this.isAddBtn = true // 表格的添加商品禁用
                    this.getDetail(res.data.data.id)
                    loading.close();
                }).catch(() => {
                    loading.close();
                })
            })

        },
        // 获取左侧筛选
        getAllWorkDicts() {
            getCorpType({ corpType: 'SP', whetherIntegral: '0' }).then(res => {
                this.treeDataGoods = res.data.data;
            });
        },
        //导入页左商品类型查询
        nodeClick(data) {
            this.treeDeptId = data.id;
            this.page.currentPage = 1;
            this.onLoadfun(this.page, { ...this.SelectSearch, goodsTypeId: this.treeDeptId });
        },
        closeGoods() {
            this.treeDataGoods = [];
            this.treeDeptId = "";
            this.activeNameTabs = "searchList";
        },
        //刷新触发
        refreshChange() {
            this.page.currentPage = 1;
            this.onLoadfun(this.page);
        },
        // 这个方法是解决 this.onLoad is not a function 的问题
        onaloadfun(page, params = { artsVision: this.form.belongToCorpId }) {
            this.loading = true;
            getList({
                ...params,
                current: page.currentPage,
                size: page.pageSize,
                whetherIntegral: '0'
            }).then(res => {
                console.log(res, 1213)
                const data = res.data.data;
                this.page.total = data.total;
                this.pageList.total = data.total
                this.data = data.records;
                this.goodsListShow = data.records;
                this.loading = false;
            })
        },
        //选中触发
        selectionChange(list) {
            this.tableData = list
        },
        // 点击搜索触发
        goodsSearch(params, done) {
            this.page.currentPage = 1;
            params = {
                ...params,
                artsVision: this.form.belongToCorpId
            }
            this.onLoadfun(this.page, params);
            done()
        },
        // 标签页切换
        tabHandle(data) {
            if (data.name == 'searchList') {
                this.goodsListShow = this.data;
                this.page.total = this.pageList.total
            } else if (data.name == 'importStaging') {
                this.goodsListShow = this.goodsListSave;
                this.page.total = 0
            }
        },
        // 商品信息价格计算
        amountChange(value, row) {
            if (value > 0) {
                this.$refs.crud.toggleRowSelection(row, true);
            } else {
                this.$refs.crud.toggleRowSelection(row, false);
            }
        },
        importStagList(row, index, type) {
            this.goodsListSave.push(row);
        },
        removeStagList(row, index, type) {
            this.goodsListSave.splice(row.$index, 1)
        },
        //确认导入触发
        async importGoods() {
            this.surplusRouteQuantityOption.push({ storageQuantity: '0' });
            if (this.goodsListSave.length > 0) {
                this.goodsListSaveHandle()
            } else {
                if (this.tableData.length > 0) {
                    this.tableDataHandle()
                }
            }
        },

        // 导入按钮事件
        tableDataHandle() {
            // 循环获取库存数量
            for (let item of this.tableData) {
                console.log(item, '循环导入')
                let page = {}
                if (this.form.storageId) {
                    page.storageId = this.form.storageId
                }
                page.goodsId = item.id
                dotList(page).then(res => {
                    console.log(res.data, '获取到的数据')
                    var obj = {}
                    if (res.data.data.length > 0) {
                        obj.inventory = res.data.data[0].balanceQuantity
                        if (item.dot) {
                            obj.dot = item.dot
                        } else {
                            obj.dot = ''
                        }
                    }
                    this.form.planItemsList.push({
                        ...obj,
                        price: item.price,
                        goodsId: item.id,
                        goodsName: item.cname,
                        dot: item.dot,
                        brandName: item.brandName,
                        brandId: item.brandId,
                        goodsTypeId: item.goodsTypeId,
                        goodsNo: item.code,
                        // propertyName:item.typeno,
                        // 规格型号
                        propertyName: item.specificationAndModel,
                        // 花纹
                        pattern: item.brandItem,
                        // 商品描述
                        goodsDescription: item.goodsDescription,

                        goodsNum: item.goodsNum,
                        units: item.unit,
                        inventory: item.inventory,
                        // sendNum:res.data.data[0],
                        // 小计
                        subTotalMoney: item.goodsNum * item.price,
                        //
                        // inventory:item.balanceQuantity,
                        // 备注
                        remarks: item.remarks,
                        // 判断批次号是否可以编辑
                        whether: item.whether,
                        rebatePrice: item.rebatePrice,
                        // 批次号的状态
                        dotedittype: false,
                        // 价格数量
                        goodsNumtype: false,
                        // 价格
                        pricetype: false,
                        // 是否是编辑状态
                        mingxibaocun: true
                    })
                    console.log(this.form.planItemsList)
                })
            }
            this.mingxibaocun = false
            this.dialogVisible = false
        },
        // 导入
        goodsListSaveHandle() {
            this.tableData = this.goodsListSave
            this.tableDataHandle()
        },

        //导入商品弹窗列表查询
        onLoadfun(page, params = {}) {
            console.log(params)
            this.loading = true;
            getList({
                ...params,
                current: page.currentPage,
                size: page.pageSize,
                customId: this.form.customerId,
                stock: this.form.storageId,
                enableOrNot: 1,
                artsVision: this.form.belongToCorpId,
                goodsTypeId: this.treeDeptId,
                whetherIntegral: '0',
                ...Object.assign(params, this.SelectSearch)
            }).then(res => {
                res.data.data.records.forEach(e => {
                    e.rebatePrice = 0
                })
                const data = res.data.data;
                this.page.total = data.total;
                this.pageList.total = data.total
                this.data = data.records;
                this.goodsListShow = data.records;

                // 获取单价数据
                for (let item of this.goodsListShow) {
                    let page = {}
                    item.goodsNum = item.goodsNum ? item.goodsNum : 0
                    if (this.form.storageId) {
                        page.storageId = this.form.storageId
                    }
                    page.goodsId = item.id
                    if (this.form.storageId) {
                        dotList(page).then(res => {
                            item.price = res.data.data[0].inventoryCostPrice ? res.data.data[0].inventoryCostPrice : 0
                        })
                    }
                }
                this.loading = false;
            })
        },
        // 采购明细行编辑
        hangeditBtn(row, index) {
            for (let item of this.form.planItemsList) {
                this.picihaolistfun(item.goodsId)
                getDetailsLT({ id: item.goodsId }).then((res) => {
                    this.$set(item, 'whether', res.data.data.whether)
                })
            }


            row.dotedittype = true
            // 价格数量
            row.goodsNumtype = true
            row.pricetype = true
            // 编辑和保存状态切换
            this.mingxibaocun = false
        },
        // 保存按钮
        hangbaocun(row) {
            row.dotedittype = false
            row.goodsNumtype = false
            row.pricetype = false
            this.mingxibaocun = true
        },
        // 批次号获取数据
        picihaolistfun(goodsId) {
            dotList({
                storageId: this.form.storageId,
                goodsId: goodsId
            }).then(res => {
                this.picihaolist = res.data.data
            })
        },

        // 编辑
        editBtn(row, index) {
            this.$refs.formContacts.dicInit()
            dotList({
                storageId: this.form.storageId,
                goodsId: this.formContacts.goodsId
            }).then(res => {
                this.findObject(this.optionContactsBack.column, "dot").dicData = res.data.data
            })
        },
        //联系人change
        contactsChange(e) {
            console.log(e);
            console.log(this.contactsOption);
            // 假设this.contactsOption是你的数组对象
            let matchedContact = this.contactsOption.find(item => item.contacts == e);
            // 判断是否找到匹配的对象
            this.$set(this.form, 'phone', matchedContact.tel)

        },
        uploadAfter(res, done, loading, column) {
            if (Array.isArray(res)) {
                if (res instanceof Array) {
                    this.form.planItemsList = this.form.planItemsList.concat(res)
                    res.forEach(item => {
                        dotList({
                            storageId: this.form.storageId,
                            goodsId: res.goodsId
                        }).then(e => {
                            this.findObject(this.optionContactsBack.column, "dot").dicData = e.data.data
                        })
                    })
                }
            } else {
                this.$message.error(res)
            }
            loading = false;
            done(res);
        },
        derivation() {
            window.open(
                `${this.templateUrl}?${this.website.tokenHeader
                }=${getToken()}&stockId=${this.form.storageId}`
            );
        },
        uploadBefore(file, done, loading) {
            done();
            loading = true;
        },
        // 销售明细 导入按钮
        excelDialogfun(name) {
            if (!this.form.customerId) {
                this.$message.error('请选择货主')
                return
            }
            if (name == '名称') {
                this.findObject(this.excelOption.column, "excelFile").action = '/api/blade-sales-part/order/import-item-name'
                this.templateUrl = '/api/blade-sales-part/order/export-item-name'
            } else if (name == 'code') {
                this.findObject(this.excelOption.column, "excelFile").action = '/api/blade-sales-part/order/import-item-code'
                this.templateUrl = '/api/blade-sales-part/order/export-item-code'
            }
            this.excelBox = true
        },
        approve(type) {
            this.approveVisible = true
            this.auditMsg = null
        },
        auditPlan(type) {
            if (type == 2) {
                this.$confirm('是否提交审核?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let obj = {
                        id: this.form.id,
                        status: type,
                        auditMsg: type == 3 ? this.auditMsg : null,
                        version: this.form.version
                    }
                    auditPlan(obj).then(res => {
                        this.getDetail(this.form.id)
                    })
                })
            }
            if (type == 3) {
                let obj = {
                    id: this.form.id,
                    status: type,
                    auditMsg: type == 3 ? this.auditMsg : null,
                    version: this.form.version
                }
                auditPlan(obj).then(res => {
                    this.getDetail(this.form.id)
                })
            }

        },
        //修改提交触发
        editCustomer(type) {
            this.$refs["form"].validate((valid, done) => {
                done();
                let picihao = false
                if (valid) {
                    for (let i in this.form.planItemsList) {
                        console.log(this.form.planItemsList[i], 1800)
                        this.form.planItemsList[i].subTotalMoney = this.form.planItemsList[i].goodsNum * this.form.planItemsList[i].price
                        if (!this.form.planItemsList[i].pid) {
                            if (this.form.planItemsList[i].whether == '1') {
                                if (!this.form.planItemsList[i].dot) {
                                    this.$message.warning(`采购明细序号${Number(i) + 1}的批次号不能为空`);
                                    picihao = true
                                    break;
                                }

                            }
                        }
                        if (this.form.planItemsList[i].goodsNum <= 0) {
                            this.$message.warning(`采购明细序号${Number(i) + 1}的数量不能为零`);
                            picihao = true
                        }
                        if (!this.form.planItemsList[i].sendNum) {
                            this.form.planItemsList[i].sendNum = 0
                        }
                    }
                    let obj = {
                        ...this.form,
                        storageName: this.form.$storageId ? this.form.$storageId : '',
                        status: type,
                    }
                    const loading = this.$loading({
                        lock: true,
                        text: '加载中',
                        spinner: 'el-icon-loading',
                        background: 'rgba(255,255,255,0.7)'
                    });

                    submit(obj).then(res => {
                        this.$message.success("操作成功");
                        this.mingxibaocun = true
                        this.getDetail(res.data.data)
                    }).finally(() => {
                        loading.close();
                    });
                } else {
                    return false;
                }
            });
        },
        //关闭弹窗表单
        beforeClose(done, type) {
            done()
        },
        getDetail(id, type) {
            const loading = this.$loading({
                lock: true,
                text: '加载中',
                spinner: 'el-icon-loading',
                background: 'rgba(255,255,255,0.7)'
            })
            getDetails({ id: id }).then(res => {
                this.form = res.data.data
                this.dataList = res.data.data.paymentRecordsList ? res.data.data.paymentRecordsList : [];
                this.$nextTick(() => {
                    this.$refs.formContacts.doLayout()
                })
                if (res.data.data.status == 2) {
                    this.$set(this.optionForm, 'disabled', true)
                    this.$set(this.optionContactsBack, 'disabled', true)
                    this.editButton = true
                }
                loading.close();
            }).catch(() => {
                loading.close();
            })
        },
        rowDelBox(row, index, type) {
            this.$confirm("确定将选择数据删除?", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                if (row.id) {
                    itemRemove({ ids: row.id }).then(res => {
                        this.form.planItemsList.splice(index, 1);
                        this.$message.success("操作成功!");
                    });
                } else {
                    this.form[type].splice(index, 1);
                    this.$message.success("操作成功!");
                }
            }
            );
        },
        // 明细信息多选
        selectionContacts(list) {
            this.selectionMultilist = list
        },
        // 一键删除
        batchDelete() {
            if (this.selectionMultilist.length == 0) {
                return this.$message.warning('请选择要删除的数据')
            }
            this.$confirm("确定将选择数据删除?", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                let multiList = this.selectionMultilist
                let arr = this.form.planItemsList
                // 获取有id 的数据
                const itemsWithId = multiList.filter(item => item.hasOwnProperty('id'));
                let arrIds = itemsWithId.map(item => item.id) // 获取id 数据
                // 把选中的删除掉
                multiList.forEach((item) => {
                    for (let index in arr) {
                        if (JSON.stringify(item) == JSON.stringify(arr[index])) {
                            arr.splice(Number(index), 1)
                        }
                    }
                })
                // 有id 的处理
                if (itemsWithId.length != 0) {
                    itemRemove({ ids: arrIds.join(',') }).then(res => {
                        this.$message.success("操作成功!");
                    });
                }
            })
        },
        rowSave(form, done, loading) {
            form.subTotalMoney = form.goodsNum * form.price
            form.goodsName = form.$goodsId
            if (this.isStatus) {
                console.log(form);
                done(form)
            } else {
                this.$message.error('请选择相同商户的商品')
            }
        },
        rowUpdate(form, index, done, loading) {
            this.$set(form, 'goodsName', form.$goodsId)
            console.log(form);
            done(form)
        },
        rowAdd(row) {
            if (!this.form.customerId) {
                this.$message.error('请选择货主')
                return
            }
            if (!this.form.storageId) {
                this.$message.error('请选择仓库')
                return
            }
            this.optionContactsBack.column.forEach(its => {
                if (its.prop == 'goodsId' || its.prop == 'goodsNum' || its.prop == 'price' || its.prop == 'dot' || its.prop == 'remarks') {
                    its.disabled = false
                } else {
                    its.disabled = true
                }
            })
            this.getAllWorkDicts()
            this.refreshChange()
            this.goodsListSave = []
            this.dialogVisible = true
        },
        //打印
        handlePrint() {
            this.switchDialog = !this.switchDialog;
        },
        onClose(val) {
            this.switchDialog = val;
        },
        //自定义列保存
        async saveColumnTwo(ref, option, optionBack, code) {
            /**
             * 已定义全局方法，直接使用，saveColumnData保存列数据方法,参数传值(表格名称，当前表格的option数据)
             * 已定义全局方法，直接使用，getColumnName方法用来获取枚举值，参数根据自己定义的code值获取中文名
             * 一定要执行异步操作，要等接口成功返回，才能执行下一行代码
             */
            const inSave = await this.saveColumnData(this.getColumnName(code), this[option]);
            if (inSave) {
                this.$message.success("保存成功");
                //关闭窗口
                this.$refs[ref].$refs.dialogColumn.columnBox = false;
            }
        },
        //自定义列重置
        async resetColumnTwo(ref, option, optionBack, code) {
            this[option] = this[optionBack];
            const inSave = await this.delColumnData(this.getColumnName(code), this[optionBack]);
            if (inSave) {
                this.$message.success("重置成功");
                this.$refs[ref].$refs.dialogColumn.columnBox = false;
            }
        },
        backToList(type) {
            this.$emit("backToList", type);
        },
    },
    watch: {
        "form.planItemsList": {
            // 执行方法
            handler(Value, newValue) {
                this.form.goodsTotalNum = 0
                Value.forEach(item => {
                    this.form.goodsTotalNum += Number(item.goodsNum ? item.goodsNum : 0)
                })
            },
            deep: false, // 深度监听
            immediate: false  // 第一次改变就执行
        },
    }
}
</script>

<style lang="scss" scoped>
::v-deep .el-form-item {
    margin-bottom: 8px !important;
}

::v-deep .el-dialog__body {
    padding: 10px 20px;
}
</style>
