
<template>
    <!-- 补卡申请管理 -->
    <div class="app-container">
        <el-form
            size="small"
            :inline="true"
            ref="queryFormRef"
            label-width="auto"
            :model="queryParams"
        >
            <el-form-item label="人员姓名" prop="userName">
                <el-input
                    clearable
                    style="width: 240px"
                    placeholder="请输入人员姓名"
                    v-model.trim="queryParams.userName"
                    @keyup.enter.native="getCardReplenishmentManageList"
                />
            </el-form-item>

            <el-form-item label="部门" prop="orgId">
                <treeselect
                    placeholder="选择部门"
                    style="width: 240px"
                    :options="deptOptions"
                    :normalizer="normalizer"
                    v-model="queryParams.orgId"
                />
            </el-form-item>
            <el-form-item>
                <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-search"
                    @click="getCardReplenishmentManageList"
                >
                    查询
                </el-button>
                <el-button
                    size="mini"
                    type="warning"
                    icon="el-icon-refresh"
                    @click="onHandleReset"
                >
                    重置
                </el-button>

                <el-button
                    plain
                    size="mini"
                    type="primary"
                    @click="onHandleAdd"
                    icon="el-icon-plus"
                >
                    新增
                </el-button>
            </el-form-item>
        </el-form>

        <!-- 列表 -->
        <el-table v-loading="loading" :data="applyList" border>
            <el-table-column
                label="序号"
                align="center"
                width="80"
                type="index"
            >
                <template slot-scope="scope">
                    <span>{{
                        (queryParams.pageNum - 1) * queryParams.pageSize +
                        scope.$index +
                        1
                    }}</span>
                </template>
            </el-table-column>

            <el-table-column
                v-for="item in tableColumns"
                :key="item.prop"
                :label="item.label"
                :prop="item.prop"
                align="center"
            >
                <template slot-scope="scope">
                    <template v-if="item.slot === 'attType'">
                        <el-tag
                            :type="
                                scope.row.attType == 1 ? 'primary' : 'success'
                            "
                        >
                            {{ scope.row.attType === 1 ? '上午' : '下午' }}
                        </el-tag>
                    </template>
                    <template v-else>
                        <span>{{ scope.row[item.prop] }}</span>
                    </template>
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="100">
                <template slot-scope="scope">
                    <el-button
                        type="danger"
                        size="mini"
                        @click="onHandleDelete(scope.row)"
                    >
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
            :total="total"
            v-show="total > 0"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getCardReplenishmentManageList"
        />

        <!-- 新增编辑弹框 -->
        <el-dialog
            width="60%"
            append-to-body
            :title="dialogTitle"
            @close="onHandleCloseDialog"
            :visible.sync="dialogVisible"
        >
            <el-form
                label-width="120px"
                ref="addAndEditFormRef"
                :model="addAndEditForm"
                :rules="addAndEditFormRules"
            >
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="人员姓名" prop="userId">
                            <el-select
                                filterable
                                clearable
                                disabled
                                style="width: 100%"
                                placeholder="请选择人员姓名"
                                v-model="addAndEditForm.userId"
                            >
                                <el-option
                                    :key="item.id"
                                    :value="item.id"
                                    :label="item.userName"
                                    v-for="item in personSelectList"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="身份证号码" prop="idNumber">
                            <el-input
                                disabled
                                style="width: 100%"
                                placeholder="请选择人员姓名后获取"
                                v-model="addAndEditForm.idNumber"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="所属部门" prop="orgName">
                            <el-input
                                disabled
                                style="width: 100%"
                                placeholder="请选择人员姓名后获取"
                                v-model="addAndEditForm.orgName"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="补卡日期" prop="currentDay">
                            <el-date-picker
                                type="date"
                                style="width: 100%"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择补卡日期"
                                :picker-options="pickerOptions"
                                v-model="addAndEditForm.currentDay"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="补卡类型" prop="attType">
                            <el-radio-group
                                size="small"
                                v-model="addAndEditForm.attType"
                            >
                                <el-radio-button :label="1">
                                    上午
                                </el-radio-button>
                                <el-radio-button :label="2">
                                    下午
                                </el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row
                    style="
                        padding-top: 10px;
                        text-align: right;
                        border-top: 1px solid #e6e6e6;
                    "
                >
                    <el-button
                        size="medium"
                        type="primary"
                        @click="onHandleSubmit"
                    >
                        提交
                    </el-button>
                    <el-button
                        size="medium"
                        type="info"
                        @click="onHandleCloseDialog"
                    >
                        取消
                    </el-button>
                </el-row>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import {
    getCardReplenishmentManageListAPI,
    addCardReplenishmentManageAPI,
    deleteCardReplenishmentManageAPI,
    isCardReplenishmentManageAPI,
} from '@/api/report/cardReplenishmentManage'

// 获取人员下拉
import { getPersonSelect } from '@/api/system/userInfo'
import { getOldData } from '@/api/setting/change'

import { listDeptTree } from '@/api/system/userInfo'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
    name: 'CardReplenishmentManage',
    components: { Treeselect },
    data() {
        return {
            total: 0,
            loading: false,
            deptOptions: [], // 部门下拉数据
            personSelectList: [], // 人员下拉数据
            addAndEditForm: {
                userId: '', // 用户id
                userName: '', // 姓名
                idNumber: '', // 身份证号
                orgId: '', // 部门ID
                orgName: '', // 部门名称
                currentDay: '', // 补卡日期
                attType: '', // 补卡类型 1 上午 2 下午
            },
            applyList: [],
            dialogVisible: false,
            dialogTitle: '新增',
            tableColumns: [
                {
                    label: '姓名',
                    prop: 'userName',
                },
                {
                    label: '所属部门',
                    prop: 'orgName',
                },
                {
                    label: '补卡时间',
                    prop: 'currentDay',
                },
                {
                    label: '补卡类型',
                    prop: 'attType',
                    slot: 'attType',
                },
            ],
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                userName: '',
                orgId: undefined,
            },
            // 校验规则
            addAndEditFormRules: {
                userId: [
                    {
                        required: true,
                        trigger: 'change',
                        message: '请选择人员姓名',
                    },
                ],
                currentDay: [
                    {
                        required: true,
                        trigger: 'change',
                        message: '请选择补卡日期',
                    },
                ],
                attType: [
                    {
                        required: true,
                        trigger: 'change',
                        message: '请选择补卡类型',
                    },
                ],
            },
            // 日期选择器配置
            pickerOptions: {
                disabledDate: (time) => {
                    const today = new Date()
                    const currentDay = today.getDate()
                    const currentMonth = today.getMonth()
                    const currentYear = today.getFullYear()

                    // 如果当前时间超过当月的3号
                    if (currentDay > 3) {
                        // 只能选择本月3号到今天的日期
                        const minDate = new Date(currentYear, currentMonth, 3)
                        const maxDate = new Date(today)
                        maxDate.setHours(23, 59, 59, 999)
                        return (
                            time.getTime() < minDate.getTime() ||
                            time.getTime() > maxDate.getTime()
                        )
                    } else {
                        // 如果在3号之前，可以选择上个月1号至今天的日期
                        const lastMonth =
                            currentMonth === 0 ? 11 : currentMonth - 1
                        const lastMonthYear =
                            currentMonth === 0 ? currentYear - 1 : currentYear
                        const minDate = new Date(lastMonthYear, lastMonth, 1)
                        const maxDate = new Date(today)
                        maxDate.setHours(23, 59, 59, 999)
                        return (
                            time.getTime() < minDate.getTime() ||
                            time.getTime() > maxDate.getTime()
                        )
                    }
                },
            },
        }
    },
    methods: {
        // 新增
        onHandleAdd() {
            this.getPersonSelect()
            this.dialogTitle = '新增'
            this.dialogVisible = true
        },

        // 删除
        onHandleDelete(row) {
            this.$confirm('确定删除该补卡申请吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(async () => {
                const res = await deleteCardReplenishmentManageAPI({
                    id: row.id,
                    attType: row.attType,
                })

                if (res.code === 200) {
                    this.$modal.msgSuccess('删除成功！')
                    this.getCardReplenishmentManageList()
                }
            })
        },

        // 重置
        onHandleReset() {
            this.$refs.queryFormRef.resetFields()
            this.queryParams.pageNum = 1
            this.queryParams.pageSize = 10
            this.getCardReplenishmentManageList()
        },

        // 获取补卡申请列表
        async getCardReplenishmentManageList() {
            this.loading = true
            const res = await getCardReplenishmentManageListAPI(
                this.queryParams,
            )
            this.loading = false
            this.applyList = res?.rows || []
            this.total = res?.total || 0
        },

        // 获取人员下拉数据
        async getPersonSelect() {
            const res = await getPersonSelect()
            this.personSelectList = res?.data?.map((item) => {
                return {
                    id: item.userIds,
                    userName: item.userName,
                    idNumber: item.idNumber,
                }
            })

            // 从store获取用户Id
            this.addAndEditForm.userId = this.$store.state.user.id.toString()
            this.handleChangeUserId(this.addAndEditForm.userId)
        },

        // 人员change事件
        async handleChangeUserId(value) {
            if (!value) {
                this.addAndEditForm.idNumber = ''
                this.addAndEditForm.userName = ''
                this.addAndEditForm.orgId = ''
                this.addAndEditForm.orgName = ''
                return
            }
            const userInfo = this.personSelectList.find(
                (item) => item.id === value,
            )
            if (userInfo) {
                this.addAndEditForm.idNumber = userInfo.idNumber
                this.addAndEditForm.userName = userInfo.userName
            }

            // 根据userId获取部门信息
            const res = await getOldData({
                userId: value,
                userIds: value,
            })
            this.addAndEditForm.orgId = res?.data?.oldOrgId
            this.addAndEditForm.orgName = res?.data?.oldOrgName
        },

        // 提交申请
        onHandleSubmit() {
            this.$refs.addAndEditFormRef.validate(async (valid) => {
                if (valid) {
                    // 先判断是否打卡
                    const { idNumber, userName, currentDay, attType } =
                        this.addAndEditForm
                    const res = await isCardReplenishmentManageAPI({
                        idNumber,
                        userName,
                        currentDay,
                        attType,
                    })
                    if (res.msg === '未打卡') {
                        const result = await addCardReplenishmentManageAPI(
                            this.addAndEditForm,
                        )

                        if (result.code === 200) {
                            this.$modal.msgSuccess('补卡申请提交成功！')
                            this.onHandleCloseDialog()
                            this.getCardReplenishmentManageList()
                        }
                        return
                    }
                    this.$modal.msgError(res.msg)
                }
            })
        },

        // 关闭弹框
        onHandleCloseDialog() {
            this.dialogVisible = false
            this.addAndEditForm = {
                userId: '',
                userName: '',
                idNumber: '',
            }
            this.$refs.addAndEditFormRef.resetFields()
        },

        // 获取部门列表
        getDeptList() {
            listDeptTree().then((response) => {
                this.deptOptions = this.handleTree(response.data, 'id')
            })
        },

        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children
            }
            return {
                id: node.id,
                label: node.orgName,
                children: node.children,
            }
        },
    },

    mounted() {
        this.getDeptList()
        this.getCardReplenishmentManageList()
    },
}
</script>
