<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';
// @ts-ignore: 忽略
import { DictEnum } from '@vben/constants';

import { cloneDeep } from 'lodash-es';

// @ts-ignore: 忽略
import { useVbenVxeGrid } from '#/adapter/vxe-table';
// @ts-ignore: 忽略
import { dictDataInfo } from '#/api/system/dict/dict-data';
// @ts-ignore: 忽略
import { handleMarketingSurvey } from '#/api/task';

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

// 定义事件
const emit = defineEmits<{ reload: [] }>();

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

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

// 初始化第一个表格配置（油站基本信息）
const stationInfoGridOptions: VxeGridProps = {
  size: 'medium',
  toolbarConfig: {
    custom: false,
    refresh: false,
    zoom: false,
  },
  pagerConfig: {
    enabled: false,
  },
  proxyConfig: {
    ajax: {
      query: async () => {
        // 这里可以调用API获取表格数据
        return {
          items: taskParams.value.taskList || [], // 初始数据为空
        };
      },
    },
  },
  columns: stationInfoColumns,
  editConfig: {
    mode: 'cell',
    trigger: 'click',
  },
};

// 初始化第二个表格配置（油品价格和销量差）
const oilPriceGridOptions: VxeGridProps = {
  size: 'medium',
  toolbarConfig: {
    custom: false,
    refresh: false,
    zoom: false,
  },
  pagerConfig: {
    enabled: false,
  },
  proxyConfig: {
    ajax: {
      query: async () => {
        // 这里可以调用API获取表格数据
        const oilProducts = await dictDataInfo(DictEnum.OIL_PRODUCT);
        const oilPriceList = oilProducts?.map((item: any) => {
          return {
            oilType: item.dictLabel,
            oilTypeCode: item.dictValue,
          };
        });
        return {
          items: oilPriceList || [], // 初始数据为空
        };
      },
    },
  },
  columns: oilPriceColumns,
  editConfig: {
    mode: 'cell',
    trigger: 'click',
  },
};

// 初始化第一个表格组件
const [StationInfoTable, stationInfoTableApi] = useVbenVxeGrid({
  gridOptions: stationInfoGridOptions,
});

// 初始化第二个表格组件
const [OilPriceTable, oilPriceTableApi] = useVbenVxeGrid({
  gridOptions: oilPriceGridOptions,
});

const initPriceColumnsAndData = () => {
  // 深拷贝oilPriceColumns这个数组，避免直接修改原数组
  const columns: any = [...(cloneDeep(oilPriceColumns) || [])];
  taskParams.value.taskList.forEach((item: any, index: number) => {
    columns[1].children.push({
      field: `listingPrice_${item.id}_${index}`,
      title: `${item.competitorName || item.stationName}`,
      width: 100,
      editRender: { name: 'input' },
    });
    columns[2].children.push({
      field: `discountPrice_${item.id}_${index}`,
      title: `${item.competitorName || item.stationName}`,
      width: 100,
      editRender: { name: 'input' },
    });
    columns[3].children.push({
      field: `salesDifference_${item.id}_${index}`,
      title: `${item.competitorName || item.stationName}`,
      width: 100,
      editRender: { name: 'input' },
    });
  });

  // 调用油品
  // const oilProducts = getDictOptions(DictEnum.OIL_PRODUCT);
  // oilPrices.value = oilProducts?.map((item: any) => {
  //   return {
  //     oilType: item.dictLabel,
  //     oilTypeCode: item.dictValue,
  //   };
  // });

  oilPriceGridOptions.columns = columns;

  oilPriceTableApi.setGridOptions(oilPriceGridOptions);
  // oilPriceTableApi.grid.set();
  // oilPriceTableApi.query();
};

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

      // stationInfoTableApi.reload();

      initPriceColumnsAndData();
    } 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 stationInfoList = stationInfoTableApi.grid.getData();
      const oilPriceList = oilPriceTableApi.grid.getData();

      const params = taskParams.value.taskList;

      stationInfoList.forEach((item: any, index: number) => {
        params[index].promotionActivities = item.promotionActivities || '';
        params[index].valueAddedServices = item.valueAddedServices || '';
        params[index].equipmentConfigChanges =
          item.equipmentConfigChanges || '';
        params[index].surveyDate = values.surveyDate || '';

        params[index].oilPriceRecords = oilPriceList.map(
          (oilPriceItem: any) => {
            return {
              oilType: oilPriceItem.oilType,
              listingPrice: oilPriceItem[`listingPrice_${item.id}_${index}`],
              discountPrice: oilPriceItem[`discountPrice_${item.id}_${index}`],
              salesDifference:
                oilPriceItem[`salesDifference_${item.id}_${index}`],
            };
          },
        );
      });

      // 这里可以调用API提交数据
      await handleMarketingSurvey(params);

      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error(error);
    } finally {
      this.confirmLoading = false;
    }
  },
});
</script>

<template>
  <Drawer :title="taskParams.taskName">
    <Form>
      <!-- 油站基本信息表格插槽 -->
      <template #stationInfoTable>
        <StationInfoTable table-title="" class="w-full" />
      </template>
      <!-- 油品价格和销量差表格插槽 -->
      <template #oilPriceTable>
        <OilPriceTable table-title="" class="w-full" />
      </template>
    </Form>
  </Drawer>
</template>

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