<script setup lang="ts">
import {
  Leave_User_list,
  LeaveType_List,
  Leave_Add,
  Leave_Edit,
  Leave_Del,
  Leave_DaysOff
} from '@/api/workAttendance/index'
import { GlobalStore } from '@/stores/index'
import { User_List } from '@/api/user/index'
import Drawer from '@/components/Drawer/index.vue'
import Dialog from '@/components/dialog/Dialog.vue'
import { Edit, Delete } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import TableBase from '@/components/TableBase/index.vue'
import { getFormatDuration } from '@/utils/common'
import type { FormInstance, FormRules } from 'element-plus'
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ColumnProps } from '@/components/TableBase/interface/index'

let uuid = ''
let isNew = true
const LeaveType = ref<any>([])
const globalStore = GlobalStore()
const formLabelWidth = ref('100px')
const ruleFormRef = ref<FormInstance>()
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_type_name', label: '请假类型' },
  { prop: 'T_start_time', label: '开始时间', ellipsis: true },
  { prop: 'T_end_time', label: '结束时间', ellipsis: true },
  { prop: 'T_duration', label: '请假时长', name: 'T_duration' },
  { prop: 'T_text', label: '理由', ellipsis: true },
  { prop: 'T_State', label: '审核', name: 'T_State', width: 100 },
  { prop: 'operation', label: '操作', width: 200, fixed: 'right' }
]

//drawer
type Fn = () => void
const callbackDrawer = (done: Fn) => {
  resetForm(ruleFormRef.value)
  done()
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const openDrawerLeave = (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
    })
  }
}
const LeaveDelete = (row: any) => {
  ElMessageBox.confirm('您确定要删除请假申请吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res: any = await Leave_Del({ User_tokey: globalStore.GET_User_tokey, T_id: row.Id })
      if (res.Code === 200) {
        ElMessage.success('删除成功！')
        nextTick(() => {
          TableRef.value && TableRef.value.getTableList()
        })
      }
    })
    .catch(() => {
      ElMessage.warning('取消成功！')
    })
}
const AddLeave = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (valid) {
      let res: any = {}
      form.value.T_duration = form.value.T_duration * 60
      if (form.value.T_duration > RemainingTime.value) {
        ElMessage.warning('请假时长不得大于剩余时长，请重新选择时间！！')
        return
      }
      if (isNew) {
        res = await Leave_Add({ ...form.value, T_approver: uuid })
      } else {
        res = await Leave_Edit({ ...form.value, T_approver: uuid })
      }
      if (res.Code === 200) {
        ElMessage.success(`${isNew ? '申请' : '修改'}成功！`)
        nextTick(() => {
          drawerRef.value && drawerRef.value.closeDrawer()
          TableRef.value && TableRef.value.getTableList()
          resetForm(ruleFormRef.value)
          isNew = true
        })
      }
    } else {
      return false
    }
  })
}

const form = ref({
  T_id: '',
  T_text: '',
  T_type: '',
  T_duration: 0,
  T_end_time: '',
  T_approver: '',
  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, message: '请输入请假时长', trigger: 'blur' },
    { type: 'number', message: '必须是整数' }
  ],
  T_approver: [{ required: true, message: '请选择审批人', trigger: 'blur' }]
})

const getLeaveTypeList = async () => {
  const res: any = await LeaveType_List({ User_tokey: globalStore.GET_User_tokey, page: 1, page_z: 999 })
  if (res.Code === 200) {
    LeaveType.value = res.Data
  }
}
// dialog
const dialog = ref()
const search = ref('')
const tableApproverRef = ref()
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 RemainingTime = ref(0)
const getLeaveDaysOff = async () => {
  const res: any = await Leave_DaysOff({ User_tokey: globalStore.GET_User_tokey })
  RemainingTime.value = res.Data
}

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

<template>
  <div>
    <TableBase ref="TableRef" :columns="columns" :requestApi="Leave_User_list" :initParam="initParam">
      <template #table-header>
        <el-row :gutter="24" class="input-suffix">
          <el-col :span="8" :offset="16" class="d-flex padding-right-0">
            <el-button type="primary" @click="openDrawerLeave">请假申请</el-button>
          </el-col>
        </el-row>
      </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 #T_duration="{ row }">
        <el-tag effect="dark"> {{ row.T_duration }}分钟 </el-tag>
      </template>
      <template #right="{ row }">
        <el-button link type="primary" size="small" :icon="Edit" @click="openDrawerLeave('edit', row)">编辑</el-button>
        <el-button link type="danger" size="small" :icon="Delete" @click="LeaveDelete(row)">删除</el-button>
      </template>
    </TableBase>
    <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">
        <span class="daysOff"
          >剩余可调休时长：<el-tag type="danger" effect="dark"> {{ getFormatDuration(RemainingTime) }} </el-tag></span
        >
        <el-form-item label="请假类型：" :label-width="formLabelWidth" prop="T_type">
          <el-select v-model="form.T_type" placeholder="请选择类型">
            <el-option v-for="item in LeaveType" :key="item.Id" :label="item.T_name" :value="item.Id" />
          </el-select>
        </el-form-item>
        <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"
            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"
            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-input
            v-model="form.T_text"
            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 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="AddLeave(ruleFormRef)">添加</el-button>
          <el-button v-else color="#626aef" @click="AddLeave(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>
  </div>
</template>
<style scoped lang="scss">
.input-suffix {
  width: 100%;
}
.inline-flex {
  white-space: nowrap;
}
.d-flex {
  display: flex;
  align-items: center;
}
.daysOff {
  margin-bottom: 1rem;
  display: inline-block;
}
</style>
