<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { Leave_User_list, LeaveType_List, Leave_Add, Leave_Edit, Leave_Del } from '@/api/workAttendance/index'
import { User_List } from '@/api/user/index'
import TableBase from '@/components/TableBase/index.vue'
import Drawer from '@/components/Drawer/index.vue'
import Dialog from '@/components/dialog/Dialog.vue'
import { ColumnProps } from '@/components/TableBase/interface/index'
import { GlobalStore } from '@/stores/index'
import { Edit, Delete } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessageBox, ElMessage } from 'element-plus'
import { dayJs } from '@/utils/common'
const globalStore = GlobalStore()
const TableRef = ref()
const columns: ColumnProps[] = [
  { prop: 'T_type_name', label: '请假类型' },
  { prop: 'T_start_time', label: '开始时间' },
  { prop: 'T_end_time', label: '结束时间' },
  { prop: 'T_duration', label: '请假时长', name: 'T_duration' },
  { prop: 'T_text', label: '理由' },
  { prop: 'T_State', label: '审核', name: 'T_State' },
  { prop: 'operation', label: '操作', width: 200, fixed: 'right' }
]
const initParam = {
  User_tokey: globalStore.GET_User_tokey
}
//drawer
const drawerRef = ref()
const ruleFormRef = ref<FormInstance>()
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.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({
          type: 'success',
          message: '删除成功！'
        })
        nextTick(() => {
          TableRef.value.getTableList()
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'warning',
        message: '取消成功！'
      })
    })
}
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 (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({
          type: 'success',
          message: `${isNew ? '申请' : '修改'}成功！`
        })
        nextTick(() => {
          drawerRef.value.closeDrawer()
          TableRef.value.getTableList()
          resetForm(ruleFormRef.value)
          isNew = true
        })
      }
    } else {
      return false
    }
  })
}
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' }]
})
let uuid = ''
const form = ref({
  T_type: '',
  T_start_time: '',
  T_end_time: '',
  T_duration: 0,
  T_text: '',
  T_approver: '',
  T_id: ''
})
const LeaveType = ref<any>([])
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
  }
}
const formLabelWidth = ref('100px')
let isNew = true
const selectApprover = () => {
  dialog.value.DialogOpen()
}

// 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 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
}
onMounted(() => {
  getLeaveTypeList()
})
</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 }"> {{ row.T_duration }}分钟 </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">
        <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;
}
</style>
