<script setup lang="ts">
import { User_List } from '@/api/user/index'
import { GlobalStore } from '@/stores/index'
import { getFormatDuration } from '@/utils/common'
import Drawer from '@/components/Drawer/index.vue'
import TableBase from '@/components/TableBase/index.vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ColumnProps } from '@/components/TableBase/interface/index'
import { ref, reactive, computed, nextTick } from 'vue'
import { Leave_Finance_List, Leave_Deduct, LeaveType_List } from '@/api/workAttendance/index'
import { useTablePublic } from '@/hooks/useTablePublic'

const LeaveType = ref<any[]>([])
const globalStore = GlobalStore()
const ruleFormRef = ref<FormInstance>()
const TableRef = ref<InstanceType<typeof TableBase> | null>(null)
const initParam = reactive({ User_tokey: globalStore.GET_User_tokey, T_name: '' })
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)
const LeaveTableRef = ref<InstanceType<typeof TableBase> | null>(null)
const { tableRowClassName } = useTablePublic()
const tableRowClassNameHandle = (data: any): any => tableRowClassName(data.row.T_uuid, LeaveinitParam.T_uuid)

let date = new Date()
const month = date.getMonth()
const year = date.getFullYear()
const salaryFromData = ref({
  year: year + '',
  month: (month < 10 ? '0' : '') + month,
  T_uuid: ''
})

// 搜索以及参数
const columns: ColumnProps[] = [
  { prop: 'T_name', label: '姓名' },
  { prop: 'T_post_name', label: '职位', ellipsis: true }
]
const userColums: 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: '理由' },
  { prop: 'T_State', label: '审核', name: 'T_State' }
]
const dateCom = computed(() => {
  return `${salaryFromData.value.year}-${salaryFromData.value.month}`
})

const LeaveinitParam = reactive({
  User_tokey: globalStore.GET_User_tokey,
  T_uuid: '',
  T_month: dateCom.value
})

const getSalaryParams = (row: any) => {
  LeaveinitParam.T_uuid = ''
  setTimeout(() => {
    userInfo.name = row.T_name
    userInfo.T_dept = row.T_dept_name
    userInfo.T_post = row.T_post_name
    LeaveinitParam.T_uuid = row.T_uuid
    LeaveTableRef.value && LeaveTableRef.value.searchTable()
  }, 100)
}

const salarDateMonthChange = (val: string) => {
  if (!val) return
  if (!LeaveinitParam.T_uuid) {
    ElMessage.warning('请选择员工!!!')
  }
  LeaveinitParam.T_month = dateCom.value
  LeaveTableRef.value && LeaveTableRef?.value.searchTable()
}
const salarDateYearChange = (val: string) => {
  if (!val) return
  if (!LeaveinitParam.T_uuid) {
    ElMessage.warning('请选择员工!!!')
  }
  LeaveinitParam.T_month = dateCom.value
  LeaveTableRef.value && LeaveTableRef.value.searchTable()
}
const userInfo = reactive({
  squareUrl: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png',
  name: '',
  T_dept: '',
  T_post: ''
})

const dataCallback = (res: any): any => res.Data.Data && res.Data.Data.filter((item: any) => item.T_approver)

// drawer
const form = reactive({
  T_type: '',
  T_duration: 0,
  hover: 0,
  minute: 0,
  T_text: ''
})

const duration = computed(() => {
  return form.hover * 60 + form.minute
})

const rules = reactive<FormRules>({
  T_type: [{ required: true, message: '请选择扣除类型', trigger: 'blur' }],
  T_duration: [{ required: true, message: '请输入扣除时长', trigger: 'blur' }],
  T_text: [{ required: true, message: '请输入扣除理由', trigger: 'blur' }]
})

const Deductduraton = async () => {
  !LeaveType.value.length && getLeaveTypeList()
  drawerRef.value?.openDrawer()
}
const getLeaveTypeList = async () => {
  const res: any = await LeaveType_List({ User_tokey: globalStore.GET_User_tokey, T_deduct: 1 })
  if (res.Code === 200) {
    LeaveType.value = res.Data
  }
}
const callbackDrawer = (done: () => void) => {
  nextTick(() => {
    resetForm(ruleFormRef.value)
    done()
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  form.hover = 0
  form.minute = 0
  formEl.resetFields()
}

const AddLeave = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  form.T_duration = duration.value
  formEl.validate(async valid => {
    if (valid) {
      open()
    }
  })
}

const open = () => {
  ElMessageBox.confirm('确定扣除？扣除后无法修改?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const params = {
        User_tokey: globalStore.GET_User_tokey,
        T_type: form.T_type,
        T_duration: form.T_duration,
        T_text: form.T_text,
        T_uuid: LeaveinitParam.T_uuid,
        T_month: dateCom.value
      }
      const res: any = await Leave_Deduct(params)
      if (res.Code === 200) {
        ElMessage.success('扣除成功!')
        nextTick(() => {
          drawerRef.value?.closeDrawer()
          resetForm(ruleFormRef.value)
        })
      }
    })
    .catch(() => {
      ElMessage.info('取消成功!')
    })
}
const searchHandle = () => TableRef.value?.searchTable()
</script>

<template>
  <div class="RecordsFinance">
    <div style="width: 290px" class="RecordsFinance-table">
      <TableBase
        ref="TableRef"
        :columns="columns"
        :requestApi="User_List"
        :initParam="initParam"
        layout="prev, pager, next"
        :rowClick="getSalaryParams"
        :tableRowClassName="tableRowClassNameHandle"
      >
        <template #table-header>
          <el-row :gutter="24" class="input-suffix margin-left-0 margin-right-0">
            <el-col :span="24" class="d-flex padding-right-0 padding-left-0">
              <span class="inline-flex">姓名：</span>
              <el-input type="text" v-model="initParam.T_name" @change="searchHandle" />
              <el-button type="primary" @click="searchHandle">搜索</el-button>
            </el-col>
          </el-row>
        </template>
      </TableBase>
    </div>
    <transition
      leave-active-class="animate__animated animate__fadeOutRight"
      enter-active-class="animate__animated animate__fadeInLeft"
    >
      <el-row class="h-100 f-1 margin-left-3 RecordsFinance-container" v-if="LeaveinitParam.T_uuid">
        <el-col :span="24" class="h-100" style="overflow: hidden; display: flex; flex-direction: column">
          <el-card class="m-b-3">
            <h3 class="title m-b-5">员工基本信息</h3>
            <div class="info-content">
              <el-avatar shape="square" size="large"><img src="@/assets/images/avatar.jpg" /> </el-avatar>
              <div class="info-name">
                <h4>名字：{{ userInfo.name }}</h4>
                <h4>部门： {{ userInfo.T_dept }}</h4>
                <h4>岗位： {{ userInfo.T_post }}</h4>
              </div>
            </div>
          </el-card>
          <el-card class="m-b-3">
            <el-row :gutter="20">
              <el-col :span="10" class="d-flex justify-start">
                <span class="demonstration">年：</span>
                <el-date-picker
                  v-model="salaryFromData.year"
                  value-format="YYYY"
                  type="year"
                  placeholder="请选择年"
                  @change="salarDateYearChange"
                />
                <span class="demonstration">月：</span>
                <el-date-picker
                  v-model="salaryFromData.month"
                  popper-class="picker-date"
                  value-format="MM"
                  format="MM"
                  type="month"
                  placeholder="请选择月"
                  @change="salarDateMonthChange"
                />
              </el-col>
              <el-col :span="12" class="d-flex justify-end">
                <el-button type="primary" @click="Deductduraton">扣除时长</el-button>
              </el-col>
            </el-row>
          </el-card>
          <div style="flex: 1">
            <TableBase
              v-if="LeaveinitParam.T_uuid"
              ref="LeaveTableRef"
              :columns="userColums"
              :requestApi="Leave_Finance_List"
              :initParam="LeaveinitParam"
              layout="total,prev, pager, next"
              :displayHeader="true"
              :dataCallback="dataCallback"
            >
              <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>
            </TableBase>
          </div>
        </el-col>
      </el-row>
    </transition>
    <Drawer ref="drawerRef" :handleClose="callbackDrawer">
      <template #header="{ params }">
        <h4 :id="params.titleId" :class="params.titleClass">扣除时长</h4>
      </template>
      <el-form ref="ruleFormRef" :model="form" :rules="rules">
        <el-form-item label="扣除类型：" label-width="100px" 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="100px" prop="T_duration">
          <div class="d-flex">
            <el-input type="text" v-model.number="form.hover"><template #suffix> 小时 </template></el-input
            ><el-input type="text" v-model.number="form.minute">
              <template #suffix> 分钟 </template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label="扣除理由：" label-width="100px" prop="T_text">
          <el-input
            v-model="form.T_text"
            autocomplete="off"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6 }"
            placeholder="请输入扣除理由"
          />
        </el-form-item>
        <div class="d-flex">
          <el-button type="primary" @click="AddLeave(ruleFormRef)">提交</el-button>
        </div>
      </el-form>
    </Drawer>
  </div>
</template>

<style scoped lang="scss">
@import '@/styles/var.scss';
.RecordsFinance {
  display: flex;
  height: 100%;
  overflow: hidden;
  .RecordsFinance-table {
    @include f-direction;
    z-index: 1;
    :deep(.table-header) {
      margin-bottom: 0;
    }
    .input-suffix {
      width: 100%;
      flex-direction: column;

      .inline-flex {
        white-space: nowrap;
        display: inline-flex;
      }
    }
  }
  .RecordsFinance-container {
    z-index: 0;
    .title {
      text-align: left;
    }
    .info-content {
      display: flex;
      color: #606266;
      .info-name {
        flex: 1;
        display: flex;
        justify-content: space-around;
        align-items: center;
        padding-left: 0.75rem;
      }
    }
  }
}
.d-flex {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: nowrap;
}
.justify-start {
  justify-content: start;
}
.justify-end {
  justify-content: end;
}
</style>
