<template>
    <div class="p-5">
        <el-card class="mb-5">
            <el-button type="primary" icon="Plus" @click="handleAdd"
                class="transition-all duration-200 hover:shadow-md">
                新增
            </el-button>
            <el-button icon="Refresh" @click="refreshData" class="transition-all duration-200 hover:shadow-md">
                刷新
            </el-button>
        </el-card>
        <!-- 数据表格 -->
        <div class="bg-white rounded-lg shadow-sm overflow-hidden transition-all duration-300 hover:shadow-md">
            <el-table v-loading="loading2" :data="tableData" stripe
                :header-cell-style="{ 'background-color': '#f5f7fa', 'font-weight': 'bold' }"
                style="width: 100%; margin-bottom: 20px; height: calc(100vh - 305px)"
                :row-class-name="tableRowClassName">
                <!-- 基础信息列 -->
                <el-table-column prop="id" label="ID" width="180" align="center"></el-table-column>
                <el-table-column prop="batch" label="批次" align="center"></el-table-column>
                <el-table-column prop="physicalsupplyId" label="使用情况ID" width="180" align="center"></el-table-column>
                <!-- 时间相关列 -->
                <el-table-column prop="issuanceTime" label="联系单下达时间" min-width="160" align="center">
                    <template #default="scope">
                        {{ formatDate(scope.row.issuanceTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="requireDelivery" label="要求到货时间" min-width="160" align="center">
                    <template #default="scope">
                        {{ formatDate(scope.row.requireDelivery) }}
                    </template>
                </el-table-column>
                <el-table-column prop="scheduledDelivery" label="计划到货时间" min-width="160" align="center">
                    <template #default="scope">
                        {{ formatDate(scope.row.scheduledDelivery) }}
                    </template>
                </el-table-column>
                <el-table-column prop="actualDelivery" label="实际到货时间" min-width="160" align="center">
                    <template #default="scope">
                        {{ formatDate(scope.row.actualDelivery) }}
                    </template>
                </el-table-column>
                <el-table-column prop="acceptanceCheck" label="验收移交时间" min-width="160" align="center">
                    <template #default="scope">
                        {{ formatDate(scope.row.acceptanceCheck) }}
                    </template>
                </el-table-column>

                <!-- 数量相关列 -->
                <el-table-column prop="requiredQuantity" label="要求到货数量" min-width="120" align="right"></el-table-column>
                <el-table-column prop="plannedQuantity" label="计划到货数量" min-width="120" align="right"></el-table-column>
                <el-table-column prop="actualAcceptance" label="实际验收数量" min-width="120" align="right"></el-table-column>
                <el-table-column prop="differenceQuantity" label="差异量" min-width="100" align="right">
                    <template #default="scope">
                        <span
                            :class="scope.row.differenceQuantity && parseFloat(scope.row.differenceQuantity) !== 0 ? 'text-red-500' : ''">
                            {{ scope.row.differenceQuantity || '-' }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="dhDifferenceQuantity" label="到货差异量" min-width="120"
                    align="right"></el-table-column>

                <!-- 金额相关列 -->
                <el-table-column prop="cargoAmount" label="货物金额" min-width="120" align="right">
                    <template #default="scope">
                        {{ scope.row.cargoAmount }}
                    </template>
                </el-table-column>
                <el-table-column prop="advance" label="预付款" min-width="100" align="right">
                    <template #default="scope">
                        {{ scope.row.advance }}
                    </template>
                </el-table-column>
                <el-table-column prop="feed" label="投料款" min-width="100" align="right">
                    <template #default="scope">
                        {{ scope.row.feed }}
                    </template>
                </el-table-column>
                <el-table-column prop="acceptancePayment" label="到货验收款" min-width="120" align="right">
                    <template #default="scope">
                        {{ scope.row.acceptancePayment }}
                    </template>
                </el-table-column>
                <el-table-column prop="debugging" label="调试款" min-width="100" align="right">
                    <template #default="scope">
                        {{ scope.row.debugging }}
                    </template>
                </el-table-column>
                <el-table-column prop="qualityGuarantee" label="质保金" min-width="100" align="right">
                    <template #default="scope">
                        {{ scope.row.qualityGuarantee }}
                    </template>
                </el-table-column>
                <el-table-column prop="settlementAmount" label="结算金额" min-width="120" align="right">
                    <template #default="scope">
                        {{ scope.row.settlementAmount }}
                    </template>
                </el-table-column>

                <!-- 状态和备注列 -->
                <el-table-column prop="expectedState" label="逾期状态" min-width="100" align="center">
                    <template #default="scope">
                        <!-- :type="getTagType(scope.row.expectedState)" -->
                        <el-tag :effect="scope.row.expectedState ? 'dark' : 'plain'">
                            {{ scope.row.expectedState || '-' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="associate" label="交接方式" min-width="120"></el-table-column>
                <el-table-column prop="deliveryRequirements" label="到货要求" min-width="150"></el-table-column>
                <el-table-column prop="transition" label="转换为合同" min-width="120" align="center">
                    <!-- <template #default="scope"> -->
                    <!-- <el-switch v-model="scope.row.transition" active-value="是" inactive-value="否"
                                                @change="handleTransitionChange(scope.row)"></el-switch> -->
                    <!-- </template> -->
                </el-table-column>

                <!-- 备注信息列（可展开） -->
                <el-table-column label="备注信息" min-width="120">
                    <template #default="scope">
                        <el-popover placement="top" width="300" trigger="click">
                            <template #reference>
                                <el-button size="small" type="text">查看详情</el-button>
                            </template>
                            <div class="space-y-2 text-sm">
                                <p><span class="font-medium">采购备注：</span>{{ scope.row.cgRemark || '-' }}
                                </p>
                                <p><span class="font-medium">到货备注：</span>{{ scope.row.dhRemark || '-' }}
                                </p>
                                <p><span class="font-medium">供应商备注：</span>{{ scope.row.gysRemark || '-'
                                }}</p>
                                <p><span class="font-medium">结算备注：</span>{{ scope.row.jsRemark || '-' }}
                                </p>
                            </div>
                        </el-popover>
                    </template>
                </el-table-column>

                <!-- 操作列 -->
                <el-table-column label="操作" min-width="120" align="center" fixed="right">
                    <template #default="scope">
                        <el-button size="small" icon="Edit" @click="handleEdit2(scope.row)"
                            class="text-blue-600 hover:text-blue-800 transition-colors"></el-button>
                        <el-button size="small" icon="Delete" @click="handleDelete2(scope.row)"
                            class="text-red-600 hover:text-red-800 transition-colors"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="flex flex-wrap items-center justify-between p-4 border-t gap-4">
                <div class="text-gray-500 text-sm">
                    共 {{ total }} 条记录，当前显示第 {{ (currentPage - 1) * pageSize + 1 }} 至 {{
                        Math.min(currentPage * pageSize, total)
                    }} 条
                </div>
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="total" layout="prev, pager, next, jumper, sizes"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" small></el-pagination>
            </div>
        </div>
    </div>
    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible2" title="确认删除" width="300px" :show-close="false">
        <div class="text-center py-4">
            <el-icon class="text-orange-500 text-4xl mb-3">
                <WarningFilled />
            </el-icon>
            <p>确定要删除这条记录吗？</p>
            <p class="text-gray-500 text-sm mt-2">此操作不可撤销，请谨慎操作</p>
        </div>
        <template #footer>
            <div class="flex justify-center gap-2">
                <el-button @click="deleteDialogVisible2 = false">取消</el-button>
                <el-button type="danger" @click="confirmDelete2" :loading="deleteLoading">
                    确认删除
                </el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible2" :title="dialogType2 === 'addSon' ? '新增采购信息' : '编辑采购信息'" :width="dialogWidth"
        :fullscreen="isFullscreen" :close-on-click-modal="false" :before-close="handleClose" destroy-on-close>
        <!-- 表单内容 -->
        <el-form ref="formRef" :model="form" :rules="formRules" label-width="140px" class="space-y-4">
            <!-- 第一行 -->
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="批次" prop="batch">
                        <el-input v-model="form.batch" placeholder="请输入批次信息"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="联系单下达时间" prop="issuanceTime">
                        <el-date-picker v-model="form.issuanceTime" type="datetime" placeholder="选择联系单下达时间"
                            value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 第二行 -->
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="要求到货数量" prop="requiredQuantity">
                        <el-input v-model="form.requiredQuantity" placeholder="请输入要求到货数量"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="要求到货时间" prop="requireDelivery">
                        <el-date-picker v-model="form.requireDelivery" type="datetime" placeholder="选择要求到货时间"
                            value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 第三行 -->
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="计划到货数量" prop="plannedQuantity">
                        <el-input v-model="form.plannedQuantity" placeholder="请输入计划到货数量"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="计划到货时间" prop="scheduledDelivery">
                        <el-date-picker v-model="form.scheduledDelivery" type="datetime" placeholder="选择计划到货时间"
                            value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 第四行 -->
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="实际到货验收数量" prop="actualAcceptance">
                        <el-input v-model="form.actualAcceptance" placeholder="请输入实际到货验收数量"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="实际到货时间" prop="actualDelivery">
                        <el-date-picker v-model="form.actualDelivery" type="datetime" placeholder="选择实际到货时间"
                            value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 第五行 -->
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="差异量" prop="differenceQuantity">
                        <el-input v-model="form.differenceQuantity" placeholder="请输入差异量"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="到货差异量" prop="dhDifferenceQuantity">
                        <el-input v-model="form.dhDifferenceQuantity" placeholder="请输入到货差异量"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 第六行 -->
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="验收移交时间" prop="acceptanceCheck">
                        <el-date-picker v-model="form.acceptanceCheck" type="datetime" placeholder="选择验收移交时间"
                            value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="逾期状态" prop="expectedState">
                        <el-select v-model="form.expectedState" placeholder="请选择逾期状态">
                            <el-option label="未逾期" value="未逾期"></el-option>
                            <el-option label="已逾期" value="已逾期"></el-option>
                            <el-option label="即将逾期" value="即将逾期"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 第七行 - 金额信息 -->
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="货物金额" prop="cargoAmount">
                        <el-input v-model="form.cargoAmount" placeholder="0.00" prefix="¥"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="预付款" prop="advance">
                        <el-input v-model="form.advance" placeholder="0.00" prefix="¥"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="投料款" prop="feed">
                        <el-input v-model="form.feed" placeholder="0.00" prefix="¥"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="到货验收款" prop="acceptancePayment">
                        <el-input v-model="form.acceptancePayment" placeholder="0.00" prefix="¥"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 第八行 - 金额信息 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="调试款" prop="debugging">
                        <el-input v-model="form.debugging" placeholder="0.00" prefix="¥"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="质保金" prop="qualityGuarantee">
                        <el-input v-model="form.qualityGuarantee" placeholder="0.00" prefix="¥"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="结算金额" prop="settlementAmount">
                        <el-input v-model="form.settlementAmount" placeholder="0.00" prefix="¥"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 第九行 -->
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="交接方式" prop="associate">
                        <el-input v-model="form.associate" placeholder="请输入交接方式"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="转换为合同" prop="transition">
                        <el-select v-model="form.transition" placeholder="请选择是否转换为合同">
                            <el-option label="是" value="是"></el-option>
                            <el-option label="否" value="否"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 第十行 -->
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="到货要求" prop="deliveryRequirements">
                        <el-input v-model="form.deliveryRequirements" placeholder="请输入到货要求" type="textarea"
                            rows="3"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 第十一行 - 备注信息 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="采购备注" prop="cgRemark">
                        <el-input v-model="form.cgRemark" placeholder="请输入采购备注" type="textarea" rows="4"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="到货备注" prop="dhRemark">
                        <el-input v-model="form.dhRemark" placeholder="请输入到货备注" type="textarea" rows="4"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="供应商备注" prop="gysRemark">
                        <el-input v-model="form.gysRemark" placeholder="请输入供应商备注" type="textarea" rows="4"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 第十二行 -->
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="结算备注" prop="jsRemark">
                        <el-input v-model="form.jsRemark" placeholder="请输入结算备注" type="textarea" rows="3"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <!-- 底部按钮 -->
        <template #footer>
            <div class="flex justify-end gap-3">
                <el-button @click="handleCancel" class="transition-all duration-200">
                    取消
                </el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitLoading"
                    class="transition-all duration-200">
                    {{ dialogType2 === 'addSon' ? '新增' : '保存' }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, reactive, onMounted, toRaw, getCurrentInstance } from 'vue';
import { materialsUsageDetails, materialsSonAdd, materialsSonDel, materialsSonEdit } from "@/api/materials/usageMaterials/index";
import { routerRename } from '@/api/air';
const { proxy } = getCurrentInstance();
const dialogVisible2 = ref(false);
const dialogType2 = ref('addSon'); // add 或 edit
const deleteDialogVisible2 = ref(false);
const currentRow2 = ref(null);
const tableData = ref([]);
const loading2 = ref(false);
const submitLoading = ref(false);
const routeParams = ref({})
const currentPage = ref(1);
const total = ref(0);
const pageSize = ref(10);
const formRef = ref(null);
const deleteLoading = ref(false);
const tableRowClassName = ({ row, rowIndex }) => {
    return rowIndex % 2 === 0 ? 'bg-white' : 'bg-gray-50';
};
const form = reactive({
    id: '',
    acceptanceCheck: '',
    acceptancePayment: '',
    actualAcceptance: '',
    actualDelivery: '',
    advance: '',
    associate: '',
    batch: '',
    cargoAmount: '',
    cgRemark: '',
    createTime: '',
    debugging: '',
    deliveryRequirements: '',
    dhDifferenceQuantity: '',
    dhRemark: '',
    differenceQuantity: '',
    expectedState: '',
    feed: '',
    gysRemark: '',
    issuanceTime: '',
    jsRemark: '',
    physicalsupplyId: null,
    plannedQuantity: '',
    qualityGuarantee: '',
    requireDelivery: '',
    requiredQuantity: '',
    scheduledDelivery: '',
    settlementAmount: '',
    transition: '',
    updateBy: null,
    updateTime: ''
});
const handleAdd = () => {
    dialogVisible2.value = true;
    dialogType2.value = 'addSon';
    resetForm();
}
const resetForm = () => {
    if (formRef.value) {
        formRef.value.resetFields();
    }

    // 重置表单数据
    Object.keys(form).forEach(key => {
        form[key] = '';
    });

    // 设置默认值
    form.findType = 1;
    form.id = '';
};

const handleEdit2 = (row) => {
    dialogType2.value = 'editSon';
    currentRow2.value = row;
    resetForm();

    // 填充表单数据
    Object.keys(form).forEach(key => {
        if (row.hasOwnProperty(key)) {
            form[key] = row[key];
        }
    });

    dialogVisible2.value = true;
};
const handleDelete2 = (row) => {
    currentRow2.value = row;
    ElMessageBox.confirm(
        '确定要删除这条记录吗？此操作不可撤销，请谨慎操作',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        confirmDelete2();
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除',
        })
    })
};
const confirmDelete2 = async () => {
    if (!currentRow2.value) return;

    deleteLoading.value = true;
    try {
        // 模拟API请求
        const res = await materialsSonDel(currentRow2.value.id)
        const { code } = res;
        if (code === 200) {
            ElMessage.success('删除成功');
            deleteDialogVisible2.value = false;
            materialsUsageDetails1();
        } else {
            ElMessage.error('删除失败');
        }
    } catch (error) {
        ElMessage.error('删除失败：' + error.message);
        console.error(error);
    } finally {
        deleteLoading.value = false;
    }
};
const handleSubmit = async () => {
    if (!formRef.value) return;
    // 表单验证
    const valid = await formRef.value.validate();
    if (!valid) return;

    submitLoading.value = true;

    try {
        // 准备提交的数据
        const submitData = { ...toRaw(form) };

        // 如果是新增，清除id
        if (dialogType2.value === 'addSon') {
            submitData.physicalsupplyId = routeParams.value.id
            const res = await materialsSonAdd(submitData)
            const { code } = res;
            if (code === 200) {
                ElMessage.success('新增成功');
                materialsUsageDetails1();
            }
        } else {
            const res = await materialsSonEdit(submitData)
            const { code } = res;
            if (code === 200) {
                ElMessage.success('保存成功');
                materialsUsageDetails1();
            }
        }
        // 重置表单
        resetForm();
    } catch (error) {
        ElMessage.error(`${dialogType2 === 'addSon' ? '新增' : '保存'}失败: ${error.message}`);
    } finally {
        submitLoading.value = false;
        dialogVisible2.value = false;
    }
};
const materialsUsageDetails1 = () => {
    materialsUsageDetails({ physicalsupplyId: routeParams.value.id }).then(res => {
        tableData.value = res.rows
    })
}
// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    }).replace(',', ' ');
};
function handleCancel() {
    dialogVisible2.value = false;
    currentRow2.value = null;
}
const refreshData = () => {
    materialsUsageDetails1();
    ElMessage.success('数据已刷新');
};
function handleSizeChange() { }
onMounted(() => {
    routeParams.value = proxy.$route.query;
    console.log('routeParams.value', routeParams.value);
    materialsUsageDetails1();
})

</script>