<template>
    <div class="NCC-common-layout attendance-summary-page">
        <div class="NCC-common-layout-center NCC-flex-main">
            <el-row class="NCC-common-search-box" :gutter="16">
                <el-form @submit.native.prevent>
                    <el-col :span="6">
                        <el-form-item label="员工姓名">
                            <user-select v-model="query.userId" placeholder="请选择员工" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="统计月份">
                            <el-date-picker v-model="statMonth" type="month" value-format="yyyy-MM" format="yyyy-MM"
                                placeholder="选择月份" style="width: 100%" clearable @change="onStatMonthChange" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="员工状态">
                            <el-select v-model="query.employeeStatus" placeholder="员工状态" clearable>
                                <el-option label="在职" :value="1" />
                                <el-option label="离职" :value="0" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item>
                            <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
                            <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>
            <div class="NCC-common-layout-main NCC-flex-main attendance-summary-main">
                <div class="NCC-common-head">
                    <div>
                        <el-button type="primary" icon="el-icon-refresh" :loading="syncLoading"
                            @click="handleSyncFromRecords()">从打卡同步汇总</el-button>
                        <el-button type="primary" icon="el-icon-upload2" @click="handleImport()">导入</el-button>
                        <el-button type="text" icon="el-icon-download" @click="downloadTemplate()">导出模板</el-button>
                        <el-button type="text" icon="el-icon-delete" @click="handleBatchDelete()">批量删除</el-button>
                    </div>
                    <div class="NCC-common-head-right">
                        <el-tooltip effect="dark" content="刷新" placement="top">
                            <el-link icon="icon-ym icon-ym-Refresh NCC-common-head-icon" :underline="false"
                                @click="reset()" />
                        </el-tooltip>
                        <screenfull isContainer />
                    </div>
                </div>
                <div class="attendance-summary-table-wrap">
                    <NCC-table v-loading="listLoading" :data="list" has-c height="100%"
                        @selection-change="handleSelectionChange">
                        <el-table-column prop="userName" label="员工姓名" align="left" min-width="100" fixed="left" />
                        <el-table-column prop="year" label="年份" align="left" width="72" fixed="left" />
                        <el-table-column prop="month" label="月份" align="left" width="72" fixed="left" />
                        <el-table-column prop="attendanceGroupDisplay" label="当月考勤组" align="left" min-width="140"
                            show-overflow-tooltip fixed="left">
                            <template slot-scope="scope">
                                {{ scope.row.attendanceGroupDisplay || '无' }}
                            </template>
                        </el-table-column>
                        <el-table-column label="员工状态" prop="employeeStatus" align="left" width="88" fixed="left">
                            <template slot-scope="scope">
                                <el-tag :type="scope.row.employeeStatus === 1 ? 'success' : 'danger'" size="small">
                                    {{ scope.row.employeeStatus === 1 ? '在职' : '离职' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="数据来源" align="left" width="96" fixed="left">
                            <template slot-scope="scope">
                                <el-tag :type="isImportSource(scope.row) ? 'warning' : 'primary'" size="small">
                                    {{ scope.row.dataSourceName || '打卡同步' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="出勤天数(算薪)" align="left" min-width="108">
                            <template slot-scope="scope">
                                {{ formatDecimal(scope.row.workDays) }}
                            </template>
                        </el-table-column>
                        <el-table-column label="请假天数" align="left" min-width="88">
                            <template slot-scope="scope">
                                {{ formatDecimal(scope.row.leaveDays) }}
                            </template>
                        </el-table-column>
                        <el-table-column label="休息天数" align="left" min-width="88">
                            <template slot-scope="scope">
                                {{ formatDecimal(scope.row.restDays) }}
                            </template>
                        </el-table-column>
                        <el-table-column label="应休天数" align="left" min-width="88">
                            <template slot-scope="scope">
                                {{ isPunchSource(scope.row) ? formatDecimal(scope.row.monthEntitledRestDays) : '无' }}
                            </template>
                        </el-table-column>
                        <el-table-column label="到岗天数" align="left" min-width="88">
                            <template slot-scope="scope">
                                {{ isPunchSource(scope.row) ? formatDecimal(scope.row.monthOnDutyDays) : '无' }}
                            </template>
                        </el-table-column>
                        <el-table-column label="工作天数(应休+到岗)" align="left" min-width="150" show-overflow-tooltip>
                            <template slot-scope="scope">
                                {{ isPunchSource(scope.row) ? formatDecimal(scope.row.monthCompositeWorkDays) : '无' }}
                            </template>
                        </el-table-column>
                        <el-table-column label="带薪请假天数" align="left" min-width="108">
                            <template slot-scope="scope">
                                {{ isPunchSource(scope.row) ? formatDecimal(scope.row.monthPaidLeaveDays) : '无' }}
                            </template>
                        </el-table-column>
                        <el-table-column label="打卡请假天数" align="left" min-width="108">
                            <template slot-scope="scope">
                                {{ isPunchSource(scope.row) ? formatDecimal(scope.row.monthLeaveDaysTotal) : '无' }}
                            </template>
                        </el-table-column>
                        <el-table-column label="迟到早退天数" align="left" min-width="108">
                            <template slot-scope="scope">
                                {{ isPunchSource(scope.row) ? formatDecimal(scope.row.monthLateEarlyDays) : '无' }}
                            </template>
                        </el-table-column>
                        <el-table-column label="旷工天数" align="left" min-width="88">
                            <template slot-scope="scope">
                                {{ isPunchSource(scope.row) ? formatDecimal(scope.row.monthAbsenteeismDays) : '无' }}
                            </template>
                        </el-table-column>
                        <el-table-column label="迟到/早退扣款" align="left" min-width="120" show-overflow-tooltip>
                            <template slot-scope="scope">
                                {{ isPunchSource(scope.row) ? formatDecimal(scope.row.monthLateDeductionAmount) : '无' }}
                            </template>
                        </el-table-column>
                        <el-table-column label="请假扣款" align="left" min-width="96">
                            <template slot-scope="scope">
                                {{ isPunchSource(scope.row) ? formatDecimal(scope.row.monthLeaveDeductionAmount) : '无'
                                }}
                            </template>
                        </el-table-column>
                        <el-table-column label="旷工扣款" align="left" min-width="96">
                            <template slot-scope="scope">
                                {{ isPunchSource(scope.row) ? formatDecimal(scope.row.monthAbsenteeismDeductionAmount) :
                                    '无' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="remark" label="备注" align="left" min-width="100" show-overflow-tooltip />
                        <el-table-column label="创建时间" prop="createTime" align="left" width="150">
                            <template slot-scope="scope">
                                {{ formatTime(scope.row.createTime) }}
                            </template>
                        </el-table-column>
                        <el-table-column label="更新时间" prop="updateTime" align="left" width="150">
                            <template slot-scope="scope">
                                {{ formatTime(scope.row.updateTime) }}
                            </template>
                        </el-table-column>
                    </NCC-table>
                </div>
                <div class="attendance-summary-pager">
                    <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize"
                        @pagination="initData" />
                </div>
            </div>
        </div>

        <ImportDialog v-if="importVisible" ref="ImportDialog" @refresh="refresh" />
        <BatchDeleteDialog v-if="batchDeleteVisible" ref="BatchDeleteDialog" @refresh="refresh" />
    </div>
</template>

<script>
import request from '@/utils/request'
import ImportDialog from './ImportDialog'
import BatchDeleteDialog from './BatchDeleteDialog'
import { saveAs } from 'file-saver'

function currentYearMonthStr() {
    const d = new Date()
    const y = d.getFullYear()
    const m = d.getMonth() + 1
    return `${y}-${m < 10 ? '0' + m : m}`
}

export default {
    components: { ImportDialog, BatchDeleteDialog },
    data() {
        const ym = currentYearMonthStr()
        const parts = ym.split('-')
        return {
            statMonth: ym,
            query: {
                userId: undefined,
                year: parseInt(parts[0], 10),
                month: parseInt(parts[1], 10),
                employeeStatus: undefined,
            },
            list: [],
            listLoading: true,
            multipleSelection: [],
            total: 0,
            listQuery: {
                currentPage: 1,
                pageSize: 20,
                sort: 'desc',
                sidx: '',
            },
            syncLoading: false,
            importVisible: false,
            batchDeleteVisible: false,
        }
    },
    created() {
        this.initData()
    },
    methods: {
        onStatMonthChange(val) {
            if (!val) {
                this.query.year = undefined
                this.query.month = undefined
                return
            }
            const p = val.split('-')
            this.query.year = parseInt(p[0], 10)
            this.query.month = parseInt(p[1], 10)
        },
        initData() {
            this.listLoading = true
            const _query = {
                ...this.listQuery,
                ...this.query
            }
            const query = {}
            for (const key in _query) {
                if (Array.isArray(_query[key])) {
                    query[key] = _query[key].join()
                } else {
                    query[key] = _query[key]
                }
            }
            request({
                url: '/api/Extend/lqattendancesummary',
                method: 'GET',
                data: query
            }).then(res => {
                this.list = res.data.list
                this.total = res.data.pagination.total
                this.listLoading = false
            }).catch(() => {
                this.listLoading = false
            })
        },
        handleSelectionChange(val) {
            this.multipleSelection = val.map(item => item.id)
        },
        handleSyncFromRecords() {
            if (!this.query.year || !this.query.month) {
                this.$message.warning('请先选择统计月份')
                return
            }
            this.$confirm(
                `将删除 ${this.query.year} 年 ${this.query.month} 月已有汇总数据，并按考勤打卡记录重新生成，是否继续？`,
                '提示',
                { type: 'warning' }
            ).then(() => {
                this.syncLoading = true
                return request({
                    url: `/api/Extend/lqattendancesummary/SyncFromAttendanceRecords/${this.query.year}/${this.query.month}`,
                    method: 'POST'
                })
            }).then(res => {
                if (res.code === 200) {
                    this.$message.success((res.data && res.data.message) || res.msg || '同步成功')
                    this.initData()
                }
            }).catch(() => { }).finally(() => {
                this.syncLoading = false
            })
        },
        handleImport() {
            this.importVisible = true
            this.$nextTick(() => {
                this.$refs.ImportDialog.init()
            })
        },
        handleBatchDelete() {
            this.batchDeleteVisible = true
            this.$nextTick(() => {
                this.$refs.BatchDeleteDialog.init(this.statMonth || undefined)
            })
        },
        async downloadTemplate() {
            if (!this.query.year || !this.query.month) {
                this.$message.warning('请先选择统计月份')
                return
            }
            try {
                const userRes = await request({
                    url: '/api/Extend/lqattendancesummary/ImportTemplateUsers',
                    method: 'GET',
                    data: {
                        year: this.query.year,
                        month: this.query.month
                    }
                })

                if (userRes.code !== 200 || !userRes.data || !userRes.data.list || userRes.data.list.length === 0) {
                    this.$message({
                        type: 'warning',
                        message: '该月份暂无符合条件的人员',
                        duration: 1500
                    })
                    return
                }

                const templateUsers = userRes.data.list
                const year = this.query.year
                const month = this.query.month
                const XLSX = await import('xlsx')

                const headers = [
                    '员工ID',
                    '员工姓名',
                    '员工电话',
                    '当月离职',
                    '年份',
                    '月份',
                    '出勤天数(算薪在店天数)',
                    '请假天数',
                    '休息天数',
                    '备注'
                ]

                const dataRows = templateUsers.map(item => [
                    item.id,
                    item.realName || '无',
                    item.mobilePhone || '',
                    item.leftInMonth ? '是' : '否',
                    year,
                    month,
                    item.workDays != null && item.workDays !== '' ? item.workDays : '',
                    item.leaveDays != null && item.leaveDays !== '' ? item.leaveDays : '',
                    item.restDays != null && item.restDays !== '' ? item.restDays : '',
                    ''
                ])

                const guideRows = [
                    ['填写说明（请勿删除表头行）'],
                    ['1. 模板人员与「从打卡同步」使用相同口径，含当月中途离职、有打卡记录人员'],
                    ['2. 出勤/请假/休息与打卡同步写入汇总表字段一致，算薪统一读取这三项'],
                    ['3. 出勤天数(算薪在店天数)：用于算薪底薪，填实际在店天数；「当月离职」列只读勿改'],
                    ['4. 打卡扩展指标（应休/到岗/扣款等）仅打卡同步时自动计算，导入无需填写']
                ]

                const excelData = [headers, ...dataRows]
                const ws = XLSX.utils.aoa_to_sheet(excelData)
                ws['!cols'] = [
                    { wch: 18 },
                    { wch: 12 },
                    { wch: 15 },
                    { wch: 10 },
                    { wch: 8 },
                    { wch: 8 },
                    { wch: 22 },
                    { wch: 10 },
                    { wch: 10 },
                    { wch: 20 }
                ]

                const wb = XLSX.utils.book_new()
                XLSX.utils.book_append_sheet(wb, ws, '导入数据')
                const guideWs = XLSX.utils.aoa_to_sheet(guideRows)
                guideWs['!cols'] = [{ wch: 80 }]
                XLSX.utils.book_append_sheet(wb, guideWs, '填写说明')

                const fileName = `考勤统计导入模板_${year}年${month}月_${new Date().getTime()}.xlsx`
                const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
                saveAs(new Blob([wbout], { type: 'application/octet-stream' }), fileName)

                this.$message({
                    type: 'success',
                    message: '模板下载成功',
                    duration: 1500
                })
            } catch (error) {
                this.$message({
                    type: 'error',
                    message: error.message && error.message.includes('xlsx')
                        ? '导出失败：请先安装 xlsx 库，运行命令: npm install xlsx --save'
                        : '模板下载失败，请稍后重试',
                    duration: 3000
                })
            }
        },
        formatTime(timestamp) {
            if (!timestamp) return '无'
            const date = new Date(timestamp)
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            })
        },
        formatDecimal(val) {
            if (val === null || val === undefined || val === '') return '无'
            const n = Number(val)
            if (!Number.isFinite(n)) return '无'
            return n.toFixed(2)
        },
        isImportSource(row) {
            if (!row) return false
            if (Number(row.dataSource) === 2) return true
            if (row.remark && row.remark.indexOf('[Excel导入]') === 0) return true
            if (row.remark && row.remark.indexOf('系统按考勤打卡汇总生成') >= 0) return false
            return Number(row.dataSource) !== 1
        },
        isPunchSource(row) {
            return !this.isImportSource(row)
        },
        search() {
            this.listQuery = {
                currentPage: 1,
                pageSize: 20,
                sort: 'desc',
                sidx: '',
            }
            this.initData()
        },
        refresh(isrRefresh) {
            this.importVisible = false
            this.batchDeleteVisible = false
            if (isrRefresh) this.reset()
        },
        reset() {
            const ym = currentYearMonthStr()
            const parts = ym.split('-')
            this.statMonth = ym
            this.query = {
                userId: undefined,
                year: parseInt(parts[0], 10),
                month: parseInt(parts[1], 10),
                employeeStatus: undefined,
            }
            this.listQuery = {
                currentPage: 1,
                pageSize: 20,
                sort: 'desc',
                sidx: '',
            }
            this.initData()
        }
    }
}
</script>

<style scoped lang="scss">
.attendance-summary-page {
    height: 100%;

    .attendance-summary-main {
        display: flex;
        flex-direction: column;
        min-height: 0;
        overflow: hidden;
    }

    .NCC-common-head {
        flex-shrink: 0;
    }

    .attendance-summary-table-wrap {
        flex: 1;
        min-height: 0;
        overflow: hidden;
        position: relative;
        width: 100%;
    }

    /* 覆盖全局 .NCC-flex-main .el-table { flex:1 }，使 height:100% 在固定区域内生效 */
    .attendance-summary-table-wrap ::v-deep .el-table {
        position: absolute !important;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        flex: none !important;
        width: auto !important;
    }

    .attendance-summary-table-wrap ::v-deep .el-table .cell {
        white-space: nowrap;
    }

    .attendance-summary-pager {
        flex-shrink: 0;
        padding-top: 4px;
    }
}
</style>
