<template>
    <div style=" width:100%;">
        <el-card style="max-width: 100vw;">
            <template #header><strong>子模块{{ projectId }}</strong></template>
        </el-card>

        <el-card class="card">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-row v-for="item in projectItems" :key="item.label">
                        <el-col :span="24">
                            <div style="margin-top: 10%;"><strong>{{ item.label }}</strong></div>
                        </el-col>
                    </el-row>
                </el-col>
                <el-col :span="12">
                    <el-row v-for="item in projectItems" :key="item.label">
                        <el-col :span="24">
                            <div v-if="item.label !== '07.简介'" style="margin-top: 11%;">
                                <template v-if="editMode">
                                    <input v-model="item.value" />
                                </template>
                                <template v-else>
                                    {{ item.value }}
                                </template>
                            </div>
                            <textarea v-if="item.label === '07.简介'" style="resize: none; margin-top: 15%; width: 100%;"
                                v-model="item.value" :disabled="!editMode" rows="4" cols="50">
                    </textarea>
                        </el-col>
                    </el-row>
                </el-col>
            </el-row>
        </el-card>
        <div style="display: flex; justify-content: center;">
            <el-button @click="toggleEditMode" :type="editMode ? 'success' : 'primary'" style="width:80px">
                {{ editMode ? '保存' : '编辑' }}
            </el-button>
            <el-button style="width:80px ;background-color: #bd3124;color: azure;" @click="deleteModuleClick">删除</el-button>
        </div>

        <el-alert>
            <router-view />
        </el-alert>
    </div>
</template>


<script lang="ts" setup>

import { ref } from 'vue';
import { useRoute } from 'vue-router';
import { getProjectModDetail, editModule, deleteModule } from '@/api/manage';
import { getToken } from '@/utils/auth';
import { ElMessage, ElMessageBox } from 'element-plus';


const projectItems = ref([
    { label: '01.模块名称', value: '项目名称1' },
    { label: '02.模块周期', value: '3个月' },
    { label: '03.工作量', value: '100小时' },
    { label: '04.负责人ID', value: '张三' },
    { label: '05.状态', value: '进行中' },
    { label: '06.时间', value: '2024-01-01 12:00:00' },
    { label: '07.简介', value: '大王iu大概iudg拍高端屁股的怕耽搁u对爬过文档爬过无' },
]);

const editMode = ref(false); // 编辑模式状态




//获取id
const route = useRoute();
const projectId = Number(route.query.id);



//加载数据
//修改表单内数据
const parseData = (data) => {


    projectItems.value.forEach(item => {
        if (item.label === '01.模块名称') {
            item.value = data.name;
        } else if (item.label === '02.模块周期') {
            item.value = data.cycle;
        } else if (item.label === '03.工作量') {
            item.value = data.workLoad ;
        } else if (item.label === '04.负责人ID') {
            item.value = "1";
        } else if (item.label === '05.状态') {
            item.value = data.status.toString();
        } else if (item.label === '06.时间') {
            item.value = new Date(data.deadLine).toLocaleDateString();
        } else if (item.label === '07.简介') {
            item.value = data.description;
        }
    })
}

//获取数据方法
const fetchData = async () => {
    const res = await getProjectModDetail(projectId, getToken());
    console.log(res.data);
    if (res.data.data) {
        parseData(res.data.data); // 解析数据
        ElMessage.success('加载成功!');
    }
};

const saveData = async () => {
    // 创建提交给后端的数据对象
    let payload = {
        name: '',
        description: '',
        principalId: '', // 需要一种方式来映射或转换为ID
        workLoad: '',
        cycle: '',
        completeTime: '',
        status: '',
        deadLine: ''
    };

    const formatDate = (dateStr) => {
        const date = new Date(dateStr);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，所以需要+1
        const day = date.getDate().toString().padStart(2, '0');
        return `${year}-${month}-${day}`;
    };

    projectItems.value.forEach(item => {
        switch (item.label) {
            case '01.模块名称':
                payload.name = item.value;
                break;
            case '02.模块周期':
                payload.cycle = item.value.toString();
                break;
            case '03.工作量':
                payload.workLoad = item.value.toString();
                break;
            case '04.负责人':
                payload.principalId = item.value; // 假设这里的值已经是ID，或者需要其他逻辑处理为ID
                break;
            case '05.状态':
                payload.status = item.value.toString();
                break;
            case '06.时间':
                payload.completeTime = formatDate(item.value);
                payload.deadLine = formatDate(item.value); // 如果deadLine和completeTime相同
                break;
            case '07.简介':
                payload.description = item.value;
                break;
        }
    });

  



    console.log(payload);

    const res = editModule(payload, projectId, getToken());
    res.then(response => {
        if (response.data.code === 200) {
            ElMessage.success('保存成功!');
            fetchData(); // 刷新页面数据
        } else {
            ElMessage.error('保存失败!');
        }
    }).catch(error => {
        ElMessage.error('保存失败!'+error);
    });



};


const toggleEditMode = () => {
    if (editMode.value) {
        saveData(); // 如果当前处于编辑模式，调用 saveData 函数保存数据
    }

    editMode.value = !editMode.value; // 切换编辑模式的状态
};

fetchData();

//删除模块
const deleteModuleClick = () => {
    //确认删除吗

    const confirm = ElMessageBox.confirm('确认删除吗？');
    confirm.then(() => {
        const res = deleteModule(projectId, getToken());
        console.log(res);
        
        res.then(response => {
            if (response.data.code === 200) {
                ElMessage.success('删除成功!');
                //返回上一级页面
                window.history.go(-1);
            } else if(response.data.code === 40019) {
                ElMessage.error('删除失败!没有权限');
            }else{
                ElMessage.error('删除失败!');
            }
        }).catch(error => {
            ElMessage.error('删除失败!'+error);
        });
    }).catch(() => {
        //取消删除
    });
}









</script>
<style>
.my-autocomplete li {
    line-height: normal;
    padding: 7px;
}

.my-autocomplete li .name {
    text-overflow: ellipsis;
    overflow: hidden;
}

.my-autocomplete li .addr {
    font-size: 12px;
    color: #b4b4b4;
}

.my-autocomplete li .highlighted .addr {
    color: #ddd;
}

.card {
    width: 28%;
    margin-left: 50%;
    transform: translateX(-50%);
}
</style>