<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.planNo" 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.planNm" 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" @import="handleImport"></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="planNo" label="计划号" width="200" header-align="center"
                            align="center" show-overflow-tooltip fixed>
                        </el-table-column>
                        <el-table-column v-if="true" prop="planNm" label="计划名称" width="200" header-align="center"
                            align="center" show-overflow-tooltip fixed>
                        </el-table-column>
                        <el-table-column v-if="true" prop="addDeptName" label="计划部门" width="160" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="addName" label="计划员" width="160" 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 v-if="true" prop="workModel.flowStatusName" label="流程状态" width="120"
                            header-align="center" align="center" show-overflow-tooltip>
                            <template #default="{ row }">
                                <div>
                                    <el-tag v-if="row.workId !== undefined && row.workModel.flowStatus === '110'">{{
                                        row.workModel.flowStatusName }}</el-tag>
                                    <el-tag type="success"
                                        v-else-if="row.workId !== undefined && row.workModel.flowStatus === '170'">{{
                                            row.workModel.flowStatusName }}</el-tag>
                                    <el-tag type="danger"
                                        v-else-if="row.workId !== undefined && (row.workModel.flowStatus === '130' || row.workModel.flowStatus === '180' || row.workModel.flowStatus === '190')">{{
                                            row.workModel.flowStatusName }}</el-tag>
                                    <el-tag type="warning" v-else>'---'</el-tag>
                                </div>

                            </template>
                        </el-table-column>
                        <el-table-column v-if="true" prop="workModel.flowNode" label="当前节点" width="120"
                            header-align="center" align="center" show-overflow-tooltip>
                            <template #default="{ row }">
                                <div>
                                    <el-tag v-if="row.workId !== undefined && row.workModel.flowStatus === '110'">{{
                                        row.workModel.flowNode }}</el-tag>
                                    <el-tag type="success"
                                        v-else-if="row.workId !== undefined && row.workModel.flowStatus === '170'">{{
                                            row.workModel.flowNode }}</el-tag>
                                    <el-tag type="danger"
                                        v-else-if="row.workId !== undefined && (row.workModel.flowStatus === '130' || row.workModel.flowStatus === '180' || row.workModel.flowStatus === '190')">{{
                                            row.workModel.flowNode }}</el-tag>
                                    <el-tag type="warning" v-else>'---'</el-tag>
                                </div>
                            </template>
                        </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.workId === '' || row.workModel.opType === '1'">编辑
                                </el-button>
                                <el-button plain type="danger" @click="handleDelete(row)"
                                    v-show="row.workId === '' || row.workModel.opType === '1'">删除
                                </el-button>
                                <el-button plain type="success" @click="handleSubmit(row)"
                                    v-show="row.workId === '' || row.workModel.opType === '1'">发起
                                </el-button>
                                <el-button plain type="primary" @click="handleDetail(row)"
                                    v-show="row.workId !== ''">详情</el-button>
                                <el-button plain type="info" @click="handleCancel(row)"
                                    v-show="row.workId !== '' && row.workModel.opType !== '1' && row.workModel.flowStatus !== '170'">撤回</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-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="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="180"
                            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="planNo" label="计划号" width="200" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="planLn" label="计划行号" width="100" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="planNm" 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 v-if="true" prop="purFlag" label="是否转为采购计划" header-align="center" align="center"
                            width="150" show-overflow-tooltip  :formatter="formatter">
                        </el-table-column>
                        <el-table-column v-if="true" prop="transQeqFlag" label="是否转为调拨申请" header-align="center" align="center"
                            width="150" show-overflow-tooltip  :formatter="formatter">
                        </el-table-column>
                        <el-table-column v-if="true" prop="materialFlag" label="是否转为领料申请" header-align="center" align="center"
                            width="150" show-overflow-tooltip  :formatter="formatter">
                        </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">编辑
                                </el-button>
                                <el-button plain type="danger" @click="handleDeleteLine(row)" v-if ="row.cancelFlag === '0' && readonlyLine">删除
                                </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="550px" top="5vh" @open="openDialog">
            <el-card>

                <el-form :model="form" label-width="120px" label-position="right" inline ref="ruleFormRef"
                    :rules="rules">
                    <el-row>
                        <el-col :span="20">
                            <el-form-item label="计划编号" prop="planNo">
                                <el-input v-model="form.planNo" disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="20">
                            <el-form-item label="计划名称" prop="planNm">
                                <el-input v-model="form.planNm"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="20">
                            <el-form-item label="计划部门" prop="addDeptName">
                                <el-input v-model="form.addDeptName" disabled>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="20">
                            <el-form-item label="计划员" prop="addName">
                                <el-input v-model="form.addName" disabled>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="20">
                            <el-form-item label="需求日期" prop="demandDt">
                                <el-date-picker v-model="form.demandDt" type="date" value-format="YYYY-MM-DD"
                                    style="width: 100%;" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="20">
                            <el-form-item label="备注">
                                <el-input v-model="form.remark" :autosize="{ minRows: 2, maxRows: 4 }"
                                    type="textarea" />
                            </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>

        <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>

        <ImportExcel ref="ImportExcelRef" :url="importUrl" :formData="formData" @importSuccess="importSuccess">
        </ImportExcel>
    </div>
</template>

<script setup>
import ButtonBar from '@/components/ButtonBar.vue'
import Popup_base_wl from "@/views/bas/Popup_base_wl.vue"
import Popup_base_ks from "@/views/bas/Popup_base_ks.vue"
import ImportExcel from '@/components/ImportExcel.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(['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 '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
        case 'purFlag':
            cellValue = cellValue === '0' ? '否' : '是'
            break
        case 'transQeqFlag':
            cellValue = cellValue === '0' ? '否' : '是'
            break
        case 'materialFlag':
            cellValue = cellValue === '0' ? '否' : '是'
            break
    }

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


/**
 *   查询
 */
const query = ref({
    planNo: '',
    planNm: '',
    demandDt: '',
})
const activeNameTop = ref('master')
const loading = ref(false)
const tableData = ref([])
const handleSearch = () => {
    form.value = {
        id: '',
        planNo: '',
        planNm: '',
        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: '',
    }
    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',
                    planNo: 'PLAN001',
                    planNm: '生产计划A',
                    addDeptName: '生产部',
                    addName: '张三',
                    demandDt: '2024-10-01',
                    remark: '紧急订单',
                    workModel: {
                        flowStatus: '',
                        flowStatusName: '',
                        flowNode: '',
                        opType: '1'
                    },
                    workId: ''
                },
                {
                    id: '2',
                    planNo: 'PLAN002',
                    planNm: '生产计划B',
                    addDeptName: '采购部',
                    addName: '李四',
                    demandDt: '2024-10-05',
                    remark: '常规订单',
                    workModel: {
                        flowStatus: '110',
                        flowStatusName: '待处理',
                        flowNode: '审批中',
                        opType: '0'
                    },
                    workId: 'WORK002'
                },
                {
                    id: '3',
                    planNo: 'PLAN003',
                    planNm: '生产计划C',
                    addDeptName: '销售部',
                    addName: '王五',
                    demandDt: '2024-10-10',
                    remark: '特殊需求',
                    workModel: {
                        flowStatus: '190',
                        flowStatusName: '已撤回',
                        flowNode: '拟稿人',
                        opType: '1'
                    },
                    workId: 'WORK003'
                },
                {
                    id: '4',
                    planNo: 'PLAN004',
                    planNm: '生产计划D',
                    addDeptName: '财务部',
                    addName: '赵六',
                    demandDt: '2024-10-15',
                    remark: '预算内',
                    workModel: {
                        flowStatus: '130',
                        flowStatusName: '已退回',
                        flowNode: '拟稿人',
                        opType: '1'
                    },
                    workId: 'WORK004'
                },
                {
                    id: '5',
                    planNo: 'PLAN005',
                    planNm: '生产计划E',
                    addDeptName: '研发部',
                    addName: '孙七',
                    demandDt: '2024-10-20',
                    remark: '研发需求',
                    workModel: {
                        flowStatus: '170',
                        flowStatusName: '已完成',
                        flowNode: '结束',
                        opType: '0'
                    },
                    workId: 'WORK005'
                },
            ]
        } 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: '',
    planNo: '',
    planNm: '',
    demandDt: '',
    remark: '',
    addId: '',
    addCode: '',
    addName: '',
    addDeptId: '',
    addDeptCode: '',
    addDeptName: '',
    addTime: '',
    modifyId: '',
    modifyCode: '',
    modifyName: '',
    modifyTime: '',
    cancelId: '',
    cancelCode: '',
    cancelName: '',
})
const ruleFormRef = ref()
// 校验
const rules = reactive({
    planNm: [
        { required: true, message: '请输入计划名称', trigger: 'blur' | 'change' },
    ],
    demandDt: [
        { required: true, message: '请输入计划日期', trigger: 'blur' | 'change' },
    ],
    addName: [
        { required: true, message: '请输入计划员', trigger: 'blur' | 'change' },
    ],
    addDeptName: [
        { required: true, message: '请输入计划部门', trigger: 'blur' | 'change' },
    ],
})

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

    form.value = {
        id: '',
        planNo: '',
        planNm: '',
        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 = '新增'
    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

    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 flowId = ref('PurPlanFinance')
const handleSubmit = (row) => {
    // ElMessageBox.confirm(
    //     '确定提交流程?',
    //     '提示', {
    //     confirmButtonText: '确认',
    //     cancelButtonText: '取消',
    //     type: 'warning',
    //     draggable: true,
    // }).then(() => {
    //     let variables = {
    // 		id: row.id,
    // 		payAmount: row.payAmount
    // 	}
    //     return workflowSubmit(
    //         flowId.value,
    //         '需求计划审批流程',
    //         '初始化提交',
    //         JSON.stringify(variables),
    //         row.workId,
    //         row.trackId)
    // }).then((result) => {
    //     if (result.status === 'success') {
    //         var url = 'pur/PurOrdHead/saveProcessInfo'
    //         var process = {
    //             'id': row.id,
    //             'workId': result.workId,
    //             'trackId': result.trackId,
    //         }
    //         var param = {
    //             json: JSON.stringify(process),
    //         }
    //         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 handleCancel = (row) => {
    // ElMessageBox.confirm(
    //     '确定撤回审批?',
    //     '提示', {
    //     confirmButtonText: '确认',
    //     cancelButtonText: '取消',
    //     type: 'warning',
    //     draggable: true,
    // }
    // ).then(() => {
    //     return workflowCancel(row.workId, row.trackId);
    // }).then((result) => {
    //     if (result.status === 'success') {
    //         ElMessage({
    //             type: 'success',
    //             message: '撤回审批成功',
    //         })
    //         getTableData()
    //     } else {
    //         ElMessage({
    //             type: 'error',
    //             message: '撤回审批失败，' + result.msg
    //         });
    //     }
    // }).catch(() => {
    //     ElMessage({
    //         type: 'info',
    //         message: '已取消提交',
    //     })
    // })
}

const handleDetail = (row) => {
    // if (row.workId === null) {
    //     ElMessage({
    //         type: 'info',
    //         message: '无法查看',
    //     })
    // } else {

    //     sessionStorage.setItem('workflowQuery', JSON.stringify({
    //         flowId: flowId.value,
    //         workId: row.workId,
    //         trackId: row.trackId,
    //         date: new Date().getTime()
    //     }))

    //     proxy.$router.push({
    //         path: '/workflow/detail',
    //     })

    // }
}


/**
 *   查询 —— 采购订单行
 */
const queryLine = ref({
    planNo: ''
})

const readonlyLine = ref(false)
const activeNameBottom = ref('first')
const tableDataLine = ref([])
const loadingLine = ref(false)
const DoubleClick = (row) => {
    form.value = { ...row }
    readonlyLine.value = row.workId === '' || row.workModel.opType === '1'
    queryLine.value.planNo = row.planNo
    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',
            planNo: 'PLAN001', // 与 tableData 中的生产计划关联
            planLn: '0001',
            planNm: '生产计划A',
            itemCd: '10101012351', // 物料编码
            itemNm: 'M2矿',   // 物料名称
            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',
            purFlag: '0',
            transQeqFlag: '0',
            materialFlag: '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: '',
    itemCd: '',
    itemNm: '',
    qty: '',
    uom: '',
    taxPrice: '',
    totalAmount: '',
    taxRate: '',
    planNo: '',
    planLn: '',
    planNm: '',
    demandDt: '',
    remark: '',
    addId: '',
    addCode: '',
    addName: '',
    addDeptId: '',
    addDeptCode: '',
    addDeptName: '',
    addTime: '',
    modifyId: '',
    modifyCode: '',
    modifyName: '',
    modifyTime: '',
    cancelId: '',
    cancelCode: '',
    cancelName: '',
})
const ruleFormRefLine = ref()
// 校验
const rulesLine = reactive({
    itemCd: [
        { required: true, message: '不允许为空', trigger: 'blur' | 'change' },
    ],
    itemNm: [
        { required: true, message: '不允许为空', trigger: 'blur' | 'change' },
    ],
    qty: [
        { required: true, message: '不允许为空', trigger: 'blur' | 'change' },
    ],
    uom: [
        { required: true, message: '不允许为空', trigger: 'blur' | 'change' },
    ],
    taxPrice: [
        { required: true, message: '不允许为空', trigger: 'blur' | 'change' },
    ],
    totalAmount: [
        { required: true, message: '不允许为空', trigger: 'blur' | 'change' },
    ],
    taxRate: [
        { required: true, message: '不允许为空', trigger: 'blur' | 'change' },
    ],
    planNm: [
        { required: true, message: '不允许为空', trigger: 'blur' | 'change' },
    ],
    demandDt: [
        { required: true, message: '不允许为空', trigger: 'blur' | 'change' },
    ],
    addName: [
        { required: true, message: '不允许为空', trigger: 'blur' | 'change' },
    ],
    addDeptName: [
        { 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(!readonlyLine.value) {
        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: '',
        planNo: form.value.planNo,
        planLn: '',
        planNm: form.value.planNm,
        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()
    }

    tableDataLine.value.push(formLine.value)

}
/**
 * 新增
 */


/**
* 物料
*/
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.planNo = row.planNo
    //         getTableDataLine()
    //     } else {
    //         ElMessage({
    //             message: '操作失败' + response.data.msg,
    //             type: 'error'
    //         })
    //     }
    // })
}

const handleCancelSaveLine = (row) => {
    if(row.id !== '') {
        row.cancelFlag = '0'
    } else {
        tableDataLine.value.pop(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.planNo = row.planNo
    //             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 ImportExcelRef = ref(null)
const importUrl = ref('pur/OrdLine/importExcel')
const formData = ref({
    fId: 'purDemandPlan',
    userId: userId
})
const handleImport = () => {
    ImportExcelRef.value.open()
}
const importSuccess = () => {
    handleSearch()
}

</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>
