<template>
    <div class="page">
        <el-form :inline="true" class="query-form m-b-10" v-if="searchVisible" ref="searchForm" :model="searchForm"
            @keyup.enter="refreshList()" @submit.prevent>
            <!-- 搜索框-->
            <el-form-item prop="deptId" label="所属部门:">
                <el-tree-select style="width: 100%;" v-model="searchForm.deptId" node-key="deptId" :props="props"
                    default-expand-all :data="deptList" check-strictly show-checkbox check-on-click-node />
            </el-form-item>
            <el-form-item label="工作时间" prop="workDates">
                <el-date-picker style="width:50%;" v-model="searchForm.workDates" type="datetimerange"
                    value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择日期" @change="handleDateChange" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="refreshList()" icon="search">查询</el-button>
                <el-button type="default" @click="resetSearch()" icon="refresh-right">重置</el-button>
            </el-form-item>
        </el-form>

        <div class="jp-table">
            <vxe-toolbar ref="dataSetToolbar" :refresh="{ query: refreshList }" export print custom>
                <template #buttons>
                    <el-button type="primary" icon="plus" @click="add()">新增用户</el-button>
                </template>
                <template #tools>
                    <vxe-button type="text" :title="searchVisible ? '收起检索' : '展开检索'" icon="vxe-icon-search"
                        class="tool-btn" @click="searchVisible = !searchVisible"></vxe-button>
                </template>
            </vxe-toolbar>

            <div class="jp-table-body">
                <vxe-table border="inner" auto-resize resizable height="auto" :loading="loading" size="small"
                    ref="dataSetTable" show-header-overflow show-overflow highlight-hover-row :menu-config="{}"
                    :print-config="{}" :import-config="{}" :export-config="{}" @sort-change="sortChangeHandle"
                    :sort-config="{ remote: true }" :data="userDataList" :checkbox-config="{}">
                    <vxe-column type="seq" width="40"></vxe-column>
                    <vxe-column field="name" title="姓名">
                    </vxe-column>
                    <vxe-column field="mobile" title="手机号">
                    </vxe-column>
                    <vxe-column field="requiredAttDays" title="应出勤天数(天)">
                    </vxe-column>
                    <vxe-column field="attDays" title="出勤天数(天)">
                    </vxe-column>
                    <vxe-column field="restDays" title="休息天数(天)">
                    </vxe-column>
                    <vxe-column field="lateTimes" title="迟到次数(次)">
                    </vxe-column>
                    <vxe-column fixed="right" align="center" width="320" title="操作">
                        <template #default="scope">
                            <!-- <el-button type="success" text @click="handleAdd(scope.row)">打卡</el-button> -->
                            <el-button type="success" text @click="edit(scope.row.userid)">修改基本信息</el-button>
                            <el-button type="success" text @click="attendance(scope.row)">考勤统计</el-button>
                        </template>
                    </vxe-column>
                </vxe-table>
                <vxe-pager background size="small" :current-page="tablePage.currentPage" :page-size="tablePage.pageSize"
                    :total="tablePage.total" :page-sizes="[
            10,
            20,
            100,
            1000,
            { label: '全量数据', value: 1000000 },
        ]" :layouts="[
            'PrevPage',
            'JumpNumber',
            'NextPage',
            'FullJump',
            'Sizes',
            'Total',
        ]" @page-change="currentChangeHandle">
                </vxe-pager>
            </div>
        </div>
        <PunchCardListDia ref="punchCardListDia"></PunchCardListDia>
        <AttendanceListDia ref="attendanceListDia"></AttendanceListDia>
        <UserAddForm ref="userAddForm"></UserAddForm>
    </div>
</template>

<script>
import ddService from "@/api/test/dd/dd.js"
import PunchCardListDia from "./PunchCardListDia";
import UserAddForm from "./UserAddForm";
import AttendanceListDia from "./AttendanceListDia";
export default {
    components: {
        PunchCardListDia,
        AttendanceListDia,
        UserAddForm
    },
    data() {
        return {
            props: {
                label: 'name',
                chindren: 'children'
            },
            url: "",
            showViewer: false,
            searchVisible: true,
            searchForm: {
                deptId: null,
                workDates: []
            },
            dataList: [],
            deptList: [],
            userDataList: [],
            tablePage: {
                total: 0,
                currentPage: 1,
                pageSize: 10,
                orders: [],
            },
            isImportCollapse: false,
            dialogInterfaceVisible: false,
            interfaceTable: [],
            loading: false,
            userInfo: {},
            dictList: [],

        };
    },
    activated() {
        this.userInfo = this.$TOOL.data.get("USER_INFO");
        this.searchForm.createById = this.userInfo.id
        this.$nextTick(() => {
            // 将表格和工具栏进行关联
            const $table = this.$refs.dataSetTable;
            const $toolbar = this.$refs.dataSetToolbar;
            $table.connect($toolbar);
        });
        this.loading = true
        ddService.deptList(1).then(res => {
            res.unshift({
                deptId: 1,
                name: '顶级部门节点',
                parentId: 0
            })
            this.deptList = this.buildTree(res)
        })
        this.searchForm.deptId = 1
        this.refreshList();
    },
    methods: {
        buildTree(data) {
            const map = new Map();
            const tree = [];
            // 先把所有项存到 Map 里，并初始化 children
            data.forEach(item => {
                map.set(item.deptId, { ...item, children: [] });
            });
            // 组装树结构
            data.forEach(item => {
                if (item.parentId) {
                    // 找到父级并添加到 children
                    const parent = map.get(item.parentId);
                    if (parent) {
                        parent.children.push(map.get(item.deptId));
                    }
                } else {
                    // parentId 为空的就是根节点
                    tree.push(map.get(item.deptId));
                }
            });

            return tree;
        },
        handleChange(value) {
            console.log(value);
            this.searchForm.deptId = value
            this.refreshList()
        },
        handleAdd(row) {
            this.$refs.punchCardListDia.init(row.userid, row.name, row.title)
        },
        //考勤统计
        attendance(row) {
            this.$refs.attendanceListDia.init(row.userid, row.name, row.title);
        },
        handleClick(tab, event) {
            console.log(tab.props.name);
            this.getUserList(tab.props.name)
        },
        // 关闭查看器
        closeViewer() {
            this.url = ''
            this.showViewer = false
        },
        onPreview(url) {
            this.url = url
            this.showViewer = true
        },
        // 获取数据列表
        refreshList() {
            this.loading = true;
            ddService
                .list({
                    deptId: this.searchForm.deptId ?? 1,
                    dateFrom: this.searchForm.workDates[0],
                    dateTo: this.searchForm.workDates[1]
                })
                .then((data) => {
                    this.userDataList = data;
                    // this.tablePage.total = data.total;
                    this.loading = false;
                    // 获取分类去重的数据
                });
        },
        // 当前页
        currentChangeHandle({ currentPage, pageSize }) {
            this.tablePage.currentPage = currentPage;
            this.tablePage.pageSize = pageSize;
            this.refreshList();
        },
        // 排序
        sortChangeHandle(column) {
            this.tablePage.orders = [];
            if (column.order != null) {
                this.tablePage.orders.push({
                    column: this.$utils.toLine(column.property),
                    asc: column.order === "asc",
                });
            }
            this.refreshList();
        },
        // 新增
        add() {
            this.$refs.userAddForm.deptList = this.deptList
            this.$refs.userAddForm.init("add")
        },
        // 编辑
        edit(id) {
            this.$refs.userAddForm.deptList = this.deptList
            this.$refs.userAddForm.init("edit", id)
        },
        // 查看
        view(id) {
            id =
                id ||
                this.$refs.dataSetTable.getCheckboxRecords().map((item) => {
                    return item.id;
                })[0];
            this.$router.push({
                path: `/database/datamodel/DataSetForm`,
                query: { method: "view", id: id, title: "数据模型配置" },
            });
        },
        // 删除
        del(id) {
            this.$confirm(`确定删除所选项吗?`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                this.loading = true;
                ddService
                    .del({
                        attachmentId: id
                    }).then(res => {
                        this.$message.success(res);
                        this.loading = false;
                        this.refreshList();
                    })


            });
        },

        resetSearch() {
            this.$refs.searchForm.resetFields();
            this.searchForm.deptId = 1
            this.searchForm.workDates = []
            this.refreshList();
        },
        handleDateChange(val) {
            if (val && val[0] && val[1]) {
                const startDate = new Date(val[0]);
                const endDate = new Date(val[1]);
                const diffDays = (endDate - startDate) / (1000 * 3600 * 24); // 计算日期差距

                if (diffDays > 31) {
                    this.$message.warning('选择的时间范围不能超过31天');
                    // 限制选中的日期范围为31天内
                    const newEndDate = new Date(startDate);
                    newEndDate.setDate(startDate.getDate() + 31);
                    this.searchForm.workDates = [startDate, newEndDate];
                }
            }
        },
    },
};
</script>
