<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 { UpFileToken } from '@/api/public/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 } from 'vue'
import TableBase from '@/components/TableBase/index.vue'
import { getFormatDuration } from '@/utils/common'
import { Edit, Delete, View, Plus } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage, genFileId } from 'element-plus'
import { ColumnProps } from '@/components/TableBase/interface/index'
import type { FormInstance, FormRules, UploadProps, UploadRawFile } from 'element-plus'

let uuid = ''
let isNew = 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 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 openDrawerOvertime = (str: string, row: any) => {
  drawerRef.value && drawerRef.value.openDrawer()
  if (str === 'edit') {
    isNew = false
    nextTick(() => {
      form.value = { ...row }
      uuid = row.T_approver
      form.value.T_approver = row.T_user_name
      form.value.T_id = row.Id
      form.value.T_prove_img = import.meta.env.VITE_BZD_ERPOSS_APP_API + form.value.T_prove_img
      fileList.value.push({
        name: 'food.jpeg',
        url: form.value.T_prove_img
      })
    })
  }
}

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

// Drawer
type Fn = () => void
const callbackDrawer = (done: Fn) => {
  disabled.value = false
  isNew = false
  nextTick(() => {
    resetForm(ruleFormRef.value)
    done()
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  fileList.value = []
  formEl.resetFields()
}
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 form = ref({
  T_id: '',
  T_text: '',
  T_duration: 0,
  T_end_time: '',
  T_approver: '',
  T_prove_img: '',
  T_start_time: ''
})
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' }]
})

// 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 onResize = () => {
  const height = document.documentElement.clientHeight
  return height / 2
}

// upload file
interface FileListType {
  url: string
  name: string
}
let prove_img = true
const upload = ref()
const fileList = ref<FileListType[]>([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
let uploadData = { token: '', key: '' }

// 图片查看 放大
const handlePictureCardPreview = async (file: any) => {
  dialogImageUrl.value = file.url as string
  dialogVisible.value = true
}
// 图片上传之前
const beforeUpload = async (file: any) => {
  let reg = /^image/g
  if (!reg.test(file.type)) {
    ElMessage.error('必须上传图片!!')
    return
  }
  prove_img = false
  let suffix = file.type.split('/')[1]
  const res: any = await UpFileToken({ User_tokey: globalStore.GET_User_tokey, T_suffix: suffix })
  uploadData.token = res.Data
  uploadData.key = file.name
}
// 图片上传超出界限
const handleExceed: UploadProps['onExceed'] = (files: any) => {
  upload.value.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value.handleStart(file)
  upload.value.submit()
}
// 图片上传成功
const onSuccess = (response: any) => {
  form.value.T_prove_img = response.key
  prove_img = true
  ElMessage.success('图片上传成功!!')
}
// 图片上传失败
const onError = () => {
  ElMessage.error('图片上传失败!!')
}
// 图片移除
const handleRemove: UploadProps['onRemove'] = () => {
  form.value.T_prove_img = ''
}
</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">申请加班</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
            :disabled="row.T_State !== 1"
            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:ss"
            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:ss"
            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.number="form.T_duration" autocomplete="off" placeholder="请假时长" />
        </el-form-item>
        <el-form-item label="取证：" :label-width="formLabelWidth">
          <el-upload
            ref="upload"
            :disabled="disabled"
            v-model:file-list="fileList"
            action="https://up-z2.qiniup.com"
            list-type="picture-card"
            :limit="1"
            :auto-upload="true"
            :before-upload="beforeUpload"
            :on-success="onSuccess"
            :on-error="onError"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
            :on-preview="handlePictureCardPreview"
            :data="uploadData"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" class="full-img" alt="Preview Image" />
          </el-dialog>
        </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>
