<template>
    <div>
        <el-card :body-style="cardBodyStyle">
            <el-form :inline="true" :model="query">
                <el-row style="margin-bottom: 5px;">
                    <el-col :span="5">
                        <el-form-item label="合同号" style="margin-bottom: 0;">
                            <el-input v-model="query.contrNo" placeholder="" clearable>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="对方合同号" style="margin-bottom: 0;">
                            <el-input v-model="query.khContrNo" placeholder="" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="订单号" style="margin-bottom: 0;">
                            <el-input v-model="query.purOrdNo" placeholder="" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="供应商" style="margin-bottom: 0;">
                            <el-input v-model="query.tradePartnerName" placeholder="" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <ButtonBar @search="handleSearch" @add="handleAdd" @closeOrdHead="closeOrdHead" @openOrdHead="openOrdHead">
        </ButtonBar>

        <el-card :body-style="cardBodyStyle">
            <el-tabs v-model="activeNameTop" type="border-card">
                <el-tab-pane label="采购订单头" name="master">
                    <el-table :data="tableData" border highlight-current-row @selection-change="handleSelectionChange"
                        v-loading="loading" @row-click="DoubleClick">
                        <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="purOrdSts" label="订单状态" width="100" header-align="center"
                            align="center" show-overflow-tooltip fixed>
                            <template #default="{ row }">
                                {{ dicList.PUR_ORD_STS.find(item => item.dicCode === row.purOrdSts)?.dicName }}
                            </template>
                        </el-table-column>
                        <el-table-column v-if="false" prop="compCd" label="公司名称" width="120" 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 fixed>
                        </el-table-column>
                        <el-table-column v-if="true" prop="contrNm" label="合同名称" width="150" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="contrNo" label="合同编码" width="150" 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-column v-if="true" prop="khContrNo" label="对方合同号" width="150" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="remark" label="备注" width="150" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="addName" label="录入人" width="150" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="addTime" label="录入日期" width="120" header-align="center"
                            align="center" show-overflow-tooltip :formatter="formatter">
                        </el-table-column>
                        <el-table-column label="操作" header-align="center" align="center" width="200" fixed="right">
                            <template #default="{ row }">
                                <el-button plain type="warning" @click="handleEdit(row)"
                                    style="margin-right: 12px;">编辑</el-button>
                                <span v-if="!(row.purOrdSts == 'B' || row.purOrdSts == 'C')">
                                    <el-button plain type="danger" @click="handleDelete(row)">删除</el-button>
                                </span>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </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-tabs v-model="activeNameBottom" type="border-card">
                <el-tab-pane label="采购订单行" name="first">
                    <el-table :data="tableDataLine" @cell-dblclick="tableEdit" border highlight-current-row
                        v-loading="loadingLine">
                        <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="purOrdSts" label="订单状态" width="100" header-align="center"
                            align="center" show-overflow-tooltip fixed>
                            <template #default="{ row }">
                                {{ dicList.PUR_ORD_STS.find(item => item.dicCode === row.purOrdSts)?.dicName }}
                            </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="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="true" prop="qty" label="数量" width="100" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="uom" label="单位" header-align="center" align="center"
                            width="100" show-overflow-tooltip :formatter="formatter">
                        </el-table-column>
                        <el-table-column v-if="true" prop="qtyUpper" label="上允差(%)" width="100" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="qtyLower" label="下允差(%)" width="100" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="taxPrice" label="含税单价" header-align="center" align="center"
                            width="100" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="totalAmount" label="含税金额" header-align="center"
                            align="center" width="100" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="price" label="单价" header-align="center" align="center"
                            width="100" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="amount" label="金额" header-align="center" align="center"
                            width="100" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="taxRate" label="税率" header-align="center" align="center"
                            width="100" show-overflow-tooltip :formatter="formatter">
                        </el-table-column>
                        <el-table-column v-if="true" prop="taxAmount" label="税额" header-align="center" align="center"
                            width="100" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="delvDt" label="交货日期" header-align="center" align="center"
                            width="180" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="blno" label="提单号" header-align="center" align="center"
                            width="200" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="stoQty" label="入库数量" header-align="center" align="center" 
                            width="100" show-overflow-tooltip>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!-- <el-card :body-style="cardBodyStyle">
            <el-pagination :current-page="currentPageLine" :page-size="pageSizeLine" :page-sizes="pageSizesLine" :total="totalRowsLine"
                background="background" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChangeLine"
                @current-change="handleCurrentChangeLine">
            </el-pagination>
        </el-card> -->

        <el-dialog fullscreen class="diaClass" :close-on-click-modal="false" draggable :title="title"
            v-model="dialogVisible" @open="openDialog" @close="handleCancelSave">
            <el-card class="box-card">
                <el-form :model="form" label-width="110px" label-position="right" inline ref="ruleFormRef"
                    :rules="rules" style="margin-top: 10px;">
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="订单号">
                                <el-input v-model="form.purOrdNo" clearable disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="合同名称">
                                <el-input v-model="form.contrNm" clearable disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="合同号" prop="contrNo">
                                <el-input v-model="form.contrNo" clearable readonly>
                                    <template #append v-if="!readonly">
                                        <el-button :icon="Search" @click="handleSearchCotHead" />
                                    </template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="合同日期">
                                <el-date-picker v-model="form.contrDt" type="date" style="width: 100%"
                                    :readonly="readonly"></el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="交货日期" prop="delvDt">
                                <el-date-picker v-model="form.delvDt" type="date" style="width: 100%"
                                    :readonly="readonly"></el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="供应商" prop="tradePartnerName">
                                <el-input v-model="form.tradePartnerName" clearable disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="供应商编码" prop="tradePartnerCode">
                                <el-input v-model="form.tradePartnerCode" clearable disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="采购部门" prop="deptNm">
                                <el-input v-model="form.deptNm" clearable disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="部门编码" prop="deptCd">
                                <el-input v-model="form.deptCd" clearable disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="采购人员">
                                <el-input v-model="form.checkName" clearable disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="交货方式">
                                <el-select v-model="form.delvMth" placeholder="请选择" :disabled="readonly">
                                    <el-option v-for="item in dicList.DELV_MTH" :key="item.dicCode"
                                        :label="item.dicName" :value="item.dicCode" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="运输方式">
                                <el-select v-model="form.trsMth" placeholder="请选择" :disabled="readonly">
                                    <el-option v-for="item in dicList.TMS_FTRANTYPE" :key="item.dicCode"
                                        :label="item.dicName" :value="item.dicCode" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="结算方式">
                                <el-select v-model="form.invMth" placeholder="请选择" :disabled="readonly">
                                    <el-option v-for="item in dicList.SAL_INV_MTH" :key="item.dicCode"
                                        :label="item.dicName" :value="item.dicCode" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="付款方式">
                                <el-select v-model="form.payMth" placeholder="请选择" :disabled="readonly">
                                    <el-option v-for="item in dicList.COM_PAY_MTH" :key="item.dicCode"
                                        :label="item.dicName" :value="item.dicCode" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="对方合同号">
                                <el-input v-model="form.khContrNo" clearable :readonly="readonly"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="备注">
                                <el-input v-model="form.remark" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
                                    placeholder="" :readonly="readonly"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="数量合计">
                                <el-input v-model="form.qty" clearable disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="金额合计">
                                <el-input v-model="form.sumAmount" clearable disabled></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>

            <el-card class="box-card" v-show="true" style="margin-top: 10px;">
                <template #header>
                    <el-button type="success" plain @click="handleSaveBatchLine">新增</el-button>
                    <el-button type="primary" plain @click="lineConfirm">确认</el-button>
                    <!-- <el-button type="warning" plain @click="lineVoid">作废</el-button> -->
                </template>
                <el-table :data="tableDataLine" @cell-dblclick="tableEditLine" border highlight-current-row
                    @selection-change="handleSelectionChangeLine" ref="tableDataLineRef" @select-all="selectAllLine">
                    <el-table-column type="selection" fixed :selectable="selectableLine"></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="purOrdSts" label="订单状态" width="100" header-align="center"
                        align="center" show-overflow-tooltip fixed>
                        <template #default="{ row }">
                            {{ dicList.PUR_ORD_STS.find(item => item.dicCode === row.purOrdSts)?.dicName }}
                        </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="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="true" prop="qty" label="数量" width="100" header-align="center" align="center"
                        show-overflow-tooltip>
                        <template #default="{ row }">
                            <span v-if="row.cancelFlag == 1 && (row.purOrdLn == '' || row.purOrdSts == 'A')">
                                <el-input v-model="row.qty" oninput="value=value.replace(/[^0-9.]/g,'')"
                                    @input="calculatePrice(row)">
                                </el-input>
                            </span>
                            <span v-else>{{ row.qty }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="true" prop="uom" label="单位" header-align="center" align="center" width="100"
                        show-overflow-tooltip :formatter="formatter">
                    </el-table-column>
                    <el-table-column v-if="true" prop="qtyUpper" label="上允差(%)" width="100" header-align="center"
                        align="center" show-overflow-tooltip>
                        <template #default="{ row }">
                            <span v-if="row.cancelFlag == 1">
                                <el-input v-model="row.qtyUpper" oninput="value=value.replace(/[^0-9.]/g,'')">
                                </el-input>
                            </span>
                            <span v-else>{{ row.qtyUpper }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="true" prop="qtyLower" label="下允差(%)" width="100" header-align="center"
                        align="center" show-overflow-tooltip>
                        <template #default="{ row }">
                            <span v-if="row.cancelFlag == 1">
                                <el-input v-model="row.qtyLower" oninput="value=value.replace(/[^0-9.]/g,'')">
                                </el-input>
                            </span>
                            <span v-else>{{ row.qtyLower }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="true" prop="taxPrice" label="含税单价" header-align="center" align="center"
                        width="100" show-overflow-tooltip>
                        <template #default="{ row }">
                            <span v-if="row.cancelFlag == 1">
                                <el-input v-model="row.taxPrice" oninput="value=value.replace(/[^0-9.]/g,'')"
                                    @input="calculatePrice(row)">
                                </el-input>
                            </span>
                            <span v-else>{{ row.taxPrice }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="true" prop="totalAmount" label="含税金额" header-align="center" align="center"
                        width="100" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="price" label="不含税单价" header-align="center" align="center"
                        width="100" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="amount" label="不含税金额" header-align="center" align="center"
                        width="100" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="taxRate" label="税率" header-align="center" align="center"
                        width="120" show-overflow-tooltip :formatter="formatter">
                    </el-table-column>
                    <el-table-column v-if="true" prop="taxAmount" label="税额" header-align="center" align="center"
                        width="100" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="delvDt" label="交货日期" header-align="center" align="center"
                        width="180" show-overflow-tooltip>
                        <template #default="{ row }">
                            <span v-if="row.cancelFlag == 1">
                                <el-date-picker v-model="row.delvDt" style="width: 130px;" align="right" type="date"
                                    placeholder="交货日期" :picker-options="pickerOptions">
                                </el-date-picker>
                            </span>
                            <span v-else>{{ row.delvDt }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="true" prop="blno" label="提单号" header-align="center" align="center"
                        width="200" show-overflow-tooltip>
                        <template #default="{ row }">
                            <span v-if="row.cancelFlag == 1">
                                <el-input v-model="row.blno" />
                            </span>
                            <span v-else>{{ row.blno }}</span>
                        </template>
                    </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 label="操作" header-align="center" align="center" width="200" fixed="right">
                        <template #default="{ row }">
                            <span v-if="row.cancelFlag == 1">
                                <el-button v-prevent-re-click plain type="primary"
                                    @click="handleSaveLine(row)">保存</el-button>
                                <el-button v-prevent-re-click plain type="success"
                                    @click="handleCancelSaveLine(row)">取消</el-button>
                            </span>
                            <span v-if="row.purOrdSts == 'A' && row.cancelFlag == 0">
                                <el-button plain type="warning" @click="handleEditLine(row)"
                                    style="margin-right: 12px;">编辑</el-button>
                            </span>
                            <span v-if="!(row.purOrdSts == 'B' || row.purOrdSts == 'D') && row.cancelFlag == 0">
                                <el-button plain type="danger" @click="handleDeleteLine(row)">删除</el-button>
                            </span>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="success" plain @click="handleSave(ruleFormRef)" v-if="!readonly">保存</el-button>
                    <el-button type="danger" plain @click="handleCancelSave">取消</el-button>
                    <!-- <el-button type="info" plain @click="handleCancelSave">关闭</el-button> -->
                </div>
            </template>
        </el-dialog>

        <PopupCot ref="PopupRefCot" @receive-from-child="retuCot" :params="paramsCot"></PopupCot>
        
        <el-dialog :close-on-click-modal="false" draggable v-model="dialogVisibleOrdPrice" @open="openDialog">
            <el-form :inline="true" :model="formPrice" label-position="right" label-width="100px" ref="ruleFormRefPrice"
                :rules="rulesPrice" style="margin-top: 10px;">
                <el-col :span="8">
                    <el-form-item label="执行时间" prop="priceStartTime">
                        <el-date-picker type="datetime" v-model="formPrice.priceStartTime" clearable></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="success" plain @click="saveLineConfirm" v-if="ordPriceButton">保存</el-button>
                    <el-button type="success" plain @click="saveOrdHeadOpen" v-if="!ordPriceButton">保存</el-button>
                    <el-button type="danger" plain @click="handleCancelLineConfirm">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import ButtonBar from '@/components/ButtonBar.vue'
import PopupCot from '@/views/cot/components/PopupCot.vue'

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

const {
    proxy
} = getCurrentInstance()

import tools from '@/tools'
import { ElMessage } from 'element-plus';
import { stringify } from 'qs'
const cardBodyStyle = ref(tools.style.card)
const inputStyle = ref(tools.style.input)

onMounted(() => {
    getDictList()
    handleSearch()
})


/**
 * 查询公司代码
 */
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 query = ref({
    contrNo: '',
    khContrNo: '',
    purOrdNo: '',
    tradePartnerName: '',
})

const activeNameTop = ref('master')
const tableData = ref([])

const handleSearch = () => {
    tableDataLine.value = []
    currentPage.value = 1
    getTableData()
}

const getTableData = () => {
    var url = 'pur/OrdHead/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 currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([5, 10, 20, 30, 40])
const pageSize = ref(5)
const handleSizeChange = (val) => {
    pageSize.value = val
    getTableData()
}
const handleCurrentChange = (val) => {
    currentPage.value = val
    getTableData()
}
/**
 * 分页
 */


/**
 * 新增
 */
const title = ref('')
const readonly = ref(false)
const dialogVisible = ref(false)
const form = ref({
    purOrdNo: '',
    purOrdSts: '',
    compCd: '',
    contrId: '',
    contrNo: '',
    contrNm: '',
    tradePartnerCode: '',
    tradePartnerName: '',
    deptCd: '',
    deptNm: '',
    contrDt: '',
    payMth: '',
    delvMth: '',
    delvDt: '',
    trsMth: '',
    invMth: '',
    fromPlace: '',
    remark: '',
    qty: '',
    uom: '',
    khContrNo: '',
    taxRate: '',
    cotLines: [],
    addId: '',
    addCode: '',
    addName: '',
    addDeptId: '',
    addDeptCode: '',
    addDeptName: '',
    addTime: '',
    modifyCode: '',
    modifyName: '',
})
const ruleFormRef = ref()
const rules = reactive({
    contrNo: [{
        required: true,
        message: '请输入合同编码',
        trigger: 'change' | 'blur'
    }],
    tradePartnerCode: [{
        required: true,
        message: '请输入供应商编码',
        trigger: 'change' | 'blur'
    }],
    tradePartnerName: [{
        required: true,
        message: '请输入供应商名称',
        trigger: 'change' | 'blur'
    }],
    deptCd: [{
        required: true,
        message: '请输入采购部门编码',
        trigger: 'change' | 'blur'
    }],
    deptNm: [{
        required: true,
        message: '请输入采购部门',
        trigger: 'change' | 'blur'
    }],
    delvDt: [{
        required: true,
        message: '请输入交货日期',
        trigger: 'change' | 'blur'
    }],
})

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

    form.value = {
        purOrdNo: '',
        controId: '',
        contrNo: '',
        contrNm: '',
        contrDt: '',
        khContrNo: '',
        tradePartnerCode: '',
        tradePartnerName: '',
        compCd: deptTree[0].deptCode,
        deptCd: dept[0].deptCode,
        deptNm: dept[0].deptName,
        checkName: window.localStorage.getItem('userDesc'),
        payMth: '',
        delvMth: '',
        delvDt: '',
        trsMth: '',
        invMth: '',
        fromPlace: '',
        remark: '',
        qty: '',
        uom: '',
        addId: userId,
        addCode: userCode,
        addName: userName,
        addDeptId: dept[0].id,
        addDeptCode: dept[0].deptCode,
        addDeptName: dept[0].deptName,
        addTime: '',
        modifyCode: '',
        modifyName: '',
    }
    tableDataLine.value = []

    if (ruleFormRef.value) {
        ruleFormRef.value.resetFields();
    }
    title.value = '新增'
    readonly.value = false
    dialogVisible.value = true
}
/**
 * 新增
 */


/**
 * 保存、修改、删除
 */
const openDialog = () => {
}
const handleSave = (ruleFormRef) => {
    ruleFormRef.validate((valid, fields) => {
        if (valid) {
            var url = 'pur/OrdHead/save'
            var param = {
                json: JSON.stringify(form.value),
            }
            proxy.$axios.post(url, param).then(response => {
                if (response.data.code == 0) {
                    ElMessage({
                        message: '保存成功',
                        type: 'success',
                    })
                    form.value = response.data.data
                    getTableDataLine(form.value.purOrdNo)
                    getTableData()
                } else {
                    // ElMessage.error('操作失败！' + response.data.msg)
                    ElMessage({
                        message: '操作失败' + response.data.msg,
                        type: 'error'
                    })
                }
            })

        } else {
            console.log('error submit!', fields)
        }
    })
}
const handleCancelSave = () => {
    dialogVisible.value = false
}
const handleEdit = (row) => {
    if (ruleFormRef.value) {
        ruleFormRef.value.resetFields();
    }
    title.value = '编辑'
    form.value = { ...row }
    form.value.modifyCode = userCode
    form.value.modifyName = userName
    readonly.value = form.value.purOrdSts === 'B' || form.value.purOrdSts == 'C'
    dialogVisible.value = true
}
const handleDelete = (row) => {
    ElMessageBox.confirm(
        '确定删除本条记录?',
        '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
    }).then(() => {
        var url = 'pur/OrdHead/remove'
        var param = {
            id: row.id
        }
        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
                });
            }
        });
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消',
        })
    })
}
/**
 * 保存、修改、删除
 */


/**
 * 订单关闭、订单打开
 */
const multipleSelection = ref([])

const handleSelectionChange = (val) => {
    multipleSelection.value = val
}

const closeOrdHead = () => {
    if (multipleSelection.value.length == 0) {
        ElMessageBox.confirm(
            '请选择采购订单头信息?',
            '提示', {
            confirmButtonText: '确认',
        })

        return
    }

    const flag = multipleSelection.value.find(item => item.purOrdSts === 'C')
    if (flag != null) {
        ElMessage({
            type: 'warning',
            message: '存在已关闭订单!'
        })
        return
    }

    var url = 'pur/OrdHead/headClose'
    var json = JSON.stringify(multipleSelection.value)
    var param = {
        json: json,
    }
    proxy.$axios.post(url, param).then(response => {
        if (response.data.code === 0) {
            ElMessage({
                type: 'success',
                message: '订单关闭成功!',
            });
            multipleSelection.value = response.data.data
            getTableData()
            getTableDataLine(formLine.value.purOrdNo)
        } else {
            ElMessage({
                type: 'error',
                message: '订单关闭失败' + response.data.msg
            })
        }
    })
}
const openOrdHead = () => {
    if (multipleSelection.value.length == 0) {
        ElMessageBox.confirm(
            '请选择采购订单头信息?',
            '提示', {
            confirmButtonText: '确认',
        })

        return
    }

    const flag = multipleSelection.value.find(item => item.purOrdSts === 'B')
    if (flag != null) {
        ElMessage({
            type: 'warning',
            message: '存在已打开订单!'
        })
        return
    }

    formPrice.value = {
        purOrdHeadId: '',
        purOrdNo: '',
        purOrdLn: '',
        itemId: '',
        itemCd: '',
        itemNm: '',
        wetQty: '',
        qty: '',
        uom: '',
        price: '',
        taxPrice: '',
        amount: '',
        taxAmount: '',
        totalAmount: '',
        contrNo: '',
        contrNoLine: '',
        khContrNo: '',
        tradePartnerCode: '',
        tradePartnerName: '',
        priceStartTime: null,
        priceSts: '',
        addId: '',
        addCode: '',
        addName: '',
        addDeptId: '',
        addDeptCode: '',
        addDeptName: '',
        addTime: '',
    }

    if (ruleFormRefPrice.value) {
        ruleFormRefPrice.value.resetFields();
    }

    ordPriceButton.value = false
    dialogVisibleOrdPrice.value = true
}

const saveOrdHeadOpen = () => {
    formPrice.value.addId = userId
    formPrice.value.addCode = userCode
    formPrice.value.addName = userName
    formPrice.value.addDeptId = dept[0].id
    formPrice.value.addDeptCode = dept[0].deptCode
    formPrice.value.addDeptName = dept[0].deptName

    var url = 'pur/OrdHead/headOpen'
    var param = {
        json: JSON.stringify(multipleSelection.value),
        json1: JSON.stringify(formPrice.value),
    }
    proxy.$axios.post(url, param).then(response => {
        if (response.data.code === 0) {
            if (response.data.data != '') {
                ElMessage({
                    message: response.data.data,
                    type: 'error'
                })
            } else {
                ElMessage({
                    type: 'success',
                    message: '订单打开成功!',
                });
            }
            getTableData()
            getTableDataLine(formLine.value.purOrdNo)
            dialogVisibleOrdPrice.value = false
        } else {
            ElMessage({
                type: 'error',
                message: '订单打开失败' + response.data.msg
            })
        }
    })

}
/**
 * 订单关闭、订单打开
 */


const selectableLine = (row, index) => {
    if (JSON.stringify(multipleSelectionLine.value) === JSON.stringify(new Array()) || (multipleSelectionLine.value.includes(row))) {
        return row
    }
}
const tableDataLineRef = ref(null)
const selectAllLine = () => {
    tableDataLineRef.value.clearSelection()
    return false
}


/**
 *   查询 —— 采购订单行
 */
const activeNameBottom = ref('first')
const tableDataLine = ref([])
const loadingLine = ref(false)

const DoubleClick = (row) => {
    formLine.value = { ...row }
    getTableDataLine(row.purOrdNo)
}

const getTableDataLine = (purOrdNo) => {
    loadingLine.value = true
    var url = 'pur/OrdLine/queryPurOrdNo'
    var param = {
        purOrdNo: purOrdNo
    }
    proxy.$axios.get(url, param).then(response => {
        tableDataLine.value = response.data.data
        form.value.sumAmount = tableDataLine.value
            // .filter(item => item.purOrdLn && !item.purOrdLn.includes('_'))
            .filter(item => item.purOrdSts === 'B')
            .reduce((sum, current) => sum + current.totalAmount, 0)

        form.value.qty = tableDataLine.value
            // .filter(item => item.purOrdLn && !item.purOrdLn.includes('_'))
            .filter(item => item.purOrdSts === 'B')
            .reduce((sum, current) => sum + current.qty, 0)
    })
    loadingLine.value = false
}
/**
 *   查询
 */


/**
 * 新增
 */
const dialogVisibleLine = ref(false)
const formLine = ref({})
const ruleFormRefLine = ref()
const rulesLine = reactive({
})
/**
 * 新增
 */


/**
 * 价格计算
 */
// 通过含税单价计算不含税单价、含税金额、不含税金额
const calculatePrice = (row) => {

    // 不含税单价 = 含税单价 / (1 + 税率)
    row.price = numberToFixed(row.taxPrice / (Number(1) + (Number(row.taxRate) / 100)));

    // 含税金额 = 含税单价 * 数量
    row.totalAmount = numberToFixed(row.taxPrice * Number(row.qty));

    // 不含税金额 = 不含税单价 * 数量
    row.amount = numberToFixed(row.price * Number(row.qty));

    // 税额 = 含税金额 - 不含税金额
    row.taxAmount = numberToFixed(row.totalAmount - Number(row.amount));
}

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 openDialogLine = () => {
}
const handleSaveLine = (row) => {
    row.cancelFlag = 0

    var url = 'pur/OrdLine/save'
    var param = {
        json: JSON.stringify(row),
    }
    proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
            formLine.value = response.data.data
            ElMessage({
                message: '保存成功',
                type: 'success',
            })
            dialogVisibleLine.value = false
            getTableDataLine(form.value.purOrdNo)
        } else {
            // ElMessage.error('操作失败！' + response.data.msg)
            ElMessage({
                message: '操作失败' + response.data.msg,
                type: 'error'
            })
        }
    })
}

const handleCancelSaveLine = (row) => {
    // dialogVisibleLine.value = false
    row.cancelFlag = 0
    getTableDataLine(form.value.purOrdNo)
}
const handleEditLine = (row) => {
    // dialogVisibleLine.value = true
    if (row.purOrdLn.includes('_')) {
        ElMessage.warning("该订单行不能编辑")
        return
    }


    for (let i of tableDataLine.value) {
        if (i.cancelFlag === 1) {
            ElMessage.warning("请保存当前编辑")
            return false;
        }
    }
    row.cancelFlag = 1
    row.modifyCode = userCode
    row.modifyName = userName
}

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


/**
 * 新增、确认、作废
 */
const multipleSelectionLine = ref([])

const handleSelectionChangeLine = (val) => {
    multipleSelectionLine.value = val
}

const handleSaveBatchLine = () => {
    if (multipleSelectionLine.value.length !== 1) {
        ElMessage({
            type: 'warning',
            message: '请选择一条要新增的数据!'
        })
        return
    }

    // const flag = multipleSelectionLine.value.find(item => item.purOrdSts !== 'B' || !item.purOrdLn || item.purOrdLn.includes('_'))
    const flag = multipleSelectionLine.value.find(item => item.purOrdSts !== 'B' || item.purOrdLn.includes('_'))
    if (flag != null) {
        ElMessage({
            type: 'warning',
            message: '订单行只有是确认状态才可以新增!'
        })
        return
    }

    var url = 'pur/OrdLine/saveBatch'
    var param = {
        json: JSON.stringify(multipleSelectionLine.value[0]),
    }
    proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
            formLine.value = response.data.data
            ElMessage({
                message: '保存成功',
                type: 'success',
            })
            getTableDataLine(form.value.purOrdNo)
        } else {
            ElMessage({
                message: '操作失败' + response.data.msg,
                type: 'error'
            })
        }
    })
}
const ordPriceButton = ref(false)
const dialogVisibleOrdPrice = ref(false)
const formPrice = ref({
    purOrdHeadId: '',
    purOrdNo: '',
    purOrdLn: '',
    itemId: '',
    itemCd: '',
    itemNm: '',
    wetQty: '',
    qty: '',
    uom: '',
    price: '',
    taxPrice: '',
    amount: '',
    taxAmount: '',
    totalAmount: '',
    contrNo: '',
    contrNoLine: '',
    khContrNo: '',
    tradePartnerCode: '',
    tradePartnerName: '',
    priceStartTime: null,
    priceSts: '',
    addId: '',
    addCode: '',
    addName: '',
    addDeptId: '',
    addDeptCode: '',
    addDeptName: '',
    addTime: '',
})
const ruleFormRefPrice = ref()
const rulesPrice = reactive({
    priceStartTime: [{
        required: true,
        message: '请输入执行开始时间',
        trigger: 'change' | 'blur'
    }],
})
const lineConfirm = () => {
    if (multipleSelectionLine.value.length == 0) {
        ElMessageBox.confirm(
            '请选择采购订单行信息?',
            '提示', {
            confirmButtonText: '确认',
        })

        return
    }

    const row = multipleSelectionLine.value[0]
    if (row.purOrdSts === 'B') {
        ElMessage({
            type: 'warning',
            message: '请勿重复确认!'
        })
        return
    }

    const flag = tableDataLine.value.find(item => row.purOrdSts == 'D' && item.purOrdSts == 'A' && item.oldPurOrdLn == row.purOrdLn)
    if (row.purOrdLn.includes('_') || flag) {
        ElMessage({
            type: 'warning',
            message: '该行不能进行确认!'
        })
        return
    }

    formPrice.value = {
        purOrdHeadId: '',
        purOrdNo: '',
        purOrdLn: '',
        itemId: '',
        itemCd: '',
        itemNm: '',
        wetQty: '',
        qty: '',
        uom: '',
        price: '',
        taxPrice: '',
        amount: '',
        taxAmount: '',
        totalAmount: '',
        contrNo: '',
        contrNoLine: '',
        khContrNo: '',
        tradePartnerCode: '',
        tradePartnerName: '',
        priceStartTime: null,
        priceSts: '',
        addId: '',
        addCode: '',
        addName: '',
        addDeptId: '',
        addDeptCode: '',
        addDeptName: '',
        addTime: '',
    }

    if (ruleFormRefPrice.value) {
        ruleFormRefPrice.value.resetFields();
    }

    ordPriceButton.value = true
    dialogVisibleOrdPrice.value = true
}
const saveLineConfirm = () => {
    formPrice.value.addId = userId
    formPrice.value.addCode = userCode
    formPrice.value.addName = userName
    formPrice.value.addDeptId = dept[0].id
    formPrice.value.addDeptCode = dept[0].deptCode
    formPrice.value.addDeptName = dept[0].deptName

    var url = 'pur/OrdLine/lineConfirm'
    var param = {
        json: JSON.stringify(multipleSelectionLine.value[0]),
        json1: JSON.stringify(formPrice.value)
    }
    proxy.$axios.post(url, param).then(response => {
        if (response.data.code === 0) {
            ElMessage({
                type: 'success',
                message: '确认成功!',
            });
            getTableDataLine(form.value.purOrdNo)
            getTableData()
            dialogVisibleOrdPrice.value = false
        } else {
            ElMessage({
                type: 'error',
                message: '确认失败，' + response.data.msg
            })
        }
    })
}
const handleCancelLineConfirm = () => {
    dialogVisibleOrdPrice.value = false
}

const lineVoid = () => {
    if (multipleSelectionLine.value.length == 0) {
        ElMessageBox.confirm(
            '请选择采购订单行信息?',
            '提示', {
            confirmButtonText: '确认',
        })

        return
    }

    const row = multipleSelectionLine.value[0]
    if (row.purOrdSts === 'D') {
        ElMessage({
            type: 'warning',
            message: '请勿重复作废!'
        })
        return
    }

    var url = 'pur/OrdLine/lineVoid'
    var json = JSON.stringify(row)
    var param = {
        json: json,
    }
    proxy.$axios.post(url, param).then(response => {
        if (response.data.code === 0) {
            ElMessage({
                type: 'success',
                message: '确认成功!',
            });
            getTableDataLine(form.value.purOrdNo)
            getTableData()
        } else {
            ElMessage({
                type: 'error',
                message: '确认失败' + response.data.msg
            })
        }
    })
}
/**
 * 新增、确认、作废
 */


/**
 * 分页
 */
const currentPageCotHead = ref(1)
const totalRowsCotHead = ref(0)
const pageSizesCotHead = ref([5, 10, 20, 30, 40])
const pageSizeCotHead = ref(5)
const handleSizeChangeCotHead = (val) => {
    pageSize.value = val
    getTableDataCotHead()
}
const handleCurrentChangeCotHead = (val) => {
    currentPage.value = val
    getTableDataCotHead()
}
/**
 * 分页
 */

/**
 * 查询 —— 合同头
 */
const paramsCot = ref({
    contrNo: '',
    contrNm: '',
    contrTy: '20',
    supplierCd: '',
    supplierNm: '',
    khContrNo: '',
    contrDt: '',
})
const PopupRefCot = ref(null)
const handleSearchCotHead = () => {
    paramsCot.value = {
        contrNo: '',
        contrNm: '',
        contrTy: '20',
        supplierCd: '',
        supplierNm: '',
        contrDt: '',
        khContrNo: '',
    }
    PopupRefCot.value.open()
}
/**
 *   查询
 */





/**
 * 选择
 */
const retuCot = (row) => {
    form.value.contrId = row.id
    form.value.contrNo = row.contrNo
    form.value.contrNm = row.contrNm
    form.value.contrDt = row.contrDt
    form.value.khContrNo = row.khContrNo
    form.value.tradePartnerCode = row.supplierCd
    form.value.tradePartnerName = row.supplierNm
    form.value.compCd = row.compCd
    form.value.payMth = row.payMth
    form.value.delvMth = row.delvMth
    form.value.delvDt = row.delvDate
    form.value.trsMth = row.trsMth
    form.value.invMth = row.invMth
    form.value.fromPlace = row.fromPlace

    // dialogVisibleCotHead.value = false
}
/**
 * 选择
 */


/**
 *  查询字典
 */
const dicList = ref({
    PUR_ORD_STS: [],
    DELV_MTH: [],
    TMS_FTRANTYPE: [],
    SAL_INV_MTH: [],
    COM_PAY_MTH: [],
    MEASURING_UNIT: [],
    TAX_RATE: [],
})
const getDictList = () => {
    var url = 'framework/Common/querySelectorList'
    var param = {
        type: JSON.stringify(['PUR_ORD_STS', 'DELV_MTH', 'TMS_FTRANTYPE', 'SAL_INV_MTH', 'COM_PAY_MTH', 'MEASURING_UNIT', 'TAX_RATE'])
    }
    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 'trsMth':
            cellValue = dicList.value.TMS_FTRANTYPE.find(item => item.dicCode == cellValue).dicName
            break
        case 'addTime':
            cellValue = cellValue.split(' ')[0]
            break
        case 'uom':
            cellValue = dicList.value.MEASURING_UNIT.find(item => item.dicCode == cellValue).dicName
            break
        case 'taxRate':
            cellValue = dicList.value.TAX_RATE.find(item => item.dicCode == cellValue).dicName
            break
    }

    return cellValue
}
/**
 *  查询字典
 */


/**
 * 物料
 */
// const PopupRef = ref(null)
// const handleItem = () => {
//   PopupRef.value.open()
// }
// const retu = (val) => {
//   row.itemId = val.id
//   row.itemCd = val.itemCd
//   row.itemNm = val.itemNm
//   row.uom = val.unit
// }
/**
 * 物料
 */
</script>

<style scoped>
::v-deep .diaClass .el-form-item {
    width: 100%
}

::v-deep .diaClass .el-dialog__body {
    background-color: #F2F6FC;
}

.el-date-editor--date {
    width: 100%;
}

::v-deep .box-card .el-card__header {
    padding: 5px 20px;
}

/* ::v-deep .el-table__header-wrapper .el-checkbox {
  visibility: hidden;
} */
</style>