<template>
	<div class="NCC-common-layout">
		<div class="NCC-common-layout-center">
			<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-select v-model="query.year" placeholder="年份" clearable>
								<el-option v-for="year in yearOptions" :key="year" :label="year + '年'" :value="year" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="月份">
							<el-select v-model="query.month" placeholder="月份" clearable>
								<el-option v-for="month in monthOptions" :key="month" :label="month + '月'" :value="month" />
							</el-select>
						</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">
				<div class="NCC-common-head">
					<div>
						<el-button type="primary" icon="el-icon-refresh" :loading="syncLoading" @click="handleSyncFromRecords()">从打卡同步汇总</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 @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" min-width="88">
						<template slot-scope="scope">{{ formatDecimal(scope.row.monthEntitledRestDays) }}</template>
					</el-table-column>
					<el-table-column label="到岗天数" align="left" min-width="88">
						<template slot-scope="scope">{{ formatDecimal(scope.row.monthOnDutyDays) }}</template>
					</el-table-column>
					<el-table-column label="工作天数(应休+到岗)" align="left" min-width="150" show-overflow-tooltip>
						<template slot-scope="scope">{{ formatDecimal(scope.row.monthCompositeWorkDays) }}</template>
					</el-table-column>
					<el-table-column label="带薪请假天数" align="left" min-width="108">
						<template slot-scope="scope">{{ formatDecimal(scope.row.monthPaidLeaveDays) }}</template>
					</el-table-column>
					<el-table-column label="请假天数" align="left" min-width="88">
						<template slot-scope="scope">{{ formatDecimal(scope.row.monthLeaveDaysTotal) }}</template>
					</el-table-column>
					<el-table-column label="迟到早退天数" align="left" min-width="108">
						<template slot-scope="scope">{{ formatDecimal(scope.row.monthLateEarlyDays) }}</template>
					</el-table-column>
					<el-table-column label="旷工天数" align="left" min-width="88">
						<template slot-scope="scope">{{ formatDecimal(scope.row.monthAbsenteeismDays) }}</template>
					</el-table-column>
					<el-table-column label="迟到/早退扣款" align="left" min-width="120" show-overflow-tooltip>
						<template slot-scope="scope">{{ formatDecimal(scope.row.monthLateDeductionAmount) }}</template>
					</el-table-column>
					<el-table-column label="请假扣款" align="left" min-width="96">
						<template slot-scope="scope">{{ formatDecimal(scope.row.monthLeaveDeductionAmount) }}</template>
					</el-table-column>
					<el-table-column label="旷工扣款" align="left" min-width="96">
						<template slot-scope="scope">{{ 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>
                <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="initData" />
            </div>
        </div>
		
		<!-- 批量删除弹窗 -->
		<BatchDeleteDialog v-if="batchDeleteVisible" ref="BatchDeleteDialog" @refresh="refresh" />
	</div>
</template>

<script>
    import request from '@/utils/request'
    import BatchDeleteDialog from './BatchDeleteDialog'
    
	export default {
        components: { BatchDeleteDialog },
        data() {
			return {
				query: {
                    userId: undefined,
                    year: undefined,
                    month: undefined,
                    employeeStatus: undefined,
				},
                list: [],
                listLoading: true,
                multipleSelection: [], 
                total: 0,
                listQuery: {
                    currentPage: 1,
                    pageSize: 20,
					sort: "desc",
                    sidx: "",
                },
                syncLoading: false,
                batchDeleteVisible: false,
                yearOptions: [],
                monthOptions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
			}
        },
		computed: {},
		created() {
			this.initYearOptions()
			this.initData()
		},
		methods: {
			initYearOptions() {
				const currentYear = new Date().getFullYear()
				for (let i = currentYear - 5; i <= currentYear + 1; i++) {
					this.yearOptions.push(i)
				}
			},
			initData() {
                this.listLoading = true;
                let _query = {
                    ...this.listQuery,
                    ...this.query
                };
                let query = {}
                for (let 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
                })
            },
			handleDel(id) {
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    type: 'warning'
                }).then(() => {
                    request({
                        url: `/api/Extend/lqattendancesummary/${id}`,
                        method: 'DELETE'
                    }).then(res => {
                        this.$message({
                            type: 'success',
                            message: res.msg,
                            onClose: () => {
                                this.initData()
                            }
                        });
                    })
                }).catch(() => {
                });
            },
			handleSelectionChange(val) {
                const res = val.map(item => item.id)
                this.multipleSelection = res
            },
            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
                })
            },
            handleBatchDelete() {
                this.batchDeleteVisible = true
                this.$nextTick(() => {
                    this.$refs.BatchDeleteDialog.init()
                })
            },
            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)
            },
			search() {
                this.listQuery = {
                    currentPage: 1,
                    pageSize: 20,
                    sort: "desc",
                    sidx: "",
                }
                this.initData()
            },
            refresh(isrRefresh) {
                this.batchDeleteVisible = false
                if (isrRefresh) this.reset()
            },
            reset() {
                for (let key in this.query) {
                    this.query[key] = undefined
                }
                this.listQuery = {
                    currentPage: 1,
                    pageSize: 20,
                    sort: "desc",
                    sidx: "",
                }
                this.initData()
            }
		}
    }
</script>

<style scoped lang="scss">
.attendance-summary-table-wrap {
  width: 100%;
  overflow-x: auto;
}
.attendance-summary-table-wrap ::v-deep .el-table .cell {
  white-space: nowrap;
}
</style>
