<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 Pagination from '@/components/TableBase/components/Pagination.vue'
import { ref, reactive, onMounted, computed, onUnmounted, nextTick } from 'vue'
import { Leave_Finance_List, Leave_Deduct, LeaveType_List } from '@/api/workAttendance/index'

const TableData = ref()
const LeaveType = ref<any[]>([])
const globalStore = GlobalStore()
const ruleFormRef = ref<FormInstance>()
const initParam = { User_tokey: globalStore.GET_User_tokey }
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)
const LeaveTableRef = ref<InstanceType<typeof TableBase> | null>(null)

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: '姓名', name: 'T_name' },
  { 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) => {
  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()
}

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 onResize = () => {
  const height = document.documentElement.clientHeight
  return height - 140 - 74 - 60 - 4 * 12
}

const getTableData = async () => {
  const res: any = await User_List({ ...initParam })
  TableData.value = res.Data.Data
  pageable.total = res.Data.Num
}
onMounted(async () => {
  await getTableData()
})
const pageable = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  small: false,
  disabled: false
})
const handleSizeChange = (val: number) => {
  pageable.pageSize = val
  LeaveTableRef.value?.getTableList()
}

const handleCurrentChange = (val: number) => {
  pageable.pageNum = val
  LeaveTableRef.value?.getTableList()
}
let clientHeight = ref(0)
const onContentResize = () => {
  const height = document.documentElement.clientHeight
  clientHeight.value = height - 140 - 60 - 3 * 12
}
onMounted(() => {
  onContentResize()
  window.onresize = onContentResize
})
onUnmounted(() => (window.onresize = null))

const tableRowClassName = (data: any): any => {
  //判断是否相等，相同时改变背景颜色
  let user: any = undefined
  if (data.row.T_uuid === LeaveinitParam.T_uuid) {
    user = data.row
  }
  if (user !== undefined) {
    let rowBackground = {
      background: '#f0f9eb',
      color: '#67c23a'
    }
    return rowBackground
  } else {
    return ''
  }
}

const dataCallback = (res: any): any => {
  return 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' }]
})

type Fn = () => void
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: Fn) => {
  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('取消成功!')
    })
}
</script>

<template>
  <div class="RecordsFinance">
    <div style="width: 290px; display: flex; padding: 20px; background: #fff; flex-direction: column">
      <el-table
        class="h-100"
        style="width: 100%; height: 100%; flex: 1"
        :data="TableData"
        @row-click="getSalaryParams"
        :row-style="tableRowClassName"
      >
        <el-table-column
          align="center"
          v-for="item in columns"
          :label="item.label"
          :prop="item.prop"
          :key="item.prop"
        />
      </el-table>
      <Pagination
        layout="total, prev, pager, next"
        :pageable="pageable"
        :handleSizeChange="handleSizeChange"
        :handleCurrentChange="handleCurrentChange"
      />
    </div>
    <transition
      leave-active-class="animate__animated animate__bounceOutRight"
      enter-active-class="animate__animated animate__bounceInDown"
    >
      <el-row class="h-100 f-1 margin-left-3" v-if="LeaveinitParam.T_uuid">
        <el-col :span="24" class="h-100" style="overflow: hidden">
          <el-card class="m-b-3">
            <h3 class="title m-b-5">员工基本信息</h3>
            <div class="info-content">
              <el-avatar shape="square" size="large" :src="userInfo.squareUrl" />
              <div class="info-name">
                <h4 class="m-b-3">名字：{{ userInfo.name }}</h4>
                <h4>
                  <span>部门：{{ userInfo.T_dept }}</span>
                  <span>岗位：{{ userInfo.T_post }}</span>
                </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="{ height: clientHeight + 'px' }">
            <TableBase
              v-if="LeaveinitParam.T_uuid"
              ref="LeaveTableRef"
              :columns="userColums"
              :requestApi="Leave_Finance_List"
              :initParam="LeaveinitParam"
              layout="total,prev, pager, next"
              :onResize="onResize"
              :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">
.RecordsFinance {
  display: flex;
  height: 100%;
  overflow: hidden;
  .w-100 {
    width: 100%;
  }
}
.d-flex {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: nowrap;
}
.justify-start {
  justify-content: start;
}
.justify-end {
  justify-content: end;
}
.input-suffix {
  width: 100%;
  flex-direction: column;
  .w-50 {
    width: 12.5rem;
  }

  .inline-flex {
    white-space: nowrap;
    display: inline-flex;
  }
}
.title {
  text-align: left;
}
.info-content {
  display: flex;
  color: #606266;
  .info-name {
    display: flex;
    flex-direction: column;
    padding-left: 0.75rem;
    span:first-child {
      margin-right: 2rem;
    }
  }
}
</style>
