<template>
  <div>
    <el-form :model="searchForm" ref="searchFormRef" inline @submit.prevent>
      <el-form-item>
        <el-date-picker
          v-model="searchForm.period"
          type="month"
          format="YYYY-MM"
          value-format="YYYY-MM"
          placeholder="年月"
          style="width: 100%"
          @change="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-input
          v-model.trim="searchForm.dept"
          placeholder="组织名称"
          clearable
          @keyup.enter="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-input
          v-model.trim="searchForm.name"
          placeholder="员工姓名"
          clearable
          @keyup.enter="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleSearch" v-hasPermi="['home:false-dilegence:search']">
          查询
        </el-button>
        <el-button @click="handleSync" v-hasPermi="['home:false-dilegence:sync']">
          同步钉钉假勤
        </el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="tableList"
      border
      stripe
      :default-expand-all="false"
      row-key="id"
      :tree-props="{ children: 'userDingAttendanceRespVOList', hasChildren: 'hasChildren' }"
      :span-method="spanMethod"
    >
      <el-table-column label="姓名" min-width="90px" fixed="left">
        <template #default="{ row }">
          <span v-if="row.userDingAttendanceRespVOList && row.userDingAttendanceRespVOList.length">
            <span>{{ row.period }}</span>
            <span class="ml-20px">考勤人数：{{ row.attendanceUserCount }}人</span>
            <span class="ml-20px">不考勤人数：{{ row.notAttendanceUserCount }}人</span>
          </span>
          <span v-else>
            {{ row.employeeName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="period" label="年月" min-width="90px" />
      <el-table-column prop="dept" label="组织" min-width="90px" />
      <el-table-column label="是否考勤" min-width="90px">
        <template #default="{ row }">
          {{ row.needAttendance ? '考勤' : '不考勤' }}
        </template>
      </el-table-column>
      <el-table-column prop="shouldWorkDay" label="应出勤天数" min-width="90px" />
      <el-table-column prop="paidLeaveDay" label="带薪假天数" min-width="90px" />
      <el-table-column label="出勤天数" align="center">
        <template #default="{ row }">
          <el-input-number
            v-if="row.edit"
            v-model="row.reallyWorkDay"
            :min="0"
            :controls="false"
            size="small"
            style="width: 65px"
          />
          <span v-else> {{ row.reallyWorkDay }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调休天数" align="center">
        <template #default="{ row }">
          <el-input-number
            v-if="row.edit"
            v-model="row.compensatoryLeaveDay"
            :min="0"
            :controls="false"
            size="small"
            style="width: 65px"
          />
          <span v-else> {{ row.compensatoryLeaveDay }}</span>
        </template>
      </el-table-column>
      <el-table-column label="缺勤天数" align="center">
        <template #default="{ row }">
          <el-input-number
            v-if="row.edit"
            v-model="row.absenceDay"
            :min="0"
            :controls="false"
            size="small"
            style="width: 65px"
          />
          <span v-else> {{ row.absenceDay }}</span>
        </template>
      </el-table-column>
      <el-table-column label="事假时长" align="center">
        <template #default="{ row }">
          <el-input-number
            v-if="row.edit"
            v-model="row.absenceLeaveDay"
            :min="0"
            :controls="false"
            size="small"
            style="width: 65px"
          />
          <span v-else> {{ row.absenceLeaveDay }}</span>
        </template>
      </el-table-column>
      <el-table-column label="婚假天数" align="center">
        <template #default="{ row }">
          <el-input-number
            v-if="row.edit"
            v-model="row.marryLeaveDay"
            :min="0"
            :controls="false"
            size="small"
            style="width: 65px"
          />
          <span v-else> {{ row.marryLeaveDay }}</span>
        </template>
      </el-table-column>
      <el-table-column label="产假天数" align="center">
        <template #default="{ row }">
          <el-input-number
            v-if="row.edit"
            v-model="row.maternityLeaveDay"
            :min="0"
            :controls="false"
            size="small"
            style="width: 65px"
          />
          <span v-else> {{ row.maternityLeaveDay }}</span>
        </template>
      </el-table-column>
      <el-table-column label="丧假天数" align="center">
        <template #default="{ row }">
          <el-input-number
            v-if="row.edit"
            v-model="row.funeralLeaveDay"
            :min="0"
            :controls="false"
            size="small"
            style="width: 65px"
          />
          <span v-else> {{ row.funeralLeaveDay }}</span>
        </template>
      </el-table-column>
      <el-table-column label="旷工天数" align="center">
        <template #default="{ row }">
          <el-input-number
            v-if="row.edit"
            v-model="row.skipWorkDay"
            :min="0"
            :controls="false"
            size="small"
            style="width: 65px"
          />
          <span v-else> {{ row.skipWorkDay }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="200">
        <template #default="{ row }">
          <el-button
            type="primary"
            style="padding: 0"
            v-if="row.edit === '0'"
            text
            v-hasPermi="['home:false-dilegence:update']"
            @click="handleEdit(row)"
          >
            修改
          </el-button>
          <el-button
            type="primary"
            v-else-if="row.edit === '1'"
            text
            style="padding: 0"
            v-hasPermi="['home:false-dilegence:update']"
            @click="handleSave(row)"
          >
            保存
          </el-button>
          <el-button
            type="danger"
            v-if="row.id"
            :disabled="row.status == 1"
            style="padding: 0"
            text
            v-hasPermi="['home:false-dilegence:sealup']"
            @click="handleSealup(row)"
          >
            <span v-if="row.status == 0">封存</span>
            <span v-else-if="row.status == 1">已封存</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      :total="total"
      v-model:page="searchForm.pageNo"
      v-model:limit="searchForm.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script setup name="FalseDilegenceReport">
import { ElLoading } from 'element-plus'
import { removeNullField } from '@/utils'
import { formatDate } from '@/utils/formatTime'
import * as FalseDiligenceApi from '@/api/home/falseDiligence.js'

const message = useMessage() // 消息弹窗

const searchForm = ref({
  name: undefined,
  period: undefined,
  dept: undefined,
  pageNo: 1,
  pageSize: 20
})

onMounted(() => {
  handleSearch()
})

function handleSearch() {
  searchForm.value.pageNo = 1
  getList()
}

const loading = ref(false)
const tableList = ref([])
const total = ref(0)
async function getList() {
  loading.value = true
  try {
    let params = {
      ...searchForm.value
    }
    if (params.period) {
      params = {
        ...params,
        year: new Date(params.period).getFullYear(),
        month: new Date(params.period).getMonth() + 1
      }
    }
    const data = await FalseDiligenceApi.getPage(removeNullField(params))
    if (searchForm.value.name) {
      tableList.value = data.list.reduce((pre, cur) => {
        return pre.concat(cur.userDingAttendanceRespVOList)
      }, [])
    } else {
      tableList.value = data.list.map((it, index) => {
        const arr = it.userDingAttendanceRespVOList.filter((user) => user.needAttendance)
        return {
          ...it,
          userDingAttendanceRespVOList: multiFieldSort(arr, [
            { key: 'dept' },
            { key: 'employeeName' }
          ]),
          id: index + 1,
          edit: it.status == 1 ? '2' : '0'
        }
      })
    }
    total.value = data.total
  } catch (err) {
    console.log(err)
  } finally {
    loading.value = false
  }
}

function multiFieldSort(arr, fields) {
  return arr.sort((a, b) => {
    // 遍历每个排序字段
    for (const field of fields) {
      const { key, order = 'asc' } = field
      const valueA = a[key]
      const valueB = b[key]

      // 处理不同类型的比较
      let compareResult
      if (typeof valueA === 'number' && typeof valueB === 'number') {
        compareResult = valueA - valueB // 数字比较
      } else {
        compareResult = String(valueA).localeCompare(String(valueB)) // 字符串比较（兼容其他类型）
      }

      // 如果当前字段值不相等，直接返回比较结果（根据排序方向调整）
      if (compareResult !== 0) {
        return order === 'desc' ? -compareResult : compareResult
      }
    }
    // 所有字段都相等，保持原有顺序
    return 0
  })
}

function spanMethod({ row, columnIndex }) {
  if (row.userDingAttendanceRespVOList && row.userDingAttendanceRespVOList.length > 0) {
    if (columnIndex === 0) {
      return [1, 14]
    } else if (columnIndex == 14 && row.id) {
      return [1, 1]
    } else {
      return [0, 0]
    }
  }
}

let globalLoading = ref({})

async function handleSync() {
  try {
    const result = await message.prompt('请输入年月，如2024-01')
    const period = formatDate(new Date(result.value), 'YYYY-MM')
    globalLoading.value = ElLoading.service({
      lock: true,
      text: `正在同步${period}假勤数据，请稍后...`,
      background: 'rgba(0, 0, 0, 0.7)'
    })
    await FalseDiligenceApi.syncFalseDiligence({ period })
    globalLoading.value.close()
    message.success(`同步成功！`)
    getList()
  } catch {
    globalLoading.value.close()
  }
}

function handleEdit(row) {
  row.edit = '1'
  row.userDingAttendanceRespVOList.forEach((it) => (it.edit = true))
}

async function handleSave(row) {
  try {
    row.edit = '0'
    row.userDingAttendanceRespVOList.forEach((it) => (it.edit = false))
    globalLoading.value = ElLoading.service({
      lock: true,
      text: `假勤数据保存中，请稍后...`,
      background: 'rgba(0, 0, 0, 0.7)'
    })
    await FalseDiligenceApi.updateFalseDiligence(row.userDingAttendanceRespVOList)
    globalLoading.value.close()
    message.success('保存成功！')
    getList()
  } catch {
    globalLoading.value.close()
  }
}

async function handleSealup(row) {
  try {
    // 二次确认
    await message.confirm('确认要封存"' + row.period + '"假勤吗?')
    // 发起修改状态
    await FalseDiligenceApi.saveFalseDiligence({
      period: row.period
    })
    message.success('封存成功！')
    // 刷新列表
    await getList()
  } catch (err) {
    console.log(err)
  }
}
</script>

<style lang="scss" scoped>
:deep(.el-table__indent) {
  display: none;
}

:deep(.el-table__placeholder) {
  display: none;
}
</style>
