<template>
    <div>
        <el-card :body-style="cardBodyStyle">
            <el-form inline :model="query">
                <el-row style="margin-bottom: 5px;" :gutter="10">
                    <el-col :span="5">
                        <el-form-item label="订单号" style="margin-bottom: 0px; ">
                            <el-input v-model="query.purOrdNo" placeholder="" clearable style="width:100%; ">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="物料名称" style="margin-bottom: 0px; ">
                            <el-input v-model="query.itemNm" placeholder="" clearable style="width:100%; "></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="物料编码" style="margin-bottom: 0px; ">
                            <el-input v-model="query.itemCd" placeholder="" clearable style="width:100%; "></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="入库标记" style="margin-bottom: 0px; ">
                            <el-radio-group v-model="query.inFlag" @change="handleSearch">
                                <el-radio label="1">入库</el-radio>
                                <el-radio label="0">退库</el-radio>
                                <el-radio label="">全部</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-button type="primary" link @click="show">
                        高级查询
                        <el-icon v-if="showA">
                            <ArrowUp />
                        </el-icon>
                        <el-icon v-else>
                            <ArrowDown />
                        </el-icon>
                    </el-button>
                </el-row>
                <el-row v-if="showA">
                    <el-col :span="5">
                        <el-form-item label="供应商" style="margin-bottom: 0px; ">
                            <el-input v-model="query.tradePartnerName" placeholder="" clearable
                                style="width:100%; "></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="检化验号" style="margin-bottom: 0px; ">
                            <el-input v-model="query.syiNo" placeholder="" clearable style="width:100%; "></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <ButtonBar @search="handleSearch" @add="handleAdd" @handlePriceMatch="handlePriceMatch"
            @handleReturnLims="handleReturnLims" @handleReturnTms="handleReturnTms"></ButtonBar>

        <el-card :body-style="cardBodyStyle">
            <el-table :data="tableData" border highlight-current-row @selection-change="handleSelectionChange">
                <el-table-column type="selection" fixed></el-table-column>
                <el-table-column type="index" label="序号" align="center" width="60" fixed>
                    <template #default="scope">
                        <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
                    </template>
                </el-table-column>
                <el-table-column v-if="false" prop="compCd" label="公司代码" width="240" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="stoInNo" label="入库单号" width="150" header-align="center"
                    align="center" show-overflow-tooltip fixed>
                </el-table-column>
                <el-table-column v-if="true" prop="stoInDt" label="入库业务日期时间" width="180" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="itemCd" label="物料编码" width="150" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="itemNm" label="物料名称" width="100" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="false" prop="itemTy" label="物料类型" width="240" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="false" prop="specType" label="规格型号" width="240" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="tradePartnerCode" label="供应商编码" width="150" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="tradePartnerName" label="供应商名称" width="250" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="carNo" label="车号" width="120" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="qtyWet" label="数量（湿基）" width="120" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="moistureContent" label="水分含量" width="120" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="qty" label="数量（干基）" width="120" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="uom" label="单位" width="100" header-align="center" align="center"
                    show-overflow-tooltip :formatter="formatter">
                </el-table-column>
                <el-table-column v-if="true" prop="price" label="单价" width="120" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="taxPrice" label="含税单价" width="120" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="false" prop="account" label="结算量" width="120" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="actCnt" label="件数" width="120" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="storeCd" label="库房编码" width="120" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="storeNm" label="库房名称" width="120" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="areaCd" label="区位" width="120" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="stackCd" label="垛位" width="120" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="contrNo" label="合同编号" width="180" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="contrNoLine" label="合同行号" width="100" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="khContrNo" label="对方合同编号" width="200" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="purOrdNo" label="采购订单号" width="200" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="purOrdLn" label="采购订单行号" width="150" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="inFlag" label="入库标记" width="100" header-align="center" align="center"
                    show-overflow-tooltip :formatter="formatter">
                </el-table-column>
                <el-table-column v-if="true" prop="billYn" label="是否形成对账单" width="150" header-align="center"
                    align="center" show-overflow-tooltip :formatter="formatter">
                </el-table-column>
                <el-table-column v-if="true" prop="billNo" label="对账单单号" width="200" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="false" prop="tmsYn" label="是否出厂" width="100" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="false" prop="syiYn" label="是否检化验" width="100" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="tmsNo" label="物流计量业务单号" width="200" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="syiNo" label="检化验业务单号" width="200" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="remark" label="备注" width="200" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="addName" label="添加人名称" width="100" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="addDeptName" label="添加部门名称" width="120" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="addTime" label="添加时间" width="200" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="matchName" label="匹配人名称" width="100" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="matchTime" label="匹配时间" width="200" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="priceStartTime" label="价格执行时间" width="200" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="account" label="结算量" width="100" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <!---
                <el-table-column label="操作" header-align="center" align="center" width="200px" fixed="right">
                    <template #default="scope">
                        <el-button plain type="warning" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button plain type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column> -->
            </el-table>
        </el-card>

        <el-card :body-style="cardBodyStyle">
            <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes" :total="totalRows"
                background="background" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                @current-change="handleCurrentChange">
            </el-pagination>
        </el-card>

        <el-card :body-style="cardBodyStyle">
            <el-form label-position="right" label-width="120px" :inline="true">
                <el-form-item label="退库数量" style="margin-bottom: 0;">
                    <el-input v-model="returnQty" size="small" clearable style="width: 200px;"
                        :disabled="!(query.inFlag != '0')"></el-input>
                </el-form-item>
                <el-form-item style="margin-bottom: 0;">
                    <el-button plain type="danger" @click="handleStockReturn" size="small"
                        :disabled="!(query.inFlag != '0')">退库</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card :body-style="cardBodyStyle">
            <el-form :model="summary" label-position="right" label-width="120px" :inline="true">
                <el-row>
                    <el-form-item label="已选总重量">
                        <el-input v-model="summary.choseTtlQty" size="small" clearable style="width: 200px;"
                            disabled></el-input>
                    </el-form-item>
                    <el-form-item label="已选总件数">
                        <el-input v-model="summary.choseTtlCnt" size="small" clearable style="width: 200px;"
                            disabled></el-input>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="查询总重量">
                        <el-input v-model="summary.queryTtlQty" size="small" clearable style="width: 200px;"
                            disabled></el-input>
                    </el-form-item>
                    <el-form-item label="查询总件数">
                        <el-input v-model="summary.queryTtlCnt" size="small" clearable style="width: 200px;"
                            disabled></el-input>
                    </el-form-item>
                </el-row>
            </el-form>
        </el-card>

        <el-dialog :close-on-click-modal="false" draggable title="采购入库" v-model="dialogVisible" width="1200px" top="5vh"
            @open="openDialog" @close="handleCancelSave">
            <el-card :body-style="cardBodyStyle">
                <el-form :inline="true" :model="queryOrd" style="margin-bottom: 5px;" :gutter="10">
                    <el-row>
                        <el-col :span="5">
                            <el-form-item label="订单号" style="margin-bottom: 0px;">
                                <el-input v-model="queryOrd.purOrdNo" placeholder="" clearable style="width:100%;">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="物料名称" style="margin-bottom: 0px;">
                                <el-input v-model="queryOrd.itemNm" placeholder="" clearable
                                    style="width:100%;"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="物料编码" style="margin-bottom: 0px;">
                                <el-input v-model="queryOrd.itemCd" placeholder="" clearable
                                    style="width:100%;"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="供应商" style="margin-bottom: 0px;">
                                <el-input v-model="queryOrd.tradePartnerName" placeholder="" clearable
                                    style="width:100%;"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>

            <el-card :body-style="cardBodyStyle">
                <el-button plain type="primary" @click="handleSearchPurOrd">查询</el-button>
            </el-card>

            <el-card :body-style="cardBodyStyle">
                <el-table :data="tableDataOrd" border highlight-current-row v-loading="loadingOrd"
                    @selection-change="handleSelectionChangeOrd">
                    <el-table-column type="selection" fixed></el-table-column>
                    <el-table-column type="index" label="序号" align="center" width="60" fixed>
                        <template #default="scope">
                            <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="true" prop="purOrdNo" label="订单号" width="200" header-align="center"
                        align="center" show-overflow-tooltip fixed>
                    </el-table-column>
                    <el-table-column v-if="true" prop="purOrdLn" label="行号" width="100" header-align="center"
                        align="center" show-overflow-tooltip fixed>
                    </el-table-column>
                    <el-table-column v-if="true" prop="itemNm" label="物料名称" width="150" header-align="center"
                        align="center" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="qty" label="数量" width="100" header-align="center" align="right"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="false" prop="moistureContent" label="水分含量" width="100" header-align="center"
                        align="right" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="uom" label="单位" header-align="center" align="center" width="80"
                        show-overflow-tooltip :formatter="formatter">
                    </el-table-column>
                    <el-table-column v-if="true" prop="qtyUpper" label="上允差(%)" width="120" header-align="center"
                        align="center" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="qtyLower" label="下允差(%)" width="120" header-align="center"
                        align="center" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="price" label="单价" header-align="center" align="center"
                        width="120" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="taxPrice" label="含税单价" header-align="center" align="center"
                        width="120" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="delvDt" label="交货日期" header-align="center" align="center"
                        width="120" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="stoQty" label="入库数量" width="100" header-align="center"
                        align="center" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="tradePartnerName" label="供应商名称" width="180" header-align="center"
                        align="center" show-overflow-tooltip>
                    </el-table-column>
                </el-table>
            </el-card>

            <el-card :body-style="cardBodyStyle">
                <el-pagination :current-page="currentPageOrd" :page-size="pageSizeOrd" :page-sizes="pageSizesOrd"
                    :total="totalRowsOrd" background="background" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChangeOrd" @current-change="handleCurrentChangeOrd">
                </el-pagination>
            </el-card>

            <el-card :body-style="cardBodyStyle">
                <el-form :model="form" label-width="80px" label-position="right" inline ref="ruleFormRef"
                    :rules="rules">
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="入库日期" prop="stoInDt">
                                <el-date-picker v-model="form.stoInDt" type="date" value-format="YYYY-MM-DD"
                                    format="YYYY-MM-DD" style="width: 175px;"></el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="车号">
                                <el-input v-model="form.carNo" clearable style="width: 175px;"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="湿基">
                                <el-input-number v-model="form.qtyWet" :precision="2" :step="0.1" :min="0"
                                    controls-position="right" clearable style="width: 175px;"
                                    @change="updateQtyWet"></el-input-number>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="水分含量">
                                <el-input-number v-model="form.moistureContent" :precision="2" :step="0.1" :min="0"
                                    controls-position="right" clearable style="width: 175px;"
                                    @change="updateQtyMoistureContent"></el-input-number>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="干基" prop="qty">
                                <el-input-number v-model="form.qty" :precision="2" :step="0.1" :min="0.01"
                                    controls-position="right" clearable style="width: 175px;"
                                    @change="updateQty"></el-input-number>
                            </el-form-item>
                        </el-col>

                        <el-col :span="6">
                            <el-form-item label="件数">
                                <el-input-number v-model="form.cnt" :precision="2" :step="0.1" :min="0.01"
                                    controls-position="right" clearable style="width: 175px;"></el-input-number>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="库房" prop="storeCd">
                                <Popup_sto_config_kf_bx :store-nm="''" :key="keyTime" @receive-from-child="returnKf"
                                    style="width: 175px;">
                                </Popup_sto_config_kf_bx>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="区位">
                                <Popup_sto_config_Qh :kf-id="storeId" @receive-from-child="returnQh"
                                    style="width: 175px;">
                                </Popup_sto_config_Qh>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="垛位">
                                <Popup_sto_config_Dw :qh-id="areaId" @receive-from-child="returnDw"
                                    style="width: 175px;">
                                </Popup_sto_config_Dw>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="计量单号">
                                <el-input v-model="form.tmsNo" clearable style="width: 175px;"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="检验单号">
                                <el-input v-model="form.syiNo" clearable style="width: 175px;"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="处理时间">
                                <el-date-picker v-model="form.transactionDate" type="datetime"
                                    value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss"
                                    style="width: 175px;"></el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="备注">
                                <el-input type="textarea" v-model="form.remark" clearable
                                    style="width: 750px"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>

            <template #footer>
                <div class="dialog-footer">
                    <el-button plain type="success" @click="handleSave(ruleFormRef)" :loading="loading">入库</el-button>
                    <el-button plain type="danger" @click="handleCancelSave">取消</el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog :close-on-click-modal="false" draggable title="" v-model="dialogVisibleTms" width="500px" top="5vh"
            @open="openDialog">
            <el-form :model="formTms" label-width="110px" label-position="right" ref="ruleFormRefTms" :rules="rulesTms">
                <el-form-item label="采购订单号" prop="purOrdNo">
                    <el-input v-model="formTms.purOrdNo" clearable style="width: 200px" disabled></el-input>
                </el-form-item>
                <el-form-item label="采购订单行号" prop="purOrdLn">
                    <el-input v-model="formTms.purOrdLn" clearable style="width: 200px" readonly>
                        <template #append>
                            <el-button :icon="Search" @click="handleSearchOrdLine" />
                        </template>
                    </el-input>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="success" @click="handleSaveTms(ruleFormRefTms)" :loading="loading">保存</el-button>
                    <el-button type="danger" @click="handleCancelSave">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import ButtonBar from '@/components/ButtonBar.vue'
import Popup_sto_config_kf_bx from "@/views/sto/components/Popup_sto_config_kf_bx.vue"
import Popup_sto_config_Qh from "@/views/sto/components/Popup_sto_config_Qh.vue"
import Popup_sto_config_Dw from "@/views/sto/components/Popup_sto_config_Dw.vue"

import {
    ref,
    reactive,
    onMounted,
    getCurrentInstance
} from 'vue'
import { Search } from '@element-plus/icons-vue'

const {
    proxy
} = getCurrentInstance()

import tools from '@/tools'
const cardBodyStyle = ref(tools.style.card)
const inputStyle = ref(tools.style.input)

onMounted(() => {
    handleSearch()
    getDictList()
    getAllKF()
    getAllQH()
    getAllDWH()
})
import Attachment from '@/components/Attachment.vue'
import { ElMessage } from 'element-plus';
import { sum } from 'element-plus/es/components/table-v2/src/utils.mjs'

/**
 * 查询公司代码
 */
const userId = window.localStorage.getItem('userId')
const userCode = window.localStorage.getItem('userCode')
const userName = window.localStorage.getItem('userDesc')
const dept = JSON.parse(window.localStorage.getItem('dept'))
const deptTree = JSON.parse(window.localStorage.getItem('deptTree'))
/**
 * 查询公司代码
 */

/**
 *  查询字典
 */
const dicList = ref([])
const getDictList = () => {
    var url = 'framework/Common/querySelectorList'
    var param = {
        type: JSON.stringify(['MEASURING_UNIT'])
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            dicList.value = response.data.data
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}

const formatter = (row, column, cellValue, index) => {
    if (!cellValue || cellValue == null || cellValue == '') {
        return cellValue
    }
    switch (column.property) {
        case 'uom':
            cellValue = dicList.value.MEASURING_UNIT.find(item => item.dicCode == cellValue).dicName
            break
        case 'inFlag':
            cellValue = cellValue === '1' ? '入库' : '退库'
            break
        case 'billYn':
            cellValue = cellValue === '1' ? '是' : '否'
            break
    }
    return cellValue
}

const allKF = ref([])
const allQH = ref([])
const allDWH = ref([])
const getAllKF = (queryString, cb) => {
    var url = 'sto/Config/queryAllKF'
    var obj = {}
    var param = {
        params: JSON.stringify(obj),
    }
    proxy.$axios.get(url, param).then(response => {
        loading.value = false
        if (response.data.code == '0') {
            allKF.value = response.data.data.records
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}
const getAllQH = (queryString, cb) => {
    var url = 'sto/Config/queryAllQH'
    var obj = {}
    var param = {
        params: JSON.stringify(obj),
    }
    proxy.$axios.get(url, param).then(response => {
        loading.value = false
        if (response.data.code == '0') {
            allQH.value = response.data.data.records
        } else {
            ElMessage.error('操作失败！' + response.data.msg)

        }
    })

}
const getAllDWH = (queryString, cb) => {
    var url = 'sto/Config/queryAllDWH'
    var obj = {}
    var param = {
        params: JSON.stringify(obj),
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            allDWH.value = response.data.data.records
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
};

/**
 *  查询字典
 */

/**
 *   查询
 */
const query = ref({
    purOrdNo: '',
    itemCd: '',
    itemNm: '',
    tradePartnerName: '',
    syiNo: '',
    inFlag: '1',
})
const summary = ref({
    choseTtlQty: '',
    choseTtlCnt: '',
    queryTtlQty: '',
    queryTtlCnt: '',
})
const showA = ref(false)
const show = () => {
    showA.value = !showA.value
}
const tableData = ref([])
const handleSearch = () => {
    currentPage.value = 1
    getTableData()
    getTitleInfo()
    returnQty.value = ''
}
const getTableData = () => {
    var url = 'pur/StoInRecord/query'
    var param = {
        page: currentPage.value,
        rows: pageSize.value,
        params: JSON.stringify(query.value)
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            tableData.value = response.data.data.records
            totalRows.value = response.data.data.total
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}
const getTitleInfo = () => {
    var url = 'pur/StoInRecord/queryTitleInfo'
    var param = {
        page: currentPage.value,
        rows: pageSize.value,
        params: JSON.stringify(query.value)
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            summary.value.queryTtlQty = response.data.data.queryTtlQty
            summary.value.queryTtlCnt = response.data.data.queryTtlCnt
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}
/**
 *   查询
 */

/**
 * 分页
 */
const currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([5, 10, 20, 30, 40, 100, 500, 1000])
const pageSize = ref(5)
const handleSizeChange = (val) => {
    pageSize.value = val
    getTableData()
}
const handleCurrentChange = (val) => {
    currentPage.value = val
    getTableData()
}

/**
 * 新增
 */
const fId = ref('')
const AttachmentRefManual = ref(null)
const dialogVisible = ref(false)
const form = ref({
    carNo: '',
    qty: '',
    moistureContent: '',
    cnt: '',
    storeCd: '',
    storeNm: '',
    areaCd: '',
    stackCd: '',
    tmsNo: '',
    syiNo: '',
    remark: '',
    compCd: '',
    addId: '',
    addCode: '',
    addName: '',
    addDeptId: '',
    addDeptCode: '',
    addDeptName: '',
    addTime: '',
    modifyCode: '',
    modifyName: '',
})
const ruleFormRef = ref()
const rules = reactive({
    stoInDt: [{
        required: true,
        message: '请输入入库日期',
        trigger: 'change' | 'blur'
    }],
    carNo: [{
        required: true,
        message: '请输入车号',
        trigger: 'change' | 'blur'
    }],
    qtyWet: [{
        required: true,
        message: '请输入湿基',
        trigger: 'change' | 'blur'
    }],
    moistureContent: [{
        required: true,
        message: '请输入水分含量',
        trigger: 'change' | 'blur'
    }],
    qty: [{
        required: true,
        message: '请输入干基',
        trigger: 'change' | 'blur'
    }],
    storeCd: [{
        required: true,
        message: '请输入库房',
        trigger: 'change' | 'blur'
    }],
    areaCd: [{
        required: true,
        message: '请输入区位',
        trigger: 'change' | 'blur'
    }],
    stackCd: [{
        required: true,
        message: '请输入垛位',
        trigger: 'change' | 'blur'
    }],
    syiNo: [{
        required: true,
        message: '请输入检化验单号',
        trigger: 'change' | 'blur'
    }],
})

const tableDataOrd = ref([])
const loadingOrd = ref(false)

const handleAdd = () => {
    if (window.localStorage.getItem('deptTree') == JSON.stringify(new Array())) {
        ElMessage({
            type: 'warning',
            message: '请添加登录人所在公司'
        })
        return
    }

    form.value = {
        carNo: '',
        qty: null,
        moistureContent: null,
        qtyWet: null,
        cnt: null,
        storeCd: '',
        areaCd: '',
        stackCd: '',
        tmsNo: '',
        syiNo: '',
        remark: '',
        //transactionDate: getCurrentDateTime(),
        compCd: deptTree[0].deptCode,
        addId: userId,
        addCode: userCode,
        addName: userName,
        addDeptId: dept[0].id,
        addDeptCode: dept[0].deptCode,
        addDeptName: dept[0].deptName,
        addTime: '',
        modifyCode: '',
        modifyName: '',
    }

    queryOrd.value = {
        purOrdNo: '',
        itemNm: '',
        itemCd: '',
        tradePartnerName: '',
    }

    storeId.value = ''
    areaId.value = ''
    stackId.value = ''

    if (ruleFormRef.value) {
        ruleFormRef.value.resetFields()
    }

    dialogVisible.value = true
    getPurOrdLine()
}

const getCurrentDateTime = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const handlePriceMatch = () => {
    if (multipleSelection.value.length < 1) {
        ElMessage({
            type: 'warning',
            message: '请选择要匹配价格的数据!'
        })
        return
    }

    var url = 'pur/StoInRecord/priceMatch'
    var param = {
        json: JSON.stringify(multipleSelection.value)
    }
    proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
            ElMessage({
                type: 'success',
                message: '匹配成功！',
            })
            getTableData()
        } else {
            ElMessage({
                type: 'error',
                message: '匹配失败！' + response.data.msg
            });
        }
    });
}
const handleReturnLims = () => {
    if (multipleSelection.value.length != 1) {
        ElMessage({
            type: 'warning',
            message: '请选择一个要退回至检化验的检化验单号!'
        })
        return
    }

    if (multipleSelection.value[0].syiNo === '') {
        ElMessage({
            type: 'warning',
            message: '该入库信息上不存在检化验单号!'
        })
        return
    }

    const syiNo = multipleSelection.value[0].syiNo
    ElMessageBox.confirm(
        '确定将所有与检化验单号' + syiNo + '有关的采购入库记录退回至检化验?',
        '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
    }).then(() => {
        var url = 'pur/StoInRecord/returnLims'
        var param = {
            syiNo: multipleSelection.value[0].syiNo
        }
        proxy.$axios.post(url, param).then(response => {
            if (response.data.code == 0) {
                ElMessage({
                    type: 'success',
                    message: '退回成功！',
                })
                getTableData()
                getTitleInfo()
            } else {
                ElMessage({
                    type: 'error',
                    message: '退回失败！' + response.data.msg
                });
            }
        });
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消',
        })
    })
}
/**
 * 订单分页
 */
const currentPageOrd = ref(1)
const totalRowsOrd = ref(0)
const pageSizesOrd = ref([5, 10, 20, 30, 40])
const pageSizeOrd = ref(5)
const handleSizeChangeOrd = (val) => {
    pageSizeOrd.value = val
    getPurOrdLine()
}
const handleCurrentChangeOrd = (val) => {
    currentPageOrd.value = val
    getPurOrdLine()
}

const queryOrd = ref({
    purOrdNo: '',
    itemNm: '',
    itemCd: '',
    tradePartnerName: '',
})

const handleSearchPurOrd = () => {
    currentPageOrd.value = 1
    getPurOrdLine()
}

//查询生效的采购订单行信息
const getPurOrdLine = () => {
    var url = 'pur/OrdLine/queryPurOrdNoActive'
    loadingOrd.value = true
    var param = {
        page: currentPageOrd.value,
        rows: pageSizeOrd.value,
        params: JSON.stringify(queryOrd.value)
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            tableDataOrd.value = response.data.data.records
            totalRowsOrd.value = response.data.data.total
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    });
    loadingOrd.value = false
}
/**
 * 新增
 */


/**
 * 库房、区号、垛位
 */
const storeId = ref('')
const areaId = ref('')
const stackId = ref('')
const returnKf = (val) => {
    storeId.value = val.id
    form.value.storeCd = val.storeCd
    form.value.storeNm = val.storeNm
    areaId.value = val.areaId
    form.value.areaCd = val.areaCd
    stackId.value = val.stackId
    form.value.stackCd = val.stackCd
}

const returnQh = (val) => {
    areaId.value = val.id
    form.value.areaCd = val.areaCd
    stackId.value = val.stackId
    form.value.stackCd = val.stackCd
}

const returnDw = (val) => {
    stackId.value = val.id
    form.value.stackCd = val.stackCd
}
/**
 * 库房、区号、垛位
 */

/**
 * 保存、修改、删除
 */
const openDialog = () => {
}

const multipleSelectionOrd = ref([])
const handleSelectionChangeOrd = (val) => {
    multipleSelectionOrd.value = val
}

const updateQtyWet = (val) => {
    form.value.qtyWet = val
    form.value.qty = null
    calculateQty(form.value.qty, form.value.qtyWet, form.value.moistureContent)
}
const updateQtyMoistureContent = (val) => {
    form.value.moistureContent = val
    calculateQty(form.value.qty, form.value.qtyWet, form.value.moistureContent)
}
const updateQty = (val) => {
    form.value.qty = val
    form.value.qtyWet = null
    calculateQty(form.value.qty, form.value.qtyWet, form.value.moistureContent)
}

const calculateQty = (qty, qtyWet, moistureContent) => {
    if (qty != null) {
        if (moistureContent != null) {
            // 湿基 = 干基 / (1 - (水分 / 100))
            form.value.qtyWet = numberToFixed(qty / (1 - moistureContent / 100))
        } else {
            form.value.qtyWet = null
        }

    }

    if (qtyWet != null) {
        if (moistureContent != null) {
            // 干基 = 湿基 - (湿基 * (水分 / 100)) = 湿基 * (1 - (水分 / 100)
            form.value.qty = numberToFixed(qtyWet * (1 - moistureContent / 100))
        } else {
            form.value.qty = null
        }
    }
}


const keyTime = ref('')
const loading = ref(false)
const handleSave = (ruleFormRef) => {
    if (JSON.stringify(multipleSelectionOrd.value) === JSON.stringify(new Array())) {
        ElMessage({
            type: 'warning',
            message: '请先选择订单行！'
        })
        return
    }

    loading.value = true
    ruleFormRef.validate((valid, fields) => {
        if (valid) {
            var url = 'pur/StoInRecord/save'
            var param = {
                json: JSON.stringify(form.value),
                jsons: JSON.stringify(multipleSelectionOrd.value),
            }
            proxy.$axios.post(url, param).then(response => {
                if (response.data.code == 0) {
                    loading.value = false
                    ElMessage({
                        message: '保存成功',
                        type: 'success',
                    })
                    // form.value = response.data.data
                    // fId.value = form.value.id
                    // AttachmentRefManual.value.upload()

                    // keyTime.value = new Date().getTime()
                    getTableData()
                    getTitleInfo()
                    getPurOrdLine()
                } else {
                    loading.value = false
                    ElMessage({
                        message: '操作失败' + response.data.msg,
                        type: 'error'
                    })
                    getTableData()
                    getTitleInfo()
                    getPurOrdLine()
                }
            })

        } else {
            loading.value = false
            console.log('error submit!', fields)
        }
    })
}
const handleCancelSave = () => {
    dialogVisible.value = false
    dialogVisibleTms.value = false
    keyTime.value = new Date().getTime()
}
const handleEdit = (row) => {
    form.value = { ...row }
    form.value.modifyCode = userCode
    form.value.modifyName = userName
    fId.value = row.id
    dialogVisible.value = true
}
const handleDelete = (row) => {
    row.cancelName = userName

    ElMessageBox.confirm(
        '确定删除本条记录?',
        '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
    }).then(() => {
        var url = 'pur/StoInRecord/remove'
        var param = {
            id: row.id
        }
        proxy.$axios.post(url, param).then(response => {
            if (response.data.code == 0) {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
                getTableData()
                getTitleInfo()
            } else {
                ElMessage({
                    type: 'error',
                    message: '删除失败' + response.data.msg
                });
            }
        });
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消',
        })
    })
}

/**
 * 保存、修改、删除
 */
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
    multipleSelection.value = val
    summary.value.choseTtlCnt = numberToFixed(multipleSelection.value.reduce((sum, current) => {
        if (query.inFlag === '0') {
            return sum + current.cnt
        } else {
            return sum + (current.inFlag === '1' ? current.cnt : -current.cnt)
        }
    }, 0))
    summary.value.choseTtlQty = numberToFixed(multipleSelection.value.reduce((sum, current) => {
        if (query.value.inFlag === '0') {
            return sum + current.qtyWet
        } else {
            return sum + (current.inFlag === '1' ? current.qtyWet : -current.qtyWet)
        }
    }, 0))
}
const numberToFixed = (data) => {
    var value = Math.round(parseFloat(data) * 100) / 100;
    var d = value.toString().split(".");
    if (d.length == 1) {
        value = value.toString() + ".00";
        return value;
    }
    if (d.length > 1) {
        if (d[1].length < 2) {
            console.log(d[1])
            value = value.toString() + "0";
        }
        return value;
    }
}

const returnQty = ref('')
const handleStockReturn = () => {
    if (multipleSelection.value.length < 1) {
        ElMessage({
            type: 'warning',
            message: '请选择要退库的数据!'
        })
        return
    }

    const flag1 = multipleSelection.value.find(item => item.stoInNo.startsWith("TK"))
    if (flag1) {

        ElMessage({
            type: 'warning',
            message: '请勿重复退库！'
        })
        return
    }
    const flag2 = multipleSelection.value.filter(item => item.billYn === '1')
    if (flag2.length > 0) {
        ElMessage({
            type: 'warning',
            message: '入库单号' + flag2.map(item => item.stoInNo).join('、') + '已形成采购对账单，取消对账单后再进行退库操作！'
        })
        return
    }

    const flag3 = multipleSelection.value.filter(item => item.qty - (item.returnQh != '' ? 0 : item.returnQh) - returnQty.value < 0)
    if (flag3.length > 0) {
        ElMessage({
            type: 'warning',
            message: '入库单号' + flag3.map(item => item.stoInNo).join('、') + '的入库数量少于累计退库数量！'
        })
        return
    }


    var url = 'pur/StoInRecord/stockReturn'
    var param = {
        json: JSON.stringify(multipleSelection.value),
        json1: returnQty.value
    }
    proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
            ElMessage({
                message: '保存成功',
                type: 'success',
            })
            form.value = response.data.data
            getTableData()
            getTitleInfo()
        } else {
            ElMessage({
                message: '操作失败' + response.data.msg,
                type: 'error'
            })
        }
    })
}

const dialogVisibleTms = ref(false)
const formTms = ref({
    purOrdNo: '',
    purOrdLn: '',
})
const ruleFormRefTms = ref()
const rulesTms = reactive({
    purOrdNo: [{
        required: true,
        message: '请输入采购订单号',
        trigger: 'change' | 'blur'
    }],
    purOrdLn: [{
        required: true,
        message: '请输入采购订单行号',
        trigger: 'change' | 'blur'
    }],
})
const handleReturnTms = () => {
    if (multipleSelection.value.length < 1) {
        ElMessage({
            type: 'warning',
            message: '请选择要修改的数据!'
        })
        return
    }

    const purOrdNo = multipleSelection.value[0].purOrdNo
    const purOrdLn = multipleSelection.value[0].purOrdLn

    const flag = multipleSelection.value.find(item => item.purOrdNo != purOrdNo || item.purOrdLn != purOrdLn)
    if (flag) {
        ElMessage({
            type: 'warning',
            message: '所选数据的订单号和订单行号必须一致!'
        })
        return
    }

    const flag1 = multipleSelection.value.filter(item => item.billYn === '1')
    if (flag1.length > 0) {
        ElMessage({
            type: 'warning',
            message: '入库单号' + flag1.map(item => item.stoInNo).join('、') + '已生成采购对账单，请先取消采购对账单'
        })
        return
    }

    if (ruleFormRefTms.value) {
        ruleFormRefTms.value.resetFields()
    }

    dialogVisibleTms.value = true
}
const handleSaveTms = (ruleFormRefTms) => {
    ruleFormRefTms.validate((valid, fields) => {
        if (valid) {
            ElMessageBox.confirm(
                '确定更改所选数据的采购订单号及采购订单行号?',
                '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                draggable: true,
            }).then(() => {
                var url = 'pur/StoInRecord/returnTms'
                var param = {
                    json: multipleSelection.value,
                    json1: formTms.value
                }
                proxy.$axios.post(url, param).then(response => {
                    if (response.data.code == 0) {
                        ElMessage({
                            type: 'success',
                            message: '退回成功！',
                        })
                        getTableData()
                        getTitleInfo()
                    } else {
                        ElMessage({
                            type: 'error',
                            message: '退回失败！' + response.data.msg
                        });
                    }
                });
            }).catch(() => {
                ElMessage({
                    type: 'info',
                    message: '已取消',
                })
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const PopupRefOrdLine = ref(null)
const handleSearchOrdLine = () => {
    PopupRefOrdLine.value.open()
}
const retuOrdLine = (val) => {
    formTms.value.purOrdNo = val.purOrdNo
    formTms.purOrdLn = val.purOrdLn
}
</script>

<style></style>