<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 { GlobalStore } from '@/stores/index'
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 { Edit, Delete, View, Plus } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { ColumnProps } from '@/components/TableBase/interface/index'
import type { FormInstance, FormRules } from 'element-plus'
import Upload from '@/components/Upload/index.vue'

let uuid = ''
let isNew = ref(true)
const search = ref('')
const TableStatRef = ref()
const disabled = ref(false)
const tableApproverRef = ref()
const globalStore = GlobalStore()
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 initParam = { User_tokey: globalStore.GET_User_tokey }

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 form = ref({
  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

  if (!isNew.value) {
    nextTick(() => {
      form.value = { ...row }
      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
    })
  }

  drawerRef.value && drawerRef.value.openDrawer()
}

const OvertimeView = (row: any) => {
  disabled.value = true
  drawerRef.value && drawerRef.value.openDrawer()
  nextTick(() => {
    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(() => {
          TableRef.value?.getTableList()
        })
      }
    })
    .catch(() => {
      ElMessage.warning('取消成功！')
    })
}
const AddOvertime = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (valid) {
      let res: any = {}
      let time = duration.value * 60
      if (isNew.value) {
        res = await Overtime_Add({ ...form.value, T_approver: uuid, T_duration: time })
      } else {
        res = await Overtime_Edit({ ...form.value, T_approver: uuid, T_duration: time })
      }
      if (res.Code === 200) {
        ElMessage.success(`${isNew.value ? '申请' : '修改'}成功！`)
        nextTick(() => {
          drawerRef.value?.closeDrawer()
          TableRef.value?.getTableList()
          resetForm(ruleFormRef.value)
          isNew.value = true
        })
      }
    } else {
      return false
    }
  })
}

// Drawer
type Fn = () => void
const callbackDrawer = (done: Fn) => {
  disabled.value = false
  isNew.value = true
  nextTick(() => {
    resetForm(ruleFormRef.value)
    done()
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  uploadRef.value?.clearfileList()
  formEl.resetFields()
}

// 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) => {
  uuid = row.T_uuid
  form.value.T_approver = row.T_name
  dialog.value?.DialogClose()
}

const duration = computed(() => {
  const end_time = dayJs(form.value.T_end_time)
  if (!form.value.T_end_time) {
    return 0
  }
  let count: number = end_time.diff(form.value.T_start_time, 'hour', true)
  let num: number = Number(count.toFixed(2))
  return Math.round(num * 10) / 10
})

const onResize = () => {
  const height = document.documentElement.clientHeight
  return height / 2
}
</script>

<template>
  <el-row :gutter="24" class="h-100">
    <el-col :span="12" class="padding-right-0 h-100">
      <TableBase
        ref="TableRef"
        :columns="columns"
        :requestApi="Overtime_User_list"
        :initParam="initParam"
        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" style="overflow: hidden">
      <TableBase
        ref="TableStatRef"
        :columns="columns_Stat"
        :requestApi="Overtime_Stat"
        :initParam="initParam"
        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">
          <el-input v-model="duration" autocomplete="off" placeholder="请假时长">
            <template #suffix> 小时 </template>
          </el-input>
        </el-form-item>
        <el-form-item label="取证：" :label-width="formLabelWidth" prop="T_prove_img">
          <Upload
            ref="uploadRef"
            :isImg="true"
            :limit="1"
            v-model="form.T_prove_img"
            :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"
        :onResize="onResize"
      >
        <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">
.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>
