<template>
    <el-dialog title="学习记录管理" :visible.sync="visible" width="1200px" @close="closeDialog">
        <div class="study-record-container">
            <!-- 搜索区域 -->
            <div class="search-section">
                <el-form :model="query" :inline="true" class="search-form">
                    <el-form-item label="学员姓名">
                        <el-input v-model="query.employeeName" placeholder="请输入学员姓名" clearable size="small" />
                    </el-form-item>
                    <el-form-item label="员工ID">
                        <el-input v-model="query.employeeId" placeholder="请输入员工ID" clearable size="small" />
                    </el-form-item>
                    <el-form-item label="学习类型">
                        <el-input v-model="query.studyType" placeholder="请输入学习类型" clearable size="small" />
                    </el-form-item>
                    <el-form-item label="学习日期">
                        <el-date-picker v-model="query.studyDateRange" type="daterange" range-separator="至"
                            start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" size="small">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="日常状态">
                        <el-input v-model="query.dailyStatus" placeholder="请输入日常状态" clearable size="small" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" size="small" @click="search">搜索</el-button>
                        <el-button size="small" @click="reset">重置</el-button>
                        <el-button type="success" size="small" icon="el-icon-plus" @click="addRecord">添加记录</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 学习记录列表 -->
            <div class="table-section">
                <el-table :data="recordList" v-loading="loading" border stripe style="width: 100%">
                    <el-table-column prop="employeeName" label="学员姓名" width="100" fixed="left" />
                    <el-table-column prop="employeeId" label="员工ID" width="120" />
                    <el-table-column prop="studyType" label="学习类型" width="120" />
                    <el-table-column prop="transportFee" label="交通费" width="100" align="center">
                        <template slot-scope="scope">
                            {{ formatMoney(scope.row.transportFee) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="studyDate" label="学习日期" width="120">
                        <template slot-scope="scope">
                            {{ scope.row.studyDate | dateFormat }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="dailyStatus" label="日常状态" width="120" />
                    <el-table-column prop="remark" label="备注" show-overflow-tooltip />
                    <el-table-column prop="isStoreAssist" label="下店协助" width="100" align="center">
                        <template slot-scope="scope">
                            <el-tag :type="scope.row.isStoreAssist === 1 ? 'success' : 'info'" size="mini">
                                {{ scope.row.isStoreAssist === 1 ? '是' : '否' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="storeName" label="协助门店" width="120" />
                    <el-table-column prop="createUserName" label="创建人" width="100" />
                    <el-table-column prop="createTime" label="创建时间" width="160">
                        <template slot-scope="scope">
                            {{ scope.row.createTime | dateTimeFormat }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120" fixed="right">
                        <template slot-scope="scope">
                            <el-button type="text" size="small" @click="cancelRecord(scope.row)">作废</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="pagination-section">
                    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :current-page="pagination.pageIndex" :page-sizes="[10, 20, 50, 100]"
                        :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper"
                        :total="pagination.total">
                    </el-pagination>
                </div>
            </div>
        </div>

        <div slot="footer" class="dialog-footer">
            <el-button @click="closeDialog">关闭</el-button>
        </div>

        <!-- 添加学习记录弹窗 -->
        <el-dialog title="添加学习记录" :visible.sync="addRecordVisible" width="600px" append-to-body>
            <el-form ref="recordForm" :model="recordForm" :rules="recordRules" label-width="100px">
                <el-form-item label="学员姓名" prop="employeeName">
                    <el-input v-model="recordForm.employeeName" placeholder="请输入学员姓名" />
                </el-form-item>
                <el-form-item label="员工ID" prop="employeeId">
                    <el-input v-model="recordForm.employeeId" placeholder="请输入员工ID" />
                </el-form-item>
                <el-form-item label="学习类型" prop="studyType">
                    <el-input v-model="recordForm.studyType" placeholder="请输入学习类型" />
                </el-form-item>
                <el-form-item label="交通费">
                    <el-input-number v-model="recordForm.transportFee" :min="0" :precision="2" style="width: 100%" />
                </el-form-item>
                <el-form-item label="学习日期" prop="studyDate">
                    <el-date-picker v-model="recordForm.studyDate" type="date" placeholder="选择学习日期"
                        value-format="yyyy-MM-dd" style="width: 100%">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="日常状态" prop="dailyStatus">
                    <el-input v-model="recordForm.dailyStatus" placeholder="请输入日常状态" />
                </el-form-item>
                <el-form-item label="是否下店协助">
                    <el-switch v-model="recordForm.isStoreAssist" :active-value="1" :inactive-value="0" />
                </el-form-item>
                <el-form-item v-if="recordForm.isStoreAssist === 1" label="门店ID" prop="storeId">
                    <el-input v-model="recordForm.storeId" placeholder="请输入门店ID" />
                </el-form-item>
                <el-form-item v-if="recordForm.isStoreAssist === 1" label="门店名称" prop="storeName">
                    <el-input v-model="recordForm.storeName" placeholder="请输入门店名称" />
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="recordForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addRecordVisible = false">取消</el-button>
                <el-button type="primary" @click="submitRecord" :loading="submitLoading">确定</el-button>
            </div>
        </el-dialog>
    </el-dialog>
</template>

<script>
import { getStudyRecordList, addStudyRecord, cancelStudyRecord, getStudentListByClassId } from '@/api/extend/lqStudyClass'

export default {
    name: 'StudyRecordDialog',
    data() {
        return {
            visible: false,
            loading: false,
            submitLoading: false,
            addRecordVisible: false,
            classId: '',
            className: '',
            studentIds: [], // 班级学员ID列表
            recordList: [],
            query: {
                employeeName: '',
                employeeId: '',
                studyType: '',
                studyDateStart: '',
                studyDateEnd: '',
                dailyStatus: '',
                studyDateRange: []
            },
            pagination: {
                pageIndex: 1,
                pageSize: 20,
                total: 0
            },
            recordForm: {
                employeeName: '',
                employeeId: '',
                studyType: '',
                transportFee: 0,
                studyDate: '',
                dailyStatus: '',
                remark: '',
                isStoreAssist: 0,
                storeId: '',
                storeName: ''
            },
            recordRules: {
                employeeName: [
                    { required: true, message: '请输入学员姓名', trigger: 'blur' }
                ],
                employeeId: [
                    { required: true, message: '请输入员工ID', trigger: 'blur' }
                ],
                studyType: [
                    { required: true, message: '请输入学习类型', trigger: 'blur' }
                ],
                studyDate: [
                    { required: true, message: '请选择学习日期', trigger: 'change' }
                ],
                dailyStatus: [
                    { required: true, message: '请输入日常状态', trigger: 'blur' }
                ]
            }
        }
    },
    methods: {
        init(classId, className) {
            this.visible = true
            this.classId = classId
            this.className = className
            this.getStudentIds(classId)
        },

        // 获取班级下的学员ID列表
        getStudentIds(classId) {
            const params = {
                classId: classId,
                currentPage: 1,
                pageSize: 1000 // 获取所有学员
            }

            getStudentListByClassId(params).then(response => {
                if (response.code === 200) {
                    const students = response.data.list || []
                    this.studentIds = students.map(student => student.employeeId).filter(id => id)
                    this.getRecordList()
                } else {
                    this.$message.error(response.msg || '获取学员列表失败')
                    this.loading = false
                }
            }).catch(() => {
                this.loading = false
            })
        },
        // 获取学习记录列表
        getRecordList() {
            this.loading = true
            const params = {
                ...this.query,
                currentPage: this.pagination.pageIndex,
                pageSize: this.pagination.pageSize
            }

            // 处理日期范围
            if (this.query.studyDateRange && this.query.studyDateRange.length === 2) {
                params.studyDateStart = this.query.studyDateRange[0]
                params.studyDateEnd = this.query.studyDateRange[1]
            }

            getStudyRecordList(params).then(response => {
                if (response.code === 200) {
                    let recordList = response.data.list || []
                    // 按班级学员ID过滤学习记录
                    if (this.studentIds && this.studentIds.length > 0) {
                        recordList = recordList.filter(record => this.studentIds.includes(record.employeeId))
                    }
                    this.recordList = recordList
                    this.pagination.total = recordList.length
                } else {
                    this.$message.error(response.msg || '获取学习记录失败')
                }
                this.loading = false
            }).catch(() => {
                this.loading = false
            })
        },

        // 搜索
        search() {
            this.pagination.pageIndex = 1
            this.getRecordList()
        },

        // 重置
        reset() {
            this.query = {
                employeeName: '',
                employeeId: '',
                studyType: '',
                studyDateStart: '',
                studyDateEnd: '',
                dailyStatus: '',
                studyDateRange: []
            }
            this.pagination.pageIndex = 1
            this.getRecordList()
        },

        // 分页大小改变
        handleSizeChange(val) {
            this.pagination.pageSize = val
            this.pagination.pageIndex = 1
            this.getRecordList()
        },

        // 当前页改变
        handleCurrentChange(val) {
            this.pagination.pageIndex = val
            this.getRecordList()
        },

        // 添加记录
        addRecord() {
            this.addRecordVisible = true
            this.resetRecordForm()
        },

        // 重置记录表单
        resetRecordForm() {
            this.recordForm = {
                employeeName: '',
                employeeId: '',
                studyType: '',
                transportFee: 0,
                studyDate: '',
                dailyStatus: '',
                remark: '',
                isStoreAssist: 0,
                storeId: '',
                storeName: ''
            }
            this.$nextTick(() => {
                if (this.$refs.recordForm) {
                    this.$refs.recordForm.clearValidate()
                }
            })
        },

        // 提交记录
        submitRecord() {
            this.$refs.recordForm.validate((valid) => {
                if (valid) {
                    this.submitLoading = true
                    addStudyRecord(this.recordForm).then(response => {
                        if (response.code === 200) {
                            this.$message.success('添加成功')
                            this.addRecordVisible = false
                            this.getRecordList()
                        } else {
                            this.$message.error(response.msg || '添加失败')
                        }
                        this.submitLoading = false
                    }).catch(() => {
                        this.submitLoading = false
                    })
                }
            })
        },

        // 作废记录
        cancelRecord(row) {
            this.$confirm('确定要作废该学习记录吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                cancelStudyRecord(row.id).then(response => {
                    if (response.code === 200) {
                        this.$message.success('作废成功')
                        this.getRecordList()
                    } else {
                        this.$message.error(response.msg || '作废失败')
                    }
                })
            })
        },

        // 格式化金额
        formatMoney(value) {
            if (value === null || value === undefined || value === '') {
                return '0.00'
            }
            return Number(value).toFixed(2)
        },

        // 关闭弹窗
        closeDialog() {
            this.visible = false
            this.recordList = []
            this.query = {
                employeeName: '',
                employeeId: '',
                studyType: '',
                studyDateStart: '',
                studyDateEnd: '',
                dailyStatus: '',
                studyDateRange: []
            }
            this.pagination = {
                pageIndex: 1,
                pageSize: 20,
                total: 0
            }
        }
    }
}
</script>

<style scoped>
.study-record-container {
    padding: 20px;
}

.search-section {
    margin-bottom: 20px;
    padding: 15px;
    background: #f5f7fa;
    border-radius: 4px;
}

.search-form .el-form-item {
    margin-bottom: 10px;
}

.table-section {
    margin-bottom: 20px;
}

.pagination-section {
    text-align: right;
    margin-top: 20px;
}
</style>
