<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';



import { Page, useVbenDrawer } from '@vben/common-ui';

import { ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';

import { queryFormSchema, tableColumns } from './employeePerfor-data';
import EmployeePerforDrawerComp from './employeePerfor-drawer.vue';

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: queryFormSchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-4',
};

// 模拟数据
const mockData = {
  rows: [
    {
      id: 1,
      name: '张三',
      position: '加油员',
      month: '2024-01',
      customerService: 28,
      safetyAssessment: 14,
      dailyPerformance: 22,
      performance: 18,
      selfAssessment: 9,
      totalScore: 91,
      evaluationLevelRef: '优秀',
      performanceLevel: 'A',
      comment: '工作认真负责，服务态度好',
      bonusRatio: 110,
      bonusPackageDesc: '超额完成任务',
      evaluationLevel: '优秀',
      deductionAmount: 0,
      deductionDesc: '无',
      gasStation: '第一加油站',
      licenseName: '驾驶证',
      annualReview: '1',
      annualReviewTask: '1',
      renewal: '0',
    },
    {
      id: 2,
      name: '李四',
      position: '收银员',
      month: '2024-01',
      customerService: 26,
      safetyAssessment: 15,
      dailyPerformance: 23,
      performance: 19,
      selfAssessment: 8,
      totalScore: 91,
      evaluationLevelRef: '优秀',
      performanceLevel: 'A',
      comment: '收银准确，工作效率高',
      bonusRatio: 105,
      bonusPackageDesc: '完成任务',
      evaluationLevel: '优秀',
      deductionAmount: 0,
      deductionDesc: '无',
      gasStation: '第二加油站',
      licenseName: '健康证',
      annualReview: '0',
      annualReviewTask: '0',
      renewal: '1',
    },
    {
      id: 3,
      name: '王五',
      position: '加油员',
      month: '2024-01',
      customerService: 24,
      safetyAssessment: 13,
      dailyPerformance: 21,
      performance: 17,
      selfAssessment: 9,
      totalScore: 84,
      evaluationLevelRef: '良好',
      performanceLevel: 'B',
      comment: '工作积极，需要提升服务技巧',
      bonusRatio: 95,
      bonusPackageDesc: '基本完成任务',
      evaluationLevel: '良好',
      deductionAmount: 50,
      deductionDesc: '迟到一次',
      gasStation: '第三加油站',
      licenseName: '驾驶证',
      annualReview: '1',
      annualReviewTask: '0',
      renewal: '0',
    },
  ],
  total: 3,
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
    trigger: 'default',
  },
  columns: tableColumns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        // 模拟API请求
        console.log('查询参数:', formValues, page);
        // 模拟过滤
        let filteredRows = [...mockData.rows];
        if (formValues.licenseName) {
          filteredRows = filteredRows.filter(row => 
            row.licenseName.includes(formValues.licenseName)
          );
        }
        if (formValues.annualReview) {
          filteredRows = filteredRows.filter(row => 
            row.annualReview === formValues.annualReview
          );
        }
        if (formValues.annualReviewTask) {
          filteredRows = filteredRows.filter(row => 
            row.annualReviewTask === formValues.annualReviewTask
          );
        }
        if (formValues.renewal) {
          filteredRows = filteredRows.filter(row => 
            row.renewal === formValues.renewal
          );
        }
        // 模拟分页
        const start = (page.currentPage - 1) * page.pageSize;
        const end = start + page.pageSize;
        const paginatedRows = filteredRows.slice(start, end);
        return { 
          items: paginatedRows, 
          total: filteredRows.length 
        };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'archive-personnelTraining-employeePerfor-index',
};

const [BasicTable, basicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [EmployeePerforDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: EmployeePerforDrawerComp,
});



// 编辑员工绩效
function handleEdit(row: any) {
  drawerApi.setData({ ...row, isUpdate: true }).open();
}

// 单个删除员工绩效
async function confirmEvent(row: any) {
  // 模拟删除操作
  console.log('删除员工绩效:', row.id);
  await basicTableApi.reload();
}

// 批量删除员工绩效
function deleteHandle() {
  const checkRecords = basicTableApi.grid.getCheckboxRecords();
  const ids = checkRecords.map((item: any) => item.id);
  if (ids.length <= 0) {
    return;
  }

  ElMessageBox.confirm(`确认删除选中的${ids.length}条员工绩效数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    // 模拟批量删除操作
    console.log('批量删除员工绩效:', ids);
    await basicTableApi.reload();
  });
}

// 考核说明提示框
function handleAssessmentInstructions() {
  ElMessageBox.alert(
    '1. 顾客服务：服务质量与速度/服务流程/服务态度等<br/>' +
    '2. 安全考核：前厅站位/指引车辆/安全例会学习/安全事故等<br/>' +
    '3. 日常综合表现：出勤/执行力/工作态度<br/>' +
    '4. 业绩表现：促销/拉新等<br/>' +
    '5. 自主评分：获得顾客表扬/拾金不昧/高峰主动协助加班/正确处理事件，避免事故的发生/外部参加会议等',
    '考核说明',
    { dangerouslyUseHTMLString: true }
  );
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="员工绩效">
      <template #toolbar-tools>
        <ElSpace>
          <ElButton
            type="info"
            @click="handleAssessmentInstructions"
          >
            考核说明
          </ElButton>
          <ElButton
            type="danger"
            :disabled="
              !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="deleteHandle"
          >
            批量删除
          </ElButton>

        </ElSpace>
      </template>
      <template #action="{ row }">
        <ElSpace>
          <ElButton
            size="small"
            type="primary"
            plain
            @click="handleEdit(row)"
          >
            编辑
          </ElButton>
          <ElPopconfirm title="确认删除" @confirm="confirmEvent(row)">
            <template #reference>
              <ElButton
                size="small"
                type="danger"
                plain
              >
                删除
              </ElButton>
            </template>
          </ElPopconfirm>
        </ElSpace>
      </template>
    </BasicTable>
    <EmployeePerforDrawer @reload="basicTableApi.reload()" />
  </Page>
</template>

<style scoped lang="scss">
:deep(.el-tooltip__trigger:focus) {
  outline: none;
}
</style>
