<template>
    <div class="overall-plan-material-supply">
        <!-- tabPosition="left" -->
        <el-card shadow="always">
            <el-form :inline="true">
                <el-form-item>
                    <el-button v-if="state.masterData.status == 'draft'" type="primary" icon="edit" @click="clickApprovalSheet1()">审批</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button v-if="state.masterData.status == 'waiting' || state.masterData.status == 'finish'" icon="view" @click="lookApprovalFlow()" type="warning">查看流程</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-table :data="state.tableData" v-loading="state.loading.list" stripe
            style="width: 100%; margin-bottom: 20px; height: calc(100vh - 230px)" row-key="id" border>
            <el-table-column prop="num" label="编号" />
            <el-table-column prop="name" label="工程或费用名称" />
            <el-table-column prop="unit" label="单位" />
            <el-table-column prop="quantity" label="数量" />
            <el-table-column prop="remark" label="备注" />
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button :disabled="state.masterData.status == 'waiting' || state.masterData.status == 'finish'" type="primary" @click="editApprovalSheet(row)">修改</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 编辑 -->
        <el-dialog v-model="visible" title="修改物料信息" :width="800" :close-on-click-modal="false" @close="handleClose">
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" class="space-y-4">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="批次号" prop="batchNumber">
                            <el-input disabled v-model="formData.batchNumber" placeholder="请输入批次号" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="品牌" prop="brand">
                            <el-input v-model="formData.brand" placeholder="请输入品牌" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 物料属性区域 -->
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="材质" prop="texture">
                            <el-input v-model="formData.texture" placeholder="请输入材质" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="质量标准" prop="qualityStandard">
                            <el-input v-model="formData.qualityStandard" placeholder="请输入质量标准" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 日期与状态区域 -->
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="使用部位" prop="partUsed">
                            <el-input v-model="formData.partUsed" placeholder="请输入使用部位" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="交货地点" prop="deliveryPoints">
                            <el-input v-model="formData.deliveryPoints" placeholder="请输入交货地点" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 其他信息区域 -->
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="预计使用日期" prop="dateService">
                            <el-date-picker v-model="formData.dateService" type="date" placeholder="选择预计使用日期"
                                format="YYYY-MM-DD" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.remark" placeholder="请输入备注信息" type="textarea" rows="3" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="billofQuantities">
import { ref, reactive, onMounted, computed, getCurrentInstance } from 'vue';
import { obtainMasterDataList, totalsupplyplan, totalSupplyplanDetails, materialChangeSupplyplan } from '@/api/materials/overallPlanMaterialSupply/index';
import { useUserStoreHook } from '@/store/modules/user';
import { edit } from '@/api/workflow/definition';
const userStore = useUserStoreHook();
const currentProject = computed(() => userStore.selectedProject);
const { proxy } = getCurrentInstance();
const visible = ref(false);
const formRef = ref(null);
const state = reactive({
    tableData: [],
    queryForm: {
        projectId: currentProject.value?.id,
        versions: '',
        sheet: '',
        pageSize: 20,
        pageNum: 1
    },
    loading: {
        versions: false,
        sheets: false,
        list: false
    },
    // 主id
    masterData: {}
    
});
// 表单数据
const formData = reactive({
    batchNumber: '',
    brand: '',
    compileDate: '',
    dateService: '',
    deliveryPoints: '',
    id: undefined,
    name: '',
    num: '',
    partUsed: '',
    planNumber: '',
    projectId: undefined,
    qualityStandard: '',
    quantity: 0,
    remark: '',
    specification: '',
    status: '',
    texture: '',
    unit: ''
});
// 表单验证规则
const formRules = reactive({
    name: [
        { required: true, message: '请输入名称', trigger: 'blur' },
        { max: 100, message: '名称长度不能超过100个字符', trigger: 'blur' }
    ],
    num: [
        { required: true, message: '请输入编号', trigger: 'blur' },
        { max: 50, message: '编号长度不能超过50个字符', trigger: 'blur' }
    ],
    quantity: [
        { required: true, message: '请输入数量', trigger: 'blur' },
        { type: 'number', min: 0, message: '数量不能为负数', trigger: 'blur' }
    ],
    compileDate: [
        { required: true, message: '请选择编制日期', trigger: 'change' }
    ]
});
// 获取主表数据
async function getMasterDataList() {
    try {
        // 获取主数据列表
        state.loading.list = true;
        const masterDataRes = await obtainMasterDataList({
            projectId: currentProject.value?.id
        });

        const { data: masterData } = masterDataRes;
        console.log('masterData', masterData);

        if (!masterData[0].id) {
            console.warn('未获取到有效的主数据ID');
            state.tableData = [];
            return;
        }
        state.masterData = masterData[0];

        // 获取供应计划
        const supplyPlanRes = await totalsupplyplan({ id: masterData[0].id });

        // 处理结果
        if (supplyPlanRes.list == null) {
            state.tableData = supplyPlanRes.rows || [];
            console.log('state.tableData', state.tableData);
        } else {
            // 根据实际业务逻辑处理有list的情况
            state.tableData = [];
        }

    } catch (error) {
        console.error('获取主数据列表失败:', error);
        // 错误情况下给默认值，避免页面出错
        state.tableData = [];
    } finally {
        state.loading.list = false;
    }
}
// 获取详情
// 修改获取详情的方法
async function totalSupplyplanDetail(id) {
    try {
        const result = await totalSupplyplanDetails(id);
        if (result?.code === 200) {
            const detailData = result.data || {};
            // 1. 清空原有表单数据
            Object.keys(formData).forEach(key => {
                formData[key] = undefined;
            });
            // 2. 处理日期格式（假设接口返回的是Date对象或ISO字符串）
            const formatDate = (date) => {
                if (!date) return '';
                // 若为字符串，先转为Date对象
                const d = typeof date === 'string' ? new Date(date) : date;
                return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
            };
            // 3. 合并数据到formData（响应式赋值）
            Object.assign(formData, {
                ...detailData,
                // 单独处理日期字段，转为表单可识别的字符串格式
                compileDate: formatDate(detailData.compileDate),
                dateService: formatDate(detailData.dateService)
            });
            console.log('表单数据已更新:', formData);
        } else {
            ElMessage.error(`获取详情失败: ${result?.msg || '未知错误'}`);
        }
    } catch (err) {
        ElMessage.error(`接口请求失败: ${err.message}`);
        console.error('详情接口错误:', err);
    } finally {
        state.loading.list = false;
    }
}
// 修改
function editApprovalSheet(row) {
    console.log(row);
    totalSupplyplanDetail(row.id)
    visible.value = true;
}
// 提交表单
const handleSubmit = async () => {
    try {
        // 表单验证
        await formRef.value.validate();
        // 触发提交事件
        console.log('submitData:', formData);
        editMaterialSupply(formData);
        handleClose();
    } catch (error) {
        // 验证失败不提交
        console.error('表单验证失败:', error);
        return;
    }
};
// 修改物资
function editMaterialSupply(formData) {
    materialChangeSupplyplan(formData).then(res => {
        if (res.code === 200) {
            ElMessage.success('修改成功');
        } else {
            ElMessage.error('修改失败');
        }
    });
}

// 关闭弹窗
const handleClose = () => {
    visible.value = false;
    // 清空表单数据
    Object.keys(formData).forEach(key => {
        formData[key] = undefined;
    });
    // 重置表单验证状态
    formRef.value?.resetFields();
};

// 审批
function clickApprovalSheet1() {
    proxy.$tab.closePage(proxy.$route);
    proxy.$router.push({
        path: `/materials/overallPlanMaterialSupply/indexEdit`,
        query: {
            id: state.masterData.id,
            type: 'update'
        }
    });
}
// 审核流程
function lookApprovalFlow() {
    proxy.$router.push({
        path: `/materials/overallPlanMaterialSupply/indexEdit`,
        query: {
            id: state.masterData.id,
            type: 'view'
        }
    });
}
onMounted(() => {
    getMasterDataList();
})
</script>
<style>
.overall-plan-material-supply {
    padding: 20px;
}

.space-y-4>.el-row {
    margin-bottom: 16px;
}

.space-y-4>.el-row:last-child {
    margin-bottom: 0;
}
</style>
