<template>
    <div class="container">
        <!-- 顶部信息 -->
        <div class="containertop">
            <div class="topleft">
                <img src="../../../assets/images/detailsicon/1.png" alt="">
                <span>项目备忘录</span>
            </div>
            <div class="topright">
                <el-button type="primary" size="medium" plain
                    style="border: none;background-color: rgba(43,98,241,0.1);color: #2B62F1;" @click="handleAdd">
                    <img src="../../../assets/images/detailsicon/icon-xz@2x.png" alt="新增"
                        style="width: 0.6rem; height: 0.6rem; margin-right: 4px;">
                    新增
                </el-button>
            </div>
        </div>
        <div class="content">
            <div class="descriptionsdiv">
                <el-form :model="form" @submit.native.prevent="onSubmit">
                    <el-form-item>
                        <el-col :span="11">
                            <el-date-picker type="date" placeholder="选择日期" v-model="form.date1"
                                @change="handleDateChange" style="width: 21.75rem;"
                                value-format="yyyy-MM-dd"></el-date-picker>
                        </el-col>
                    </el-form-item>
                </el-form>
            </div>
            <div class="descriptionsdivnext">
                <!-- 渲染多个备忘录 -->
                <div v-for="memo in memos" :key="memo.id" class="descriptionditem">
                    <div class="itemone">{{ memo.createTime }}</div>
                    <div class="itemtwo">{{ memo.remark }}</div>
                    <div class="itemthree">记录人：{{ memo.createBy }}</div>
                    <div class="iconguanbi" @click="handleDeleteMemo(memo.id)"> <img
                            src="../../../assets/images/icon-关闭-项目备忘录@2x.png" alt=""></div>
                    <div class="iconguanbi2" @click="handleEditMemo(memo)"> <img
                            src="../../../assets/images/detailsicon/icon-bj@2x.png" alt=""></div>
                </div>
                <div v-if="memos.length === 0" class="no-data"
                    style="width: 100%; display: flex;align-items: center;justify-content: center;color: gray;">
                    暂无数据
                </div>
            </div>
        </div>

        <!-- 新增/编辑弹窗表单 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
            <el-form :model="newMemo" label-width="100px">
                <el-form-item label="姓名">
                    <el-input v-model="newMemo.createBy" disabled></el-input>
                </el-form-item>
                <el-form-item label="备忘时间">
                    <el-date-picker type="date" placeholder="选择日期" v-model="newMemo.createTime" disabled
                        style="width: 21.75rem;"></el-date-picker>
                </el-form-item>
                <el-form-item label="关键/主题字">
                    <el-input type="textarea" v-model="newMemo.remark" :rows="4"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { addxmmmb, deletexmmmb, updateProjectRemark, getxmmmbPage } from '@/api/ManageApi/index';

export default {
    props: {
        xmId: {
            type: Number,
            required: true
        }
    },
    data() {
        return {
            form: {
                date1: null,
            },
            dialogVisible: false,
            dialogTitle: '新增备忘录',
            newMemo: {
                id: 0,
                remark: '',
                xmId: this.xmId,
                createTime: '',
                createBy: '',
            },
            memos: [],
            date1: null,
        };
    },
    created() {
        this.fetchMemos();
    },
    methods: {
        onSubmit() {
            console.log('submit!');
            console.log(this.form);
        },
        handleDateChange(date) {
            if (date) {
                this.fetchMemosByDate(date);
            } else {
                // 如果清空日期选择，则查询全部
                this.fetchMemos();
            }
        },

        // 根据日期查询备忘录
        fetchMemosByDate(date) {
            const params = {
                xmId: this.xmId,
                startTime: date,
            };

            getxmmmbPage(params)
                .then(response => {
                    if (response.code === 200) {
                        this.memos = response.data || [];
                    } else {
                        this.$message.error(response.msg || '查询失败');
                    }
                })
                .catch(error => {
                    console.error("查询失败:", error);
                    this.$message.error('查询失败');
                });
        },
        // 原有的fetchMemos方法修改为查询全部
        fetchMemos() {
            const params = {
                xmId: this.xmId
            };
            getxmmmbPage(params)
                .then(response => {
                    if (response.code === 200) {
                        this.memos = response.data || [];
                    } else {
                        this.$message.error(response.msg || '查询失败');
                    }
                })
                .catch(error => {
                    console.error("查询失败:", error);
                    this.$message.error('查询失败');
                });
        },
        // 获取当前用户ID（Vuex中）
        getCurrentUserId() {
            return this.$store.state.user.id || 0;
        },
        // 打开新增弹窗
        handleAdd() {
            this.dialogTitle = '新增备忘录';
            this.dialogVisible = true;
            const now = new Date();
            this.newMemo = {
                id: 0,
                remark: '',
                xmId: this.xmId,
                createTime: now.toISOString().replace('T', ' ').substring(0, 19),
                createBy: this.getCurrentUserName(),
                createId: this.getCurrentUserId(),
                updateTime: now.toISOString().replace('T', ' ').substring(0, 19),
                updateBy: this.getCurrentUserName(),
                updateId: this.getCurrentUserId()
            };
        },

        // 打开编辑弹窗
        handleEditMemo(memo) {
            if (memo) {
                this.dialogTitle = '编辑备忘录';
                this.dialogVisible = true;
                const now = new Date();
                this.newMemo = {
                    ...memo, // 保留原有字段
                    updateTime: now.toISOString().replace('T', ' ').substring(0, 19),
                    updateBy: this.getCurrentUserName(),
                    updateId: this.getCurrentUserId()
                };
            }
        },
        // 删除备忘录
        handleDeleteMemo(id) {
            this.$confirm('确认删除该备忘录？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                deletexmmmb([id])
                    .then(response => {
                        if (response.code === 200) {
                            this.$message.success('删除成功！');
                            this.fetchMemos(); // 刷新列表
                        } else {
                            this.$message.error('删除失败：' + (response.msg || '未知错误'));
                        }
                    })
                    .catch(error => {
                        console.error('删除失败:', error.response?.data || error.message);
                        this.$message.error('删除失败！');
                    });
            }).catch(() => {
                this.$message.info('已取消删除');
            });
        },
        // 提交表单（新增/编辑）
        handleSubmit() {
            console.log('提交的数据:', JSON.stringify(this.newMemo, null, 2));
            this.dialogVisible = false;

            if (this.newMemo.id && this.newMemo.id !== 0) {
                // 编辑数据
                updateProjectRemark(this.newMemo)
                    .then(response => {
                        if (response.code === 200) {
                            this.$message.success('备忘录更新成功！');
                            this.fetchMemos();
                        } else {
                            this.$message.error(response.msg || '更新失败');
                        }
                    })
                    .catch(error => {
                        console.error('更新失败:', error);
                        this.$message.error('更新失败');
                    });
            } else {
                // 新增数据
                addxmmmb(this.newMemo)
                    .then(response => {
                        if (response.code === 200) {
                            this.$message.success('备忘录添加成功！');
                            this.fetchMemos();
                        } else {
                            this.$message.error(response.msg || '添加失败');
                        }
                    })
                    .catch(error => {
                        console.error('添加失败:', error);
                        this.$message.error('添加失败');
                    });
            }
        },
        // 获取当前账号的名称
        getCurrentUserName() {
            // 假设当前账号的名称存储在 Vuex store 中
            return this.$store.state.user.name; // 根据实际情况调整
        },
    },
};
</script>

<style scoped>
.container {
    display: flex;
    flex-direction: column;
    width: 100%;
    background-color: #FFFFFF;
    box-shadow: 0rem 0.13rem 0.63rem 0rem rgba(177, 177, 177, 0.1);
    border-radius: 0.5rem 0.5rem 0.5rem 0.5rem;
    gap: 1rem;
}

.content {
    padding: 1rem;
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.containertop {
    height: auto;
    display: flex;
    justify-content: space-between;
    padding: .7rem 0;
    border-bottom: 1px solid #E5E5E5;
    padding: .5rem;
}

.topleft {
    width: 8rem;
    display: flex;
    gap: 0.4rem;
    align-items: center;
}

.topleft img {
    width: 0.81rem;
    height: 0.81rem;
}

.topleft span {
    width: auto;
    height: 0.88rem;
    font-family: AlibabaPuHuiTi, AlibabaPuHuiTi;
    font-weight: 500;
    font-size: 0.88rem;
    color: #3D424C;
    line-height: 0.88rem;
    text-align: right;
    font-style: normal;
    text-transform: none;
}

.descriptionsdiv {
    width: 100%;
    margin-left: 0rem;
    height: auto;
}

.el-tag+.el-tag {
    margin-left: 10px;
}

.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}

.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}

.descriptionsdivnext {
    display: flex;
    height: 8rem;
    margin-top: -1rem;
    gap: 1rem;
    flex-wrap: wrap;
}

.descriptionditem {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
    width: 21.75rem;
    height: auto;
    background: #FBFCFF;
    border-radius: 0.25rem 0.25rem 0.25rem 0.25rem;
    border: 0.06rem solid #E6E6E6;
    padding: .5rem;
    position: relative;
    gap: 1rem;
}

.itemone {
    width: 100%;
    height: 0.88rem;
    font-family: AlibabaPuHuiTi, AlibabaPuHuiTi;
    font-weight: 500;
    font-size: 0.88rem;
    color: #3D424C;
    line-height: 0.88rem;
    font-style: normal;
    text-transform: none;
}

.itemtwo {
    width: 100%;
    height: 2rem;
    font-family: AlibabaPuHuiTi, AlibabaPuHuiTi;
    font-weight: 400;
    font-size: 0.88rem;
    color: #3D424C;
    line-height: 0.88rem;
    font-style: normal;
    text-transform: none;
    margin-top: .5rem;
}

.itemthree {
    width: 100%;
    height: 0.88rem;
    font-family: AlibabaPuHuiTi, AlibabaPuHuiTi;
    font-weight: 400;
    font-size: 0.88rem;
    color: #808080;
    line-height: 0.88rem;
    font-style: normal;
    text-transform: none;
}

.itemfour {
    position: absolute;
    bottom: 0.5rem;
    right: 0.5rem;
}

.el-textarea__inner {
    height: 10rem !important;
    /* 固定高度 */
    resize: none;
    /* 禁止调整大小 */
}

.iconguanbi {
    position: absolute;
    top: 0;
    right: 0;
}

.iconguanbi2 {
    position: absolute;
    top: 1rem;
    right: 1rem;
    width: 2rem;
    height: 2rem;
    background-color: rgba(43, 98, 241, 0.1);
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.iconguanbi2 img {
    width: 1.2rem;
    height: 1.2rem;
}

.iconguanbi img {
    width: 1.4rem;
    height: 1.4rem;
}
</style>