<script setup lang="ts">
// @ts-ignore: 忽略
import type { VxeGridProps } from '#/adapter/vxe-table';

import { ref } from 'vue';

// @ts-ignore: 忽略
import { useVbenDrawer, useVbenForm } from '@vben/common-ui';

import { ElMessageBox } from 'element-plus';

// @ts-ignore: 忽略
import { useVbenVxeGrid } from '#/adapter/vxe-table';
// @ts-ignore: 忽略
// 这里需要替换为实际的API，如果没有可以先注释
import { handleTankWater } from '#/api/task';

// @ts-ignore: 忽略
import { defautTableColumns, drawerFormSchema } from './config-data.tsx';

const emit = defineEmits<{ reload: [] }>();

// 初始化表单配置
const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  schema: drawerFormSchema(),
});

// 初始化任务参数
const taskParams: any = ref({
  taskId: '',
  taskName: '',
  taskList: null,
  subFormType: '',
});

// 初始化抽屉组件
const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      return;
    }
    try {
      drawerApi.drawerLoading(true);
      const { taskId, taskName, taskList, subFormType } = drawerApi.getData();
      taskParams.value.taskId = taskId;
      taskParams.value.taskName = taskName;
      taskParams.value.taskList = taskList;
      taskParams.value.subFormType = subFormType;

      // 如果有任务数据，填充表单
      if (taskList && taskList.length > 0) {
        formApi.setValues(taskList[0]);
      } else {
        formApi.resetForm();
      }
    } catch (error) {
      console.error(error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },
  onClosed() {
    formApi.resetForm();
  },
  async onConfirm() {
    try {
      this.confirmLoading = true;

      // 验证表单
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }

      // 获取表单数据
      const values = await formApi.getValues();

      // 获取表格数据
      const list = basicTableApi.grid.getData();

      // 计算高度差
      if (list && list.length > 0) {
        list.forEach((item: any) => {
          item.heightDifference =
            item.manualTankOilHeightH2 - item.levelGaugeOilHeightH1;
        });
      }

      // 构建提交数据
      const params = {
        id: drawerApi.getData().taskId,
        ...values,
        tankWaterDetailList: list,
      };

      // 调用API提交数据
      await handleTankWater(params);

      // 触发刷新事件
      emit('reload');
      // 关闭抽屉
      drawerApi.close();
    } catch (error) {
      console.error(error);
    } finally {
      this.confirmLoading = false;
    }
  },
});

const tableData = ref<any[]>([]);

// 初始化表格配置
const gridOptions: VxeGridProps = {
  size: 'medium',
  toolbarConfig: {
    custom: false,
    refresh: false,
    zoom: false,
  },
  pagerConfig: {
    enabled: false,
  },
  proxyConfig: {
    ajax: {
      query: async () => {
        // 这里可以调用API获取表格数据
        return {
          items: tableData.value || [], // 初始数据
        };
      },
    },
  },
  columns: defautTableColumns,
  editConfig: {
    mode: 'cell',
    trigger: 'click',
  },
};

// 初始化表格组件
const [BasicTable, basicTableApi] = useVbenVxeGrid({
  gridOptions,
});

const addRow = () => {
  tableData.value.push({
    key: Date.now(),
    tankNumber: '',
    oilProduct: '',
    levelGaugeOilHeightH1: 0,
    levelGaugeWaterHeight: 0,
    manualTankOilHeightH2: 0,
    manualTankWaterHeight: 0,
    heightDifference: 0,
    tankTemperature: 0,
  });
};

const removeRow = (row: any) => {
  // 增加二次确认
  ElMessageBox.confirm('确定删除这行吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    tableData.value = tableData.value.filter((item) => item.key !== row.key);

    basicTableApi.reload();
  });
};
</script>

<template>
  <Drawer :title="taskParams.taskName">
    <Form>
      <!-- 测量信息表格插槽 -->
      <template #tankWaterDetailList>
        <BasicTable table-title="" class="w-full">
          <template #bottom>
            <ElButton class="mt-2 w-full" @click="addRow">
              + 新增行（无法读取到油站管号和油品时使用）
            </ElButton>
          </template>

          <template #action="{ row }">
            <ElButton type="danger" @click="removeRow(row)"> 删除 </ElButton>
          </template>
        </BasicTable>
      </template>
    </Form>
  </Drawer>
</template>

<style scoped lang="scss">
:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>
