<script setup lang="ts">
import {
    Overtime_User_list,
    Overtime_Stat,
    Overtime_Add,
    Overtime_Del,
    Overtime_Edit
} from '@/api/workAttendance/index'
import { User_List } from '@/api/user/index'
import Upload from './Upload/index.vue'
import Drawer from '@/components/Drawer/index.vue'
import Dialog from '@/components/dialog/Dialog.vue'
import { floatReg } from '@/views/salary/salary/relus'
import { reactive, ref, nextTick, computed } from 'vue'
import TableBase from '@/components/TableBase/index.vue'
import { getFormatDuration, dayJs } from '@/utils/common'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useTablePublic } from '@/hooks/useTablePublic'
import type { FormInstance, FormRules } from 'element-plus'
import { Edit, Delete, View, Plus } from '@element-plus/icons-vue'
import { ColumnProps } from '@/components/TableBase/interface/index'


let showWatch = ref(true)
let isNew = ref(true)
const search = ref('')
const TableStatRef = ref()
const disabled = ref(false)
const tableApproverRef = ref()
const formLabelWidth = ref('100px')
const ruleFormRef = ref<FormInstance>()
const dialog = ref<InstanceType<typeof Dialog> | null>(null)
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)
const TableRef = ref<InstanceType<typeof TableBase> | null>(null)
const uploadRef = ref<InstanceType<typeof Upload> | null>(null)
const { resetForm, globalStore, updateOnTableList } = useTablePublic()

const columns: ColumnProps[] = [
    { prop: 'T_start_time', label: '开始时间', ellipsis: true },
    { prop: 'T_end_time', label: '结束时间', ellipsis: true },
    { prop: 'T_duration', label: '时长', width: '100px', name: 'T_duration' },
    { prop: 'T_State', label: '审核', width: '100px', name: 'T_State' },
    { prop: 'operation', label: '操作', width: 200, fixed: 'right' }
]
const columns_Stat: ColumnProps[] = [
    { prop: 'T_duration', label: '时长', width: '100px', name: 'T_duration' },
    { prop: 'RemainingTime', label: '剩余时长', width: '100px', name: 'RemainingTime' },
    { prop: 'T_type_name', label: '事项' },
    { prop: 'T_approver_name', label: '处理人' },
    { prop: 'UpdateTime', label: '时间', ellipsis: true }
]
const fileListImg: any = ref([])
const form:any = ref({
    uuid: '',
    T_id: '',
    T_text: '',
    T_duration: 0,
    T_end_time: '',
    T_approver: '',
    T_prove_img: '',
    T_start_time: ''
})
const validate_float = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入加班时长'))
    } else {
        if (floatReg.test(value) || /\d+/.test(value)) {
            callback()
        } else {
            callback(new Error('时间必须是数字或小数'))
        }
    }
}
const rules = reactive<FormRules>({
    T_type: [{ required: true, message: '请选择请假类型', trigger: 'blur' }],
    T_start_time: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
    T_end_time: [{ required: true, message: '请选择结束时间', trigger: 'blur' }],
    T_duration: [{ required: true, validator: validate_float, trigger: 'blur' }],
    T_approver: [{ required: true, message: '请选择审批人', trigger: 'blur' }]
})

const openDrawerOvertime = (str: string, row?: any) => {
    isNew.value = str === 'new' ? true : false
    showWatch.value = str == 'new' ? true : false
    if (!isNew.value) {
        nextTick(() => {
            form.value = { ...row }
            form.value.uuid = row.T_approver
            form.value.T_approver = row.T_approver_name
            form.value.T_id = row.Id
            form.value.T_duration = row.T_duration / 60
            fileListImg.value = row.T_prove_img.split('|')
        })
    }else{
        fileListImg.value = []
    }
    drawerRef.value && drawerRef.value.openDrawer()
    


}

const OvertimeView = (row: any) => {
    showWatch.value = false
    disabled.value = true
    drawerRef.value && drawerRef.value.openDrawer()
    nextTick(() => {
        fileListImg.value = row.T_prove_img.split('|')
        form.value = { ...row }
        form.value.T_approver = row.T_approver_name
    })
}
const OvertimeDelete = (row: any) => {
    ElMessageBox.confirm('您确定要删除加班申请吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            const res: any = await Overtime_Del({ User_tokey: globalStore.GET_User_tokey, T_id: row.Id })
            if (res.Code === 200) {
                ElMessage.success('删除成功！')
                nextTick(() => updateOnTableList(TableRef.value))
            }
        })
        .catch(() => {
            ElMessage.warning('取消成功！')
        })
}
const AddOvertime = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async valid => {
        if (valid) {
            if (fileListImg.value.length < 3) {
                ElMessage.error(`取证图片至少3张以上`)
                return
            }
            let mapImg = [...fileListImg.value]
            form.value.T_prove_img = mapImg.join('|')
            let res: any = {}
            let time = duration.value * 60 + minutes.value
            console.log('提交minutes', duration.value, minutes.value, time)
            if (time < 0) { ElMessage.error('时间选择错误，请重新选择'); return }
            if (isNew.value) {
                res = await Overtime_Add({ ...form.value, T_approver: form.value.uuid, T_duration: time })
            } else {
                res = await Overtime_Edit({ ...form.value, T_approver: form.value.uuid, T_duration: time })
            }
            if (res.Code === 200) {
                ElMessage.success(`${isNew.value ? '申请' : '修改'}成功！`)
                nextTick(() => {
                    drawerRef.value?.closeDrawer()
                    updateOnTableList(TableRef.value)
                    resetForm(ruleFormRef.value)
                    uploadRef.value?.clearfileList()
                    isNew.value = true
                })
            }
        } else {
            return
        }
    })
}

// Drawer
const callbackDrawer = (done: () => void) => {
    disabled.value = false
    isNew.value = true
    nextTick(() => {
        resetForm(ruleFormRef.value)
        uploadRef.value?.clearfileList()
        done()
    })
}

// dialog
const Dialogcolumns: ColumnProps[] = [{ prop: 'T_name', label: '名字', name: 'T_name' }]
const approverInitParam = {
    User_tokey: globalStore.GET_User_tokey,
    T_name: '',
    T_dept_leader: 1
}
const searchHandle = () => {
    approverInitParam.T_name = search.value
    tableApproverRef.value.searchTable()
}
const selectApprover = () => {
    dialog.value?.DialogOpen()
}
const getApproverInfo = (row: any) => {
    form.value.uuid = row.T_uuid
    form.value.T_approver = row.T_name
    dialog.value?.DialogClose()
}


const duration = computed(() => {
    if (!form.value.T_start_time || !form.value.T_end_time) { return 0 }
    let strTime = form.value.T_start_time
    let endTime = form.value.T_end_time
    var endDate: any = new Date(strTime) //开始时间 
    var nowDate: any = new Date(endTime) //结束时间 
    let h: any = (nowDate - endDate) / (60 * 60 * 1000)
    return parseInt(h) //获取小时部分 
})
const minutes = computed(() => {
    if (!form.value.T_start_time || !form.value.T_end_time) { return 0 }
    let strTime = form.value.T_start_time
    let endTime = form.value.T_end_time
    var endDate: any = new Date(strTime) //开始时间 
    var nowDate: any = new Date(endTime) //结束时间 
    let m: any = (nowDate - endDate) % (60 * 60 * 1000) / (60 * 1000); //获取分钟部分
    return parseInt(m)
})
</script>

<template>
    <el-row :gutter="24" class="h-100">
        <el-col :span="12" class="padding-right-0 h-100 my-overtime-table-left">
            <TableBase ref="TableRef" :columns="columns" :requestApi="Overtime_User_list"
                :initParam="{ User_tokey: globalStore.GET_User_tokey }" layout="total,sizes,prev, pager, next">
                <template #table-header>
                    <div class="table-header">
                        <h4>我的加班</h4>
                        <el-button type="primary" @click="openDrawerOvertime('new')">申请加班</el-button>
                    </div>
                </template>
                <template #T_duration="{ row }"> {{ getFormatDuration(row.T_duration) }} </template>
                <template #T_State="{ row }">
                    <el-tag v-if="row.T_State === 1" type="success">通过</el-tag>
                    <el-tag v-else-if="row.T_State === 2" type="warning">未通过</el-tag>
                    <el-tag v-else type="danger">待审核</el-tag>
                </template>
                <template #right="{ row }">
                    <el-button :disabled="row.T_State === 1" link type="primary" size="small" :icon="Edit"
                        @click="openDrawerOvertime('edit', row)">编辑</el-button>
                    <el-button :disabled="row.T_State === 1" link type="danger" size="small" :icon="Delete"
                        @click="OvertimeDelete(row)">删除</el-button>
                    <el-button link type="success" size="small" :icon="View" @click="OvertimeView(row)">查看</el-button>
                </template>
            </TableBase>
        </el-col>
        <el-col :span="12" class="h-100 my-overtime-table-right" style="overflow: hidden">
            <TableBase ref="TableStatRef" :columns="columns_Stat" :requestApi="Overtime_Stat"
                :initParam="{ User_tokey: globalStore.GET_User_tokey }" layout="total,sizes,prev, pager, next">
                <template #table-header="{ pageable }">
                    <el-button text>
                        <h4>
                            <el-text class="mx-1" type="primary">剩余总时长：{{ getFormatDuration(pageable.RemainingTime as number) }}</el-text>
                        </h4>
                    </el-button></template>
                <template #T_duration="{ row }">{{ getFormatDuration(row.T_duration) }} </template>
                <template #RemainingTime="{ row }">{{ getFormatDuration(row.RemainingTime) }} </template>
            </TableBase>
        </el-col>
        <Drawer ref="drawerRef" :handleClose="callbackDrawer">
            <template #header="{ params }">
                <h4 :id="params.titleId" :class="params.titleClass">{{ isNew ? '添加' : '编辑' }} - 申请</h4>
            </template>
            <el-form ref="ruleFormRef" :model="form" :rules="rules">
                <el-form-item label="开始时间：" :label-width="formLabelWidth" prop="T_start_time">
                    <el-date-picker style="width: 100%" class="my-date-picker" v-model="form.T_start_time"
                        type="datetime" :disabled="disabled" placeholder="选择开始时间" format="YYYY-MM-DD HH:mm"
                        value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
                <el-form-item label="结束时间：" :label-width="formLabelWidth" prop="T_end_time">
                    <el-date-picker style="width: 100%" class="my-date-picker" v-model="form.T_end_time" type="datetime"
                        :disabled="disabled" placeholder="选择结束时间" format="YYYY-MM-DD HH:mm"
                        value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
                <el-form-item label="加班时长：" :label-width="formLabelWidth" prop="T_duration">
                    <template style="display: flex;align-items: center;gap:20px">
                        <el-input v-model="duration" autocomplete="off" placeholder="请假时长">
                            <template #suffix> 小时 </template>
                        </el-input>
                        <el-input v-model="minutes" autocomplete="off" placeholder="请假时长">
                            <template #suffix> 分钟 </template>
                        </el-input>
                    </template>
                </el-form-item>
                <el-form-item label="取证：" :label-width="formLabelWidth" >
                    <Upload ref="uploadRef" :showWatch="showWatch" :limit="10" v-model:modelValue="fileListImg" :disabled="disabled"
                        accept="image/*">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </Upload>
                </el-form-item>
                <el-form-item label="内容：" :label-width="formLabelWidth" prop="T_text">
                    <el-input v-model="form.T_text" :disabled="disabled" autocomplete="off" type="textarea"
                        :autosize="{ minRows: 4, maxRows: 6 }" placeholder="请输入内容" />
                </el-form-item>
                <el-form-item label="审批：" :label-width="formLabelWidth" prop="T_approver">
                    <el-input :disabled="disabled" v-model="form.T_approver" autocomplete="off" placeholder="审批人"
                        @focus="selectApprover" />
                </el-form-item>
                <el-form-item :label-width="formLabelWidth">
                    <el-button v-if="isNew" color="#626aef" @click="AddOvertime(ruleFormRef)"
                        :disabled="disabled">添加</el-button>
                    <el-button v-else color="#626aef" @click="AddOvertime(ruleFormRef)">修改</el-button>
                </el-form-item>
            </el-form>
        </Drawer>
        <Dialog ref="dialog" width="30%">
            <template #header>
                <h3>选择审批人</h3>
            </template>
            <TableBase ref="tableApproverRef" :columns="Dialogcolumns" :initParam="approverInitParam"
                :requestApi="User_List" layout="total, prev, pager, next">
                <template #table-header>
                    <el-row :gutter="20">
                        <el-col :span="20" class="d-flex">
                            <span class="inline-flex">账户查询：</span>
                            <el-input v-model="search" type="text" class="w-50 m-2" />
                            <el-button type="primary" @click="searchHandle">搜索</el-button>
                        </el-col>
                    </el-row>
                </template>
                <template #T_name="{ row }">
                    <el-button type="primary" link @click="getApproverInfo(row)">{{ row.T_name }}</el-button>
                </template>
            </TableBase>
        </Dialog>
    </el-row>
</template>

<style scoped lang="scss">
@import '@/styles/var.scss';

.my-overtime-table-left,
.my-overtime-table-right {
    @include f-direction;
}

.table-header {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.full-img {
    width: 100%;
    height: 100%;
}

.d-flex {
    display: flex;
    align-items: center;

    .inline-flex {
        white-space: nowrap;
    }
}

.mx-1 {
    letter-spacing: 1px;
}
</style>
