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

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

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

import { ElMessage, ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  addbaseApi,
  copybaseApi,
  editbaseApi,
  querybaseApilist,
  startbaseApi,
  xiangqigApi,
} from '#/api/system/tasksettings/tasktemplate';

import {
  formActions,
  getTaskFrequencyOptions,
  PersoninchargeOptions,
  positionsOptions,
  queryFormSchema,
  tableColumns,
} from './taskTemplate-data';
import taskTemplateDrawerComp from './taskTemplate-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',
  formActions,
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
    trigger: 'default',
  },
  columns: tableColumns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const res = await querybaseApilist({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        // console.log(res);
        return {
          items: res?.rows,
          total: res?.total,
        };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'system-checklis-taskTemplate-index',
};

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

const [taskTemplateDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: taskTemplateDrawerComp,
  // 设置抽屉宽度为700px，使用class属性覆盖默认宽度
  class: 'w-[850px]',
  // 禁止点击遮罩层关闭抽屉
  closeOnClickModal: false,
});

// 新增任务
function openDrawer() {
  drawerApi.setData({ isUpdate: false }).open();
}

// 查看任务
async function handleView(row: any) {
  try {
    const res = await xiangqigApi(row.id);
    drawerApi
      .setData({
        ...res,
        isView: true,
        executePosition: Number(res.executePosition),
        taskLeader: Number(res.taskLeader),
        isLicensable: String(res.isLicensable),
        isRating: String(res.isRating),
        isMust: String(res.isMust),
        executionMethod: String(res.executionMethod),
        status: String(res.status),
        isTiming: String(res.isTiming),
        level: String(res.level),
        repel: Number(res.repel),
      })
      .open();
  } catch (error) {
    console.error('任务编辑失败:', error);
    ElMessage.error('任务编辑失败');
  }
}

// 编辑任务
async function handleEdit(row: any) {
  try {
    const res = await xiangqigApi(row.id);
    console.log(res);
    drawerApi
      .setData({
        ...res,
        isUpdate: true,
        executePosition: Number(res.executePosition),
        taskLeader: Number(res.taskLeader),
        isLicensable: String(res.isLicensable),
        isRating: String(res.isRating),
        isMust: String(res.isMust),
        executionMethod: String(res.executionMethod),
        status: String(res.status),
        isTiming: String(res.isTiming),
        level: String(res.level),
        repel: Number(res.repel),
      })
      .open();
  } catch (error) {
    console.error('任务编辑失败:', error);
    ElMessage.error('任务编辑失败');
  }
}
// executePosition
// 复制任务
async function handleCopy(row: any) {
  try {
    await copybaseApi({ id: row.id });
    ElMessage.success('任务复制成功');
  } catch (error) {
    console.error('任务复制失败:', error);
    ElMessage.error('任务复制失败');
  }
  // drawerApi.setData({ ...row, isCopy: true, id: '' }).open();
}

// 分发任务
async function handleDistribute(row: any) {
  try {
    await startbaseApi({ id: row.id });
    ElMessage.success('任务分发成功');
    basicTableApi.reload();
  } catch (error) {
    console.error('任务分发失败:', error);
    ElMessage.error('任务分发失败');
  }
  // drawerApi.setData({ ...row, isCopy: true, id: '' }).open();
}

// 导出任务模板
function handleExport() {
  console.log('导出任务模板');
  ElMessageBox.alert('任务模板导出功能待实现', '提示');
}

const handleConfirm = async (data: any) => {
  console.log('提交数据', data);

  drawerApi.drawerLoading(true);
  try {
    data.standardGuideline = '14,17';
    data.files = data?.attachment
      ?.map((item: any) => item.response.data.fileName)
      .join(',');

    // 根据是否包含 id 来决定调用新增接口还是编辑接口
    if (data.id) {
      // 编辑操作
      await editbaseApi({ ...data, id: data.id });
    } else {
      // 新增操作
      await addbaseApi(data);
    }

    drawerApi.close();
    // 刷新表格数据
    basicTableApi.reload();
  } catch (error) {
    console.error('保存任务模板失败:', error);
  } finally {
    drawerApi.drawerLoading(false);
  }
};
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="任务模板列表">
      <template #toolbar-tools>
        <ElSpace>
          <ElButton type="primary" @click="openDrawer"> 新增任务 </ElButton>
          <ElButton type="primary" ghost @click="handleExport"> 导出 </ElButton>
        </ElSpace>
      </template>
      <template #taskLeader="{ row }">
        {{
          PersoninchargeOptions.find(
            (item: any) => item.value == row.taskLeader,
          )?.label || '-'
        }}
      </template>
      <template #executePosition="{ row }">
        {{
          positionsOptions.find(
            (item: any) => item.value == row.executePosition,
          )?.label || '-'
        }}
      </template>
      <template #taskFrequency="{ row }">
        {{
          getTaskFrequencyOptions().find(
            (item: any) => item.value == row.taskFrequency,
          )?.label || '-'
        }}
      </template>
      <template #status="{ row }">
        <ElTag
          :type="
            row.status === '启用' || row.status === 0 ? 'success' : 'danger'
          "
        >
          {{
            row.status === 0 ? '启用' : row.status === 1 ? '关闭' : row.status
          }}
        </ElTag>
      </template>
      <template #isTiming="{ row }">
        <ElTag>
          {{
            row.isTiming === 0 ? '否' : row.isTiming === 1 ? '是' : row.isTiming
          }}
        </ElTag>
      </template>
      <template #action="{ row }">
        <ElSpace>
          <ElButton size="small" type="primary" plain @click="handleView(row)">
            查看
          </ElButton>
          <ElButton size="small" type="primary" plain @click="handleEdit(row)">
            编辑
          </ElButton>
          <ElButton size="small" type="primary" plain @click="handleCopy(row)">
            复制
          </ElButton>
          <ElButton
            size="small"
            type="primary"
            plain
            @click="handleDistribute(row)"
          >
            分发
          </ElButton>
        </ElSpace>
      </template>
    </BasicTable>
    <taskTemplateDrawer @confirm="handleConfirm" />
  </Page>
</template>

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