<script lang="ts" setup>
// @ts-ignore
import { computed, onMounted } from 'vue';

import { DictEnum } from '@vben/constants';

import { ElCard, ElDescriptions, ElDescriptionsItem } from 'element-plus';
import { cloneDeep } from 'lodash-es';

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

// 定义组件的Props接口
interface SalesSurveyProps {
  taskDetail: any;
}

// 接收父组件传递的任务详情数据
const props = defineProps<SalesSurveyProps>();

// 计算属性，获取销售调研数据
const salesSurveyData = computed(() => {
  return props.taskDetail || [];
});

// 格式化日期时间

// 格式化数值，保留两位小数
const formatNumber = (value: number | string) => {
  if (value === undefined || value === null || value === '') return '-';
  const num = Number(value);
  if (isNaN(num)) return '-';
  return num.toFixed(2);
};

// 第一个表格列配置（油站基本信息）
const stationInfoColumns: any = [
  {
    field: 'competitorName',
    title: '油站',
    width: 120,
    fixed: 'left',
    formatter: ({ row }) => {
      return row.competitorName || row.stationName || '-';
    },
  },
  {
    field: 'stationNatureName',
    title: '油站性质',
    width: 100,
    formatter: ({ row }) => {
      return row.stationNatureName || '-';
    },
  },
  {
    field: 'isCompetitor',
    title: '竞争关系',
    width: 120,
    formatter: ({ row }) => {
      return row.isCompetitor === 1 ? '是' : '否';
    },
  },
  {
    field: 'distanceKm',
    title: '距离(KM)',
    width: 100,
  },
  {
    field: 'promotionActivities',
    title: '优惠活动',
    width: 200,
    editRender: { name: 'textarea' },
  },
  {
    field: 'valueAddedServices',
    title: '增值服务',
    width: 200,
    editRender: { name: 'textarea' },
  },
  {
    field: 'equipmentConfigChanges',
    title: '油站设备配置变化',
    width: 200,
    editRender: { name: 'textarea' },
  },
];

// 第二个表格列配置（油品价格和销量差）
const oilPriceColumns: any = [
  {
    field: 'oilType',
    title: '油品',
    width: 100,
    fixed: 'left',
  },
  {
    field: 'listingPrice',
    title: '挂牌价',
    width: 100,
    children: [],
  },
  {
    field: 'discountPrice',
    title: '优惠价',
    width: 100,
    children: [],
  },
  {
    field: 'salesDifference',
    title: '销量差',
    width: 120,
    children: [],
  },
];

// 初始化第一个表格配置（油站基本信息）
const stationInfoGridOptions: any = {
  size: 'medium',
  toolbarConfig: {
    custom: false,
    refresh: false,
    zoom: false,
  },
  pagerConfig: {
    enabled: false,
  },
  proxyConfig: {
    ajax: {
      query: async () => {
        return {
          items: props.taskDetail || [],
        };
      },
    },
  },
  columns: stationInfoColumns,
};

// 初始化第二个表格配置（油品价格和销量差）
const oilPriceGridOptions: any = {
  size: 'medium',
  toolbarConfig: {
    custom: false,
    refresh: false,
    zoom: false,
  },
  pagerConfig: {
    enabled: false,
  },
  proxyConfig: {
    ajax: {
      query: async () => {
        const oilProducts = await dictDataInfo(DictEnum.OIL_PRODUCT);
        const oilPriceList = oilProducts?.map((item: any) => {
          const info: any = {
            oilType: item.dictLabel,
            oilTypeCode: item.dictValue,
          };

          props.taskDetail.forEach((item: any, index: number) => {
            item.formOilPriceRecords.forEach((record: any) => {
              if (record.oilTypeCode === item.oilTypeCode) {
                info[`listingPrice_${item.id}_${index}`] =
                  record.listingPrice || '-';
                info[`discountPrice_${item.id}_${index}`] =
                  record.discountPrice || '-';
                info[`salesDifference_${item.id}_${index}`] =
                  record.salesDifference || '-';
              }
            });
          });
          return info;
        });
        console.log(oilPriceList, 'oilPriceList');
        return {
          items: oilPriceList || [], // 初始数据为空
        };
      },
    },
  },
  columns: oilPriceColumns,
};

// 使用BasicTable组件
const [StationInfoTable, stationInfoTableApi] = useVbenVxeGrid({
  gridOptions: stationInfoGridOptions,
});

const [OilPriceTable, oilPriceTableApi] = useVbenVxeGrid({
  gridOptions: oilPriceGridOptions,
});

const init = () => {
  const columns: any = [...(cloneDeep(oilPriceColumns) || [])];
  props.taskDetail.forEach((item: any, index: number) => {
    columns[1].children.push({
      field: `listingPrice_${item.id}_${index}`,
      title: `${item.competitorName || item.stationName}`,
      width: 100,
    });
    columns[2].children.push({
      field: `discountPrice_${item.id}_${index}`,
      title: `${item.competitorName || item.stationName}`,
      width: 100,
    });
    columns[3].children.push({
      field: `salesDifference_${item.id}_${index}`,
      title: `${item.competitorName || item.stationName}`,
      width: 100,
    });
  });

  oilPriceGridOptions.columns = columns;

  oilPriceTableApi.setGridOptions(oilPriceGridOptions);
};

onMounted(() => {
  init();
});
</script>

<template>
  <ElCard>
    <template #header>
      <div class="flex items-center gap-4">
        <div style="width: 4px; height: 12px; background-color: #215acd"></div>
        <span
          class="text-lg font-bold text-gray-800"
          style="font-size: 14px; font-weight: 600"
        >
          竟对销售调查详情
        </span>
      </div>
    </template>

    <div class="task-info">
      <!-- 基本信息 -->
      <div class="section-title">
        <div class="section-bar"></div>
        <span class="section-text">油站策略</span>
      </div>
      <ElDescriptions :column="4" class="mb-6">
        <ElDescriptionsItem label="调查时间:">
          {{ taskDetail[0]?.surveyDate || '-' }}
        </ElDescriptionsItem>
      </ElDescriptions>

      <!-- 油站基本信息表格 -->
      <!-- <div class="section-title">
        <div class="section-bar"></div>
        <span class="section-text">油站基本信息</span>
      </div> -->
      <div class="mb-6">
        <StationInfoTable table-title="" class="w-full" />
      </div>

      <!-- 油品价格和销量差表格 -->
      <div class="section-title">
        <div class="section-bar"></div>
        <span class="section-text">价格销售</span>
      </div>
      <div class="mb-6">
        <OilPriceTable table-title="" class="w-full" />
      </div>
    </div>
  </ElCard>
</template>

<style scoped lang="scss">
.task-info {
  .section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    margin: 20px 0 12px 0;

    .section-bar {
      width: 4px;
      height: 12px;
      background-color: #215acd;
    }

    .section-text {
      font-size: 14px;
      font-weight: 600;
      color: var(--text-color-primary);
    }
  }

  :deep(.el-descriptions) {
    margin-bottom: 0 !important;
  }

  :deep(.el-descriptions__label) {
    font-size: 14px;
    font-weight: 400;
    color: var(--text-color-secondary);
  }

  :deep(.el-descriptions__content) {
    font-size: 14px;
    font-weight: 500;
    color: var(--text-color-primary);
  }

  :deep(.el-descriptions__table) {
    background: transparent !important;
  }
}
</style>
