<template>
    <div>
        <el-card :body-style="cardBodyStyle">
            <el-form :model="query" label-position="right" :inline="true">
                <el-row :gutter="10" style="margin-bottom: 5px;">
                    <el-col :span="5">
                        <el-form-item label="领料单号" style="margin-bottom: 0px;">
                            <el-input v-model="query.reqNo" placeholder="请输入" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="领料名称" style="margin-bottom: 0px;">
                            <el-input v-model="query.reqNm" placeholder="请输入" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="领料日期" style="margin-bottom: 0px;">
                            <el-date-picker v-model="query.demandDt" type="date" value-format="YYYY-MM-DD"
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <ButtonBar @search="handleSearch" @add="handleAdd" @confirm="confirm"></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"
                        @row-click="DoubleClick">
                        <el-table-column type="selection" fixed></el-table-column>
                        <el-table-column type="index" label="序号" align="center" width="60" fixed="left">
                            <template #default="scope">
                                <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column v-if="true" prop="reqNo" label="领料单号" min-width="150" header-align="center"
                            align="center" show-overflow-tooltip fixed>
                        </el-table-column>
                        <el-table-column v-if="true" prop="reqNm" label="领料名称" min-width="120" header-align="center"
                            align="center" show-overflow-tooltip fixed>
                        </el-table-column>
                        <el-table-column v-if="true" prop="reqSts" label="领料状态" header-align="center" align="center"
                            min-width="100" show-overflow-tooltip :formatter="formatter">
                        </el-table-column>
                        <el-table-column v-if="true" prop="purTy" label="领料类型" min-width="100" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="false" prop="purMth" label="采购方式" min-width="100" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="addDeptName" label="领料部门" min-width="100"
                            header-align="center" align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="addName" label="领料人" min-width="100" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="demandDt" label="领料日期" min-width="150" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>

                        <el-table-column label="操作" header-align="center" align="center" width="300px" fixed="right">
                            <template #default="{ row }">
                                <el-button plain type="warning" @click="handleEdit(row)" v-show="row.reqSts === 'A'">编辑
                                </el-button>
                                <el-button plain type="danger" @click="handleDelete(row)" v-show="row.reqSts === 'A'">删除
                                </el-button>
                                <el-button plain type="primary" @click="handleDetail(row)"
                                    v-show="row.reqSts === 'B'">查看</el-button>
                            </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-button plain type="primary" @click="handleAddLine">新增</el-button>
            <el-button plain type="success" @click="handleConfirmLine">确认</el-button>
        </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" border highlight-current-row
                        @selection-change="handleSelectionChangeLine">
                        <el-table-column type="selection" fixed></el-table-column>
                        <el-table-column type="index" label="序号" align="center" width="60" fixed="left">
                            <template #default="scope">
                                <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column v-if="true" prop="reqLn" label="领料单行号" width="100" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="reqSts" label="领料状态" header-align="center" align="center"
                            min-width="100" show-overflow-tooltip :formatter="formatter">
                        </el-table-column>
                        <el-table-column v-if="false" prop="storeCd" label="领料库房编码" width="100" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="storeNm" label="领料库房" width="100" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="false" 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="150" header-align="center"
                            align="center" show-overflow-tooltip>
                            <template #default="{ row }">
                                <span v-if="row.cancelFlag == '1'">
                                    <el-input v-model="row.itemNm" clearable readonly>
                                        <template #append>
                                            <el-button :icon="Search" @click="handleSearchItem" />
                                        </template>
                                    </el-input>
                                </span>
                                <span v-else>{{ row.itemNm }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column v-if="true" prop="specType" 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.specType" clearable>
                                    </el-input>
                                </span>
                                <span v-else>{{ row.specType }}</span>
                            </template>
                        </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'">
                                    <el-input v-model="row.qty" oninput="value=value.replace(/[^0-9.]/g,'')" clearable
                                        @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="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,'')"
                                        clearable @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">
                            <template #default="{ row }">
                                <span v-if="row.cancelFlag == 1">
                                    <el-select v-model="row.taxRate" placeholder="请选择" clearable
                                        @change="calculatePrice(row)">
                                        <el-option v-for="item in dicList.TAX_RATE" :key="item.dicCode"
                                            :label="item.dicName" :value="item.dicCode" />
                                    </el-select>
                                </span>
                                <span v-else>{{ row.taxPrice }}</span>
                            </template>
                        </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="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="180"
                            header-align="center" align="center" show-overflow-tooltip>
                            <template #default="{ row }">
                                <span v-if="row.cancelFlag == 1">
                                    <el-input v-model="row.tradePartnerName" clearable readonly>
                                        <template #append>
                                            <el-button :icon="Search" @click="handleSearchTradePartner" />
                                        </template>
                                    </el-input>
                                </span>
                                <span v-else>{{ row.tradePartnerName }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column v-if="true" prop="reqNo" label="领料单号" width="200" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="reqNm" label="领料名称" width="200" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="addDeptName" label="领料部门" width="100" 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="demandDt" label="领料日期" width="200" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="remark" label="备注" header-align="center" align="center"
                            width="160" show-overflow-tooltip>
                        </el-table-column>

                        <el-table-column label="操作" header-align="center" align="center" width="300px" fixed="right">
                            <template #default="{ row }">
                                <el-button plain type="primary" @click="handleSaveLine(row)"
                                    v-if="row.cancelFlag === '1'">保存
                                </el-button>
                                <el-button plain type="success" @click="handleCancelSaveLine(row)"
                                    v-if="row.cancelFlag === '1'">取消
                                </el-button>
                                <el-button plain type="warning" @click="handleEditLine(row)"
                                    v-if="row.cancelFlag === '0' && readonlyLine && row.reqSts == 'A'">编辑
                                </el-button>
                                <el-button plain type="danger" @click="handleDeleteLine(row)"
                                    v-if="row.cancelFlag === '0' && readonlyLine && row.reqSts == 'A'">删除
                                </el-button>
                            </template>
                        </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 class="diaClass" :close-on-click-modal="false" draggable :title="title" v-model="dialogVisible"
            width="700px" top="5vh" @open="openDialog">
            <el-card>

                <el-form :model="form" label-width="100px" label-position="right" inline ref="ruleFormRef"
                    :rules="rules">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="领料单号" prop="reqNo">
                                <el-input v-model="form.reqNo" disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="领料名称" prop="reqNm">
                                <el-input v-model="form.reqNm" :readonly="readonly"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="领料类型" prop="purTy">
                                <el-select v-model="form.purTy" placeholder="请选择" clearable style="width: 220px"
                                    :disabled="readonly">
                                    <el-option key="10" label="备选备件" value="10" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="领料部门" prop="addDeptName">
                                <el-input v-model="form.addDeptName" disabled>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="领料人" prop="addName">
                                <el-input v-model="form.addName" disabled>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="领料日期" prop="demandDt">
                                <el-date-picker v-model="form.demandDt" type="date" value-format="YYYY-MM-DD"
                                    style="width: 100%;" :readonly="readonly" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="备注">
                                <el-input v-model="form.remark" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
                                    :readonly="readonly" />
                            </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)">保存</el-button>
                    <el-button plain type="danger" @click="handleCancelSave">取消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 需求计划审批通过？ -->
        <PopupPurDemandPlan ref="PopupRefDemandPlan" @receive-from-child="retuDemandPlan"></PopupPurDemandPlan>

        <Popup_base_wl ref="PopupRefItem" :salesFlag="''" :purchaseFlag="'Y'" @receive-from-child="retuItem">
        </Popup_base_wl>

        <Popup_base_ks ref="PopupRefTradePartner" :tpTypeShow="true" :tpType="'1'"
            @receive-from-child="retuTradePartner">
        </Popup_base_ks>

        <el-dialog :close-on-click-modal="false" draggable v-model="dialogVisibleLine" @open="openDialog" width = "450">
            <el-card>
                <el-form :inline="true" :model="formLine" label-position="right" label-width="80px"
                    ref="ruleFormRefLine" :rules="rulesLine" style="margin-top: 10px;">
                    <el-col :span="22">
                        <el-form-item label="领料库房" prop="storeNm">
                            <Popup_sto_config_kf_bx :store-nm="''" :key="keyTime" @receive-from-child="returnKf">
                            </Popup_sto_config_kf_bx>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-card>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="success" plain @click="saveLineConfirm(ruleFormRefLine)">保存</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 PopupPurDemandPlan from '@/views/pur/components/PopupPurDemandPlan.vue'
import Popup_base_wl from "@/views/bas/Popup_base_wl.vue"
import Popup_base_ks from "@/views/bas/Popup_base_ks.vue"
import Popup_sto_config_kf_bx from "@/views/sto/components/Popup_sto_config_kf_bx.vue"

import {
    ref,
    reactive,
    onMounted,
    getCurrentInstance
} from 'vue'

const {
    proxy
} = getCurrentInstance()

import style from '@/tools/style'
import { Search } from '@element-plus/icons-vue'
import { workflowCancel, workflowSubmit } from "@/tools/workflow.js"
const cardBodyStyle = ref(style.card)


onMounted(() => {
    getDicList()
    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 dicList = ref({
    COM_PAY_MTH: [],
    PUR_PAY_TYPE: [],
    PROVINCE_CODE: [],
    PUR_PAY_STS: [],
})
const getDicList = () => {
    var url = 'framework/Common/querySelectorList'
    var param = {
        type: JSON.stringify(['PUR_ORD_STS', '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 'reqSts':
            cellValue = dicList.value.PUR_ORD_STS.find(item => item.dicCode == cellValue)?.dicName
            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 query = ref({
    reqNo: '',
    reqNm: '',
    demandDt: '',
})
const activeNameTop = ref('master')
const loading = ref(false)
const tableData = ref([])
const handleSearch = () => {
    form.value = {
        id: '',
        reqNo: '',
        reqNm: '',
        demandDt: '',
        remark: '',
        reqSts: '',
        processInstanceId: '',
        processInstanceStatus: '',
        addId: userId,
        addCode: userCode,
        addName: userName,
        addDeptId: dept[0].Id,
        addDeptCode: dept[0].deptCode,
        addDeptName: dept[0].deptName,
        addTime: '',
        modifyId: '',
        modifyCode: '',
        modifyName: '',
        modifyTime: '',
        cancelId: '',
        cancelCode: '',
        cancelName: '',
    }
    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
            tableData.value = [
                {
                    id: '1',
                    reqNo: 'RQ250110001',
                    reqNm: '生产领料A',
                    purTy: '备选备件',
                    purMth: '公开招标',
                    addDeptName: '采购部',
                    addName: '张三',
                    demandDt: '2024-10-01',
                    reqSts: 'A',
                },
                {
                    id: '2',
                    reqNo: 'RQ250110002',
                    reqNm: '生产领料B',
                    purTy: '备选备件',
                    purMth: '公开招标',
                    addDeptName: '采购部',
                    addName: '李四',
                    demandDt: '2024-10-05',
                    reqSts: 'B',
                },
                {
                    id: '3',
                    reqNo: 'RQ250110003',
                    reqNm: '生产领料C',
                    purTy: '备选备件',
                    purMth: '公开招标',
                    addDeptName: '采购部',
                    addName: '王五',
                    demandDt: '2024-10-10',
                    reqSts: 'C',
                },
            ]
        } 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 dialogVisible = ref(false)
const form = ref({
    id: '',
    reqNo: '',
    reqNm: '',
    demandDt: '',
    remark: '',
    addId: '',
    addCode: '',
    addName: '',
    addDeptId: '',
    addDeptCode: '',
    addDeptName: '',
    addTime: '',
    modifyId: '',
    modifyCode: '',
    modifyName: '',
    modifyTime: '',
    cancelId: '',
    cancelCode: '',
    cancelName: '',
})
const ruleFormRef = ref()
// 校验
const rules = reactive({
    reqNm: [
        { required: true, message: '请输入领料名称', trigger: 'blur' | 'change' },
    ],
    demandDt: [
        { required: true, message: '请输入领料日期', trigger: 'blur' | 'change' },
    ],
    purTy: [
        { required: true, message: '请输入采购类型', trigger: 'blur' | 'change' },
    ],
    purMth: [
        { required: true, message: '请输入采购方式', trigger: 'blur' | 'change' },
    ],
    addName: [
        { required: true, message: '请输入领料人', trigger: 'blur' | 'change' },
    ],
    addDeptName: [
        { required: true, message: '请输入领料部门', trigger: 'blur' | 'change' },
    ],
})

const readonly = ref(false)
const handleAdd = () => {
    if (window.localStorage.getItem('dept') == JSON.stringify(new Array())) {
        ElMessage({
            type: 'warning',
            message: '请添加登录人所在部门'
        })
        return
    }

    form.value = {
        id: '',
        reqNo: '',
        reqNm: '',
        purTy: '',
        demandDt: '',
        remark: '',
        processInstanceId: '',
        processInstanceStatus: '',
        addId: userId,
        addCode: userCode,
        addName: userName,
        addDeptId: dept[0].Id,
        addDeptCode: dept[0].deptCode,
        addDeptName: dept[0].deptName,
        addTime: '',
        modifyId: '',
        modifyCode: '',
        modifyName: '',
        modifyTime: '',
        cancelId: '',
        cancelCode: '',
        cancelName: '',
        cancelFlag: '1'
    }

    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) {
    //                 form.value = response.data.data
    //                 ElMessage({
    //                     message: '保存成功',
    //                     type: 'success',
    //                 })
    //                 getTableData()
    //                 dialogVisible.value = false
    //             } else {
    //                 ElMessage({
    //                     message: '操作失败' + response.data.msg,
    //                     type: 'error'
    //                 })
    //             }
    //         })

    //     } else {
    //         console.log('error submit!', fields)
    //     }
    // })
}
const handleCancelSave = () => {
    dialogVisible.value = false
    getTableData()
}
const handleEdit = (row) => {
    if (ruleFormRef.value) {
        ruleFormRef.value.resetFields();
    }
    title.value = '编辑'
    form.value = { ...row }
    form.value.modifyCode = userCode
    form.value.modifyName = userName

    readonly.value = false
    dialogVisible.value = true
}

const handleDetail = (row) => {
    if (ruleFormRef.value) {
        ruleFormRef.value.resetFields();
    }
    title.value = '查看'
    form.value = { ...row }

    readonly.value = true
    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 confirm = () => {
    const flag = multipleSelection.value.filter(item => item.reqSts === 'B')
    if (flag.length > 0) {
        ElMessage({
            type: 'warning',
            message: '领料单号' + flag.map(item => item.reqNo).join('、') + '已确认，请勿重复操作！'
        })
        return
    }


    multipleSelection.value.forEach(item => item.reqSts = 'B') // 上线后需要注释该行代码
    // var url = 'pur/OrdHead/confirm'
    // 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 queryLine = ref({
    reqNo: ''
})

const readonlyLine = ref(false)
const activeNameBottom = ref('first')
const tableDataLine = ref([])
const loadingLine = ref(false)
const DoubleClick = (row) => {
    form.value = { ...row }
    readonlyLine.value = row.reqSts != 'C'
    queryLine.value.reqNo = row.reqNo
    getTableDataLine()
}
const getTableDataLine = () => {
    var url = 'pur/OrdLine/query'
    var param = {
        page: currentPageLine.value,
        rows: pageSizeLine.value,
        params: JSON.stringify(queryLine.value)
    }
    proxy.$axios.get(url, param).then(response => {
        // tableDataLine.value = response.data.data.records
        totalRowsLine.value = response.data.data.total
        tableDataLine.value = [{
            id: '1',
            reqNo: 'RQ250110001', // 与 tableData 中的生产领料关联
            reqLn: '0001',
            reqNm: '生产领料A',
            itemCd: '10101012351', // 物料编码
            itemNm: 'M2矿',   // 物料名称
            reqSts: 'B',
            qty: 100,          // 领料量
            uom: 'wet ton',         // 领料部门
            taxPrice: 1000.00,    // 含税单价
            totalAmount: 100000.00, // 含税金额 (领料量 * 含税单价)
            price: 884.96,
            amount: 88496.00,
            taxRate: 13,     // 税率,
            tradePartnerCode: 'D01000008',
            tradePartnerName: '青岛陆洋兴达国际贸易有限公司',
            addDeptName: '生产部', // 领料部门（可以从 tableData 继承或单独设置）
            addName: '张三',    // 领料人（可以从 tableData 继承或单独设置）
            demandDt: '2024-10-01', // 需求日期（可以从 tableData 继承或单独设置）
            cancelFlag: '0',
        },]
    })
}
/**
 *   查询
 */


/**
 * 分页
 */
const currentPageLine = ref(1)
const totalRowsLine = ref(0)
const pageSizesLine = ref([5, 10, 20, 30, 40])
const pageSizeLine = ref(5)
const handleSizeChangeLine = (val) => {
    pageSizeLine.value = val
    getTableDataLine()
}
const handleCurrentChangeLine = (val) => {
    currentPageLine.value = val
    getTableDataLine()
}
/**
 * 分页
 */


/**
 * 新增
 */
const formLine = ref({
    id: '',
    storeCd: '',
    storeNm: '',
    itemCd: '',
    itemNm: '',
    qty: '',
    uom: '',
    taxPrice: '',
    totalAmount: '',
    taxRate: '',
    reqNo: '',
    reqLn: '',
    reqNm: '',
    demandDt: '',
    remark: '',
    addId: '',
    addCode: '',
    addName: '',
    addDeptId: '',
    addDeptCode: '',
    addDeptName: '',
    addTime: '',
    modifyId: '',
    modifyCode: '',
    modifyName: '',
    modifyTime: '',
    cancelId: '',
    cancelCode: '',
    cancelName: '',
})
const ruleFormRefLine = ref()
// 校验
const rulesLine = reactive({
    storeCd: [
        { required: true, message: '请输入领料库房编码', trigger: 'blur' | 'change' },
    ],
    storeNm: [
        { required: true, message: '请输入领料库房', trigger: 'blur' | 'change' },
    ],
    inStoreCd: [
        { required: true, message: '请输入调入库房编码', trigger: 'blur' | 'change' },
    ],
    inStoreNm: [
        { required: true, message: '请输入调入库房', trigger: 'blur' | 'change' },
    ],
    
})

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

    if (form.value.id === '') {
        ElMessage({
            type: 'warning',
            message: '请选择领料申请头'
        })
        return
    }

    if (form.value.reqSts === 'C') {
        ElMessage({
            type: 'warning',
            message: '该领料申请头处于关闭状态'
        })
        return
    }

    const flag = tableDataLine.value.find(item => item.cancelFlag === '1')
    if (flag) {
        ElMessage({
            type: 'warning',
            message: '请先保存行！'
        })
        return
    }


    formLine.value = {
        id: '',
        itemCd: '',
        itemNm: '',
        qty: '',
        uom: '',
        taxPrice: '',
        totalAmount: '',
        taxRate: '',
        reqNo: form.value.reqNo,
        reqLn: '',
        reqNm: form.value.reqNm,
        demandDt: form.value.demandDt,
        remark: '',
        processInstanceId: '',
        processInstanceStatus: '',
        addId: userId,
        addCode: userCode,
        addName: userName,
        addDeptId: dept[0].Id,
        addDeptCode: dept[0].deptCode,
        addDeptName: dept[0].deptName,
        addTime: '',
        modifyId: '',
        modifyCode: '',
        modifyName: '',
        modifyTime: '',
        cancelId: '',
        cancelCode: '',
        cancelName: '',
        cancelFlag: '1',
    }

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

    PopupRefDemandPlan.value.open()

}

const PopupRefDemandPlan = ref(null)
const retuDemandPlan = (val) => {
    console.log(val)

    if (JSON.stringify(val) != JSON.stringify(new Array())) {
        const temp = ref([])
        val.forEach(item => {
            const row = { ...item }
            row.reqNo = form.value.reqNo
            row.reqNm = form.value.reqNm
            row.reqSts = 'A'
            // 领料日期
            const now = new Date();
            row.demandDt = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
            row.addId = userId
            row.addCode = userCode
            row.addName = userName
            row.addDeptId = dept[0].id
            row.addDeptCode = dept[0].deptCode
            row.addDeptName = dept[0].deptName

            temp.value.push(row)

            // 正式上线删除代码
            row.reqLn = '000' + (tableDataLine.value.length + 1)
            tableDataLine.value.push(row)
        })

        // var url = 'pur/OrdHead/saveBatch'
        // var param = {
        //     json: JSON.stringify(temp.value), // 保存领料明细
        //     json1: JSON.stringify(val),       // 回写是否生成领料申请
        // }
        // proxy.$axios.post(url, param).then(response => {
        //     if (response.data.code == 0) {
        //         form.value = response.data.data
        //         ElMessage({
        //             message: '保存成功',
        //             type: 'success',
        //         })
        //         getTableData()
        //     } else {
        //         ElMessage({
        //             message: '操作失败' + response.data.msg,
        //             type: 'error'
        //         })
        //     }
        // })
    }
}
/**
 * 新增
 */



/**
* 物料
*/
const PopupRefItem = ref(null)
const handleSearchItem = () => {
    PopupRefItem.value.open()
}
const retuItem = (val) => {
    formLine.value.itemId = val.id
    formLine.value.itemCd = val.itemCd
    formLine.value.itemNm = val.itemNm
    formLine.value.uom = val.unit
}


/**
* 供应商
*/
const PopupRefTradePartner = ref(null)
const handleSearchTradePartner = () => {
    PopupRefTradePartner.value.open()
}
const retuTradePartner = (val) => {
    // const flag = tableDataLine.value.find(item => item.tradePartnerCode != val.tradePartnerCode)
    // if(flag) {
    //     ElMessage({
    //         type: 'warning',
    //         message: '存在不同的供应商'
    //     })
    //     return 
    // }

    formLine.value.tradePartnerId = val.id
    formLine.value.tradePartnerName = val.tradePartnerName
    formLine.value.tradePartnerCode = val.tradePartnerCode
}

const calculatePrice = (row) => {
    if (row.qty !== '' && row.taxPrice !== '' && row.taxRate !== '') {

        // 不含税单价 = 含税单价 / (1 + 税率)
        row.price = numberToFixed(Number(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 handleSaveLine = (row) => {
    if (row.itemNm === '' || row.tradePartnerName === '' || row.qty === '' || row.taxPrice === '' || row.taxRate === '') {
        if (row.itemNm === '') {
            ElMessage({
                type: 'warning',
                message: '物料不能为空'
            })
        }

        if (row.tradePartnerName === '') {
            ElMessage({
                type: 'warning',
                message: '供应商不能为空'
            })
        }

        if (row.qty === '') {
            ElMessage({
                type: 'warning',
                message: '领料量不能为空'
            })
        }

        if (row.taxPrice === '') {
            ElMessage({
                type: 'warning',
                message: '含税价格不能为空'
            })
        }

        if (row.taxRate === '') {
            ElMessage({
                type: 'warning',
                message: '税率不能为空'
            })
        }

        return
    }

    row.cancelFlag = '0'
    if (row.id === '') {
        row.addId = userId
        row.addCode = userCode
        row.addName = userName
        row.addDeptId = dept[0].Id
        row.addDeptCode = dept[0].deptCode
        row.addDeptName = dept[0].deptName
    } else {
        row.modifyId = userId
        row.modifyCode = userCode
        row.modifyName = userName
    }

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

const handleCancelSaveLine = (row) => {
    if (row.id !== '') {
        row.cancelFlag = '0'
    } else {
        handleDeleteLine(row)
    }
}

const handleDeleteLine = (row) => {
    row.cancelId = userId
    row.cancelCode = userCode
    row.cancelName = userName

    tableDataLine.value.pop(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: '删除成功',
    //             })
    //             queryLine.value.reqNo = row.reqNo
    //             getTableDataLine()
    //         } else {
    //             ElMessage({
    //                 type: 'error',
    //                 message: '删除失败' + response.data.msg
    //             });
    //         }
    //     });
    // }).catch(() => {
    //     ElMessage({
    //         type: 'info',
    //         message: '已取消',
    //     })
    // })
}

const handleEditLine = (row) => {
    const flag = tableDataLine.value.find(item => item.cancelFlag === '1')
    if (flag) {
        ElMessage({
            type: 'warning',
            message: '请先保存行！'
        })
        return
    }

    row.cancelFlag = '1'
}



/**
 * 
 */
const multipleSelectionLine = ref([])
const handleSelectionChangeLine = (val) => {
    multipleSelectionLine.value = val
}

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

    if (form.value.id === '') {
        ElMessage({
            type: 'warning',
            message: '请选择领料申请头'
        })
        return
    }

    const flag = tableDataLine.value.find(item => item.cancelFlag === '1')
    if (flag) {
        ElMessage({
            type: 'warning',
            message: '请先保存行！'
        })
        return
    }

    if (multipleSelectionLine.value.length === 0) {
        ElMessage({
            type: 'warning',
            message: '请选择要确认的领料明细'
        })
        return
    }

    const flag1 = multipleSelectionLine.value.filter(item => item.reqSts === 'B')
    if (flag1.length > 0) {
        ElMessage({
            type: 'warning',
            message: '领料单行号' + flag1.map(item => item.reqLn).join('、') + '已确认，请勿重复操作！'
        })
        return
    }

    dialogVisibleLine.value = true
}


/**
 * 
 */
const keyTime = ref('')
const dialogVisibleLine = ref(false)
const returnKf = (val) => {
    formLine.value.storeCd = val.storeCd
    formLine.value.storeNm = val.storeNm
}
const saveLineConfirm = (ruleFormRefLine) => {
    
    multipleSelectionLine.value.forEach(item => {
        item.reqSts = 'B'
        item.storeCd = formLine.value.storeCd
        item.storeNm = formLine.value.storeNm
        item.modifyId = userId
        item.modifyCode = userCode
        item.modifyName = userName

        // 正式上线删除代码
        tableDataLine.value.forEach(item1 => {
            if (item1.reqLn == item.reqLn) {
                item1 = item
            }
        })
    })
    // 正式上线删除代码
    dialogVisibleLine.value = false
    keyTime.value = new Date().getTime()

    // ruleFormRefLine.validate((valid, fields) => {
    //     if (valid) {
    //         var url = 'pur/OrdLine/lineConfirm'
    //         var param = {
    //             json: JSON.stringify(multipleSelectionLine.value)
    //         }
    //         proxy.$axios.post(url, param).then(response => {
    //             if (response.data.code === 0) {
    //                 ElMessage({
    //                     type: 'success',
    //                     message: '确认成功!',
    //                 });
    //                 queryLine.value.reqNo = row.reqNo
    //                 getTableDataLine()
    //                 dialogVisibleLine.value = false
    //                 keyTime.value = new Date().getTime()
    //             } else {
    //                 ElMessage({
    //                     type: 'error',
    //                     message: '确认失败，' + response.data.msg
    //                 })
    //             }
    //         })
    //     } else {
    //         console.log('error submit!', fields)
    //     }
    // })
}
const handleCancelLineConfirm = (row) => {
    dialogVisibleLine.value = false
    keyTime.value = new Date().getTime()
}
</script>

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

.el-form-item {
    width: 100%
}

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

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

.highlighted-cell {
    border: 1px solid red;
    border-radius: 5px;
    padding: 1px;
    color: #67c23a;
}
</style>
