<template>
  <div>
    <div class="flex justify-between items-center mb-4">
      <h3 class="text-md font-medium">测试数据</h3>
      <div>
        <el-button type="info" icon="MagicStick" :disabled="!paramsList.length" @click="handleAutoGenerate">自动生成测试数据</el-button>
        <el-button type="primary" icon="View" :loading="previewLoading" :disabled="!paramsList.length" @click="handleGeneratePreview"
          >生成预览</el-button
        >
        <el-button
          type="success"
          icon="Download"
          :loading="downloadLoading"
          :disabled="!paramsList.length || !previewUrl"
          @click="handleDownloadDocument"
          >下载文件</el-button
        >
      </div>
    </div>

    <!-- 测试数据编辑区域 -->
    <div class="test-data-container">
      <!-- 根级参数 -->
      <div v-if="rootParamsList.length" class="mb-6">
        <h4 class="text-sm font-medium mb-3 text-gray-700">
          <el-icon class="mr-1"><Document /></el-icon>
          根级参数
        </h4>
        <el-table :data="rootParamsList" border size="small" style="width: 100%">
          <el-table-column prop="paramName" label="参数名称" width="150" />
          <el-table-column prop="paramType" label="类型" width="80" align="center">
            <template #default="scope">
              <el-tag :type="getParamTypeTag(scope.row.paramType)" size="small">
                {{ getParamTypeText(scope.row.paramType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="paramDesc" label="描述" width="120" />
          <el-table-column label="测试数据" min-width="200">
            <template #default="scope">
              <el-input
                v-model="testData[scope.row.paramName]"
                :placeholder="`请输入${scope.row.paramDesc || scope.row.paramName}`"
                size="small"
                clearable
                @input="handleTestDataChange(scope.row.paramName, $event)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 嵌套参数（按容器分组） -->
      <div v-for="container in containerParamsList" :key="container.paramId" class="mb-6">
        <div class="container-header mb-3">
          <h4 class="text-sm font-medium text-gray-700">
            <el-icon class="mr-1 text-orange-500"><Folder /></el-icon>
            {{ container.paramName }}
            <el-tag type="warning" size="small" class="ml-2">{{ getParamTypeText(container.paramType) }}</el-tag>
          </h4>
          <p class="text-xs text-gray-500 mt-1">
            {{ container.paramDesc || '列表容器，可包含多条记录' }}
          </p>
        </div>

        <!-- 容器的子参数列表 -->
        <div v-if="getContainerChildren(container.paramId).length" class="container-content">
          <!-- 列表项数量控制 -->
          <div class="mb-3 flex items-center">
            <span class="text-sm text-gray-600 mr-2">列表项数量:</span>
            <el-input-number
              v-model="listItemCounts[container.paramName]"
              :min="0"
              :max="10"
              size="small"
              @change="updateListItems(container.paramName)"
            />
            <el-button type="text" size="small" class="ml-2" @click="generateContainerData(container)"> 生成示例数据 </el-button>
          </div>

          <!-- 列表项编辑 -->
          <div class="list-items">
            <div
              v-for="(item, index) in getContainerTestData(container.paramName)"
              :key="index"
              class="list-item mb-4 p-3 border border-gray-200 rounded"
            >
              <div class="flex justify-between items-center mb-2">
                <span class="text-sm font-medium text-gray-700">项目 {{ index + 1 }}</span>
                <el-button type="danger" size="small" text @click="removeListItem(container.paramName, index)"> 删除 </el-button>
              </div>

              <el-table :data="getContainerChildren(container.paramId)" size="small" border style="width: 100%">
                <el-table-column prop="paramName" label="字段名" width="120">
                  <template #default="scope">
                    {{ getChildParamName(scope.row.paramName) }}
                  </template>
                </el-table-column>
                <el-table-column prop="paramType" label="类型" width="80" align="center">
                  <template #default="scope">
                    <el-tag :type="getParamTypeTag(scope.row.paramType)" size="small">
                      {{ getParamTypeText(scope.row.paramType) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="值" min-width="200">
                  <template #default="scope">
                    <el-input
                      v-model="item[getChildParamName(scope.row.paramName)]"
                      :placeholder="`请输入${scope.row.paramDesc || getChildParamName(scope.row.paramName)}`"
                      size="small"
                      @input="updateContainerItemData(container.paramName, index, getChildParamName(scope.row.paramName), $event)"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <!-- 添加新项按钮 -->
            <el-button type="dashed" size="small" style="width: 100%" @click="addListItem(container.paramName)"> + 添加新项 </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 数据预览JSON -->
    <div class="mt-6">
      <el-card>
        <template #header>
          <div class="flex justify-between items-center">
            <span class="text-sm font-medium">生成的测试数据预览</span>
            <el-button type="text" size="small" @click="copyJsonData">复制JSON</el-button>
          </div>
        </template>
        <pre class="json-preview">{{ formattedTestData }}</pre>
      </el-card>
    </div>

    <el-empty v-if="!paramsList.length" description="请先在参数管理标签页解析模板参数" />

    <!-- 预览区域 -->
    <div class="preview-container mt-6">
      <div v-if="previewUrl" class="preview-content">
        <iframe :src="previewUrl" class="preview-iframe" frameborder="0" @load="handlePreviewLoad"></iframe>
      </div>
      <div v-else class="preview-placeholder">
        <div class="text-center">
          <el-icon :size="64" class="mb-2 text-gray-400"><View /></el-icon>
          <p class="text-gray-500">点击"生成预览"按钮查看模板预览</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, PropType, reactive, ref, watch } from 'vue';
import { View, InfoFilled, Document, Folder } from '@element-plus/icons-vue';
import { ElMessage, ElLoading } from 'element-plus';
import { TemplateParamVO } from '@/api/system/template/types';
import { secureRandom } from '@/utils/ruoyi';

type TagType = 'primary' | 'success' | 'info' | 'warning' | 'danger';

const props = defineProps({
  paramsList: {
    type: Array as PropType<TemplateParamVO[]>,
    default: () => []
  },
  templateId: {
    type: [Number, String],
    default: undefined
  },
  templateName: {
    type: String,
    default: ''
  },
  testData: {
    type: Object as PropType<Record<string, any>>,
    default: () => ({})
  },
  previewUrl: {
    type: String,
    default: ''
  },
  previewLoading: {
    type: Boolean,
    default: false
  },
  downloadLoading: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['generate-preview', 'download-document', 'update-test-data', 'auto-generate']);

// 列表项数量控制
const listItemCounts = reactive<Record<string, number>>({});

// 分类参数
const rootParamsList = computed(() => {
  return props.paramsList.filter((p) => !p.parentId && !isContainerType(p.paramType));
});

const containerParamsList = computed(() => {
  return props.paramsList.filter((p) => !p.parentId && isContainerType(p.paramType));
});

// 判断是否为容器类型
const isContainerType = (paramType: string): boolean => {
  const containerTypes = ['list', 'conditionalList', 'nestedList', 'table'];
  return containerTypes.includes(paramType);
};

// 获取容器的子参数
const getContainerChildren = (containerId: number | string) => {
  return props.paramsList.filter((p) => p.parentId === containerId);
};

// 获取子参数名称（去除前缀）
const getChildParamName = (fullParamName: string): string => {
  if (fullParamName.includes('.')) {
    const parts = fullParamName.split('.');
    return parts[parts.length - 1];
  }
  return fullParamName;
};

// 获取容器的测试数据
const getContainerTestData = (containerName: string): any[] => {
  const data = props.testData[containerName];
  if (Array.isArray(data)) {
    return data;
  }
  // 如果不是数组，初始化为空数组
  emit('update-test-data', containerName, []);
  return [];
};

// 更新列表项数量
const updateListItems = (containerName: string) => {
  const targetCount = listItemCounts[containerName] || 0;
  const currentData = getContainerTestData(containerName);

  if (targetCount > currentData.length) {
    // 增加项目
    const container = containerParamsList.value.find((c) => c.paramName === containerName);
    if (container) {
      const children = getContainerChildren(container.paramId);
      const newItems = [];

      for (let i = currentData.length; i < targetCount; i++) {
        const newItem: any = {};
        children.forEach((child) => {
          const childName = getChildParamName(child.paramName);
          newItem[childName] = generateSampleValue(child);
        });
        newItems.push(newItem);
      }

      emit('update-test-data', containerName, [...currentData, ...newItems]);
    }
  } else if (targetCount < currentData.length) {
    // 减少项目
    emit('update-test-data', containerName, currentData.slice(0, targetCount));
  }
};

// 添加列表项
const addListItem = (containerName: string) => {
  const container = containerParamsList.value.find((c) => c.paramName === containerName);
  if (container) {
    const children = getContainerChildren(container.paramId);
    const newItem: any = {};

    children.forEach((child) => {
      const childName = getChildParamName(child.paramName);
      newItem[childName] = generateSampleValue(child);
    });

    const currentData = getContainerTestData(containerName);
    emit('update-test-data', containerName, [...currentData, newItem]);
    listItemCounts[containerName] = (listItemCounts[containerName] || 0) + 1;
  }
};

// 删除列表项
const removeListItem = (containerName: string, index: number) => {
  const currentData = getContainerTestData(containerName);
  currentData.splice(index, 1);
  emit('update-test-data', containerName, [...currentData]);
  listItemCounts[containerName] = Math.max(0, (listItemCounts[containerName] || 0) - 1);
};

// 更新容器项数据
const updateContainerItemData = (containerName: string, itemIndex: number, fieldName: string, value: any) => {
  const currentData = getContainerTestData(containerName);
  if (currentData[itemIndex]) {
    currentData[itemIndex][fieldName] = value;
    emit('update-test-data', containerName, [...currentData]);
  }
};

// 增强的示例值生成
const generateSampleValue = (param: TemplateParamVO): string => {
  // 优先使用默认值
  if (param.defaultValue && param.defaultValue.trim() !== '') {
    return param.defaultValue;
  }

  const paramName = getChildParamName(param.paramName).toLowerCase();

  // 公司和机构相关
  if (paramName.includes('managecom') && !paramName.includes('name')) {
    return '8600';
  }
  if (paramName.includes('managecomname') || paramName.includes('comname')) {
    return '示例分公司';
  }

  // 人员信息
  if (paramName.includes('name') || paramName.includes('姓名')) {
    const names = ['张三', '李四', '王五', '赵六'];
    return names[Math.floor(secureRandom() * names.length)];
  }
  if (paramName.includes('agentcode') || paramName.includes('工号')) {
    return `A${(100001 + Math.floor(secureRandom() * 999)).toString()}`;
  }

  // 日期时间
  if (paramName.includes('date') || paramName.includes('time') || paramName.includes('日期')) {
    return new Date().toLocaleDateString('zh-CN');
  }
  if (paramName.includes('indexcalno') || paramName.includes('期号')) {
    const now = new Date();
    return `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}`;
  }

  // 金额相关 - 更智能的金额生成
  if (isAmountField(paramName)) {
    return generateAmountByField(paramName);
  }

  // 税费相关
  if (isTaxField(paramName)) {
    return (secureRandom() * 500 + 50).toFixed(2);
  }

  // 其他字段
  return `示例${getChildParamName(param.paramName)}`;
};

// 判断是否为金额字段
const isAmountField = (name: string): boolean => {
  const amountKeywords = ['money', 'total', 'sum', 'payable', 'performance', 'basic', '金额', '佣金', '绩效', '津贴', '奖金', '合计'];

  // 特殊处理：f开头的字段通常是金额
  if (name.startsWith('f') && name.length <= 3) {
    return true;
  }

  return amountKeywords.some((keyword) => name.includes(keyword));
};

// 判断是否为税费字段
const isTaxField = (name: string): boolean => {
  return name.startsWith('k') || name.includes('tax') || name.includes('税');
};

// 根据字段生成合理的金额
const generateAmountByField = (name: string): string => {
  let baseAmount = 1000;

  // 根据字段名称调整基础金额
  if (name.includes('total') || name.includes('sum') || name.includes('合计')) {
    baseAmount = 5000;
  } else if (name.includes('basic') || name.includes('基础')) {
    baseAmount = 2000;
  } else if (name.includes('performance') || name.includes('绩效')) {
    baseAmount = 1500;
  } else if (name.includes('f01') || name.includes('职级')) {
    baseAmount = 3000;
  } else if (name.includes('f02') || name.includes('服务')) {
    baseAmount = 1000;
  } else {
    baseAmount = 500;
  }

  // 添加随机变化
  const randomAmount = baseAmount + (secureRandom() - 0.5) * baseAmount * 0.4;
  return Math.max(0, randomAmount).toFixed(2);
};

// 生成容器数据
const generateContainerData = (container: any) => {
  const children = getContainerChildren(container.paramId);
  const itemCount = listItemCounts[container.paramName] || 2;
  const newData = [];

  for (let i = 0; i < itemCount; i++) {
    const item: any = {};
    children.forEach((child) => {
      const childName = getChildParamName(child.paramName);
      item[childName] = generateSampleValue(child);
    });
    newData.push(item);
  }

  emit('update-test-data', container.paramName, newData);
};

// 自动生成所有测试数据
const handleAutoGenerate = () => {
  if (!props.paramsList.length) {
    ElMessage.warning('请先解析模板参数');
    return;
  }

  const loading = ElLoading.service({
    lock: true,
    text: '正在生成测试数据...',
    background: 'rgba(0, 0, 0, 0.1)'
  });

  try {
    const generatedData: Record<string, any> = {};

    // 检查是否为佣金报表模板（包含list1和佣金相关字段）
    const isWageReport =
      containerParamsList.value.some((c) => c.paramName === 'list1') &&
      rootParamsList.value.some((p) => p.paramName.includes('sf') || p.paramName.includes('sk'));

    if (isWageReport) {
      // 使用专门的佣金报表数据生成
      const wageData = generateWageReportData();
      Object.assign(generatedData, wageData);
    } else {
      // 使用通用数据生成
      // 生成根级参数数据
      rootParamsList.value.forEach((param) => {
        generatedData[param.paramName] = generateSampleValue(param);
      });

      // 生成容器参数数据
      containerParamsList.value.forEach((container) => {
        const children = getContainerChildren(container.paramId);
        const itemCount = 2; // 默认生成2条数据
        const listData = [];

        for (let i = 0; i < itemCount; i++) {
          const item: any = {};
          children.forEach((child) => {
            const childName = getChildParamName(child.paramName);
            item[childName] = generateSampleValue(child);
          });
          listData.push(item);
        }

        generatedData[container.paramName] = listData;
        listItemCounts[container.paramName] = itemCount;
      });
    }

    // 更新列表项计数
    containerParamsList.value.forEach((container) => {
      const data = generatedData[container.paramName];
      if (Array.isArray(data)) {
        listItemCounts[container.paramName] = data.length;
      }
    });

    emit('auto-generate', generatedData);
    ElMessage.success('测试数据已自动生成');
  } catch (error) {
    ElMessage.error('生成测试数据失败，请重试');
  } finally {
    loading.close();
  }
};

// 专门的佣金报表数据生成器
const generateWageReportData = (): Record<string, any> => {
  const testData: Record<string, any> = {};

  // 根级参数的默认值（汇总数据）
  const rootDefaults: Record<string, string> = {
    'managecom': '8600',
    'sf01': '15000.00', // 基本佣金合计
    'sf02': '3000.00', // 职龄佣金合计
    'sf08': '1000.00', // 服务津贴合计
    'sf11': '500.00', // 基础佣金类加扣款合计
    'sf12': '200.00', // 活动管理扣款合计
    'sf13': '300.00', // 品质管理加扣款合计
    'sbasictotal': '19200.00', // 基础佣金合计
    'sf03': '8000.00', // 业务绩效合计
    'sf04': '2000.00', // 管理绩效合计
    'sadditional': '1500.00', // 附加绩效合计
    'sf14': '800.00', // 精准营销首期绩效合计
    'sf15': '600.00', // 精准营销续期绩效合计
    'sf10': '400.00', // 竞赛方案奖励合计
    'sf16': '1200.00', // 健康养老首期业务绩效合计
    'sf17': '900.00', // 健康养老续期业务绩效合计
    'sf20': '300.00', // 绩效奖金类加扣款合计
    'stotalperformance': '15100.00', // 绩效奖金合计
    'ssumpayable': '34300.00', // 应发合计
    'sf18': '30000.00', // 合并计税项合计
    'ssummoney': '30000.00', // 计税金额合计
    'sk08': '4500.00', // 个人所得税合计
    'sk01': '1800.00', // 增值税合计
    'sk02': '180.00', // 城建税合计
    'sk03': '108.00', // 教育附加税合计
    'sk04': '54.00', // 地方教育附加税合计
    'sothertax': '100.00', // 其他税费合计
    'sf19': '6742.00', // 税后扣款合计
    'scurrmoney': '27558.00' // 实发佣金合计
  };

  // 设置根级参数
  rootParamsList.value.forEach((param) => {
    testData[param.paramName] = rootDefaults[param.paramName] || generateSampleValue(param);
  });

  // 生成list1员工数据
  const employees = [
    { name: '张三', agentcode: 'A100001' },
    { name: '李四', agentcode: 'A100002' }
  ];

  testData.list1 = employees.map((emp, index) => ({
    managecomname: '示例分公司',
    indexcalno: '202411',
    name: emp.name,
    agentcode: emp.agentcode,
    f01: (3000 + index * 500).toFixed(2), // 职级佣金
    f02: (1500 + index * 200).toFixed(2), // 长期服务佣金
    f08: (500 + index * 100).toFixed(2), // 服务津贴
    f11: (250 + index * 50).toFixed(2), // 基础佣金类加扣款
    f12: (100 + index * 20).toFixed(2), // 活动管理扣款
    f13: (150 + index * 30).toFixed(2), // 品质管理加扣款
    basictotal: (5600 + index * 800).toFixed(2), // 基础佣金合计
    f03: (4000 + index * 600).toFixed(2), // 业务绩效
    f04: (1000 + index * 200).toFixed(2), // 管理绩效
    additional: (750 + index * 150).toFixed(2), // 附加绩效
    f14: (400 + index * 80).toFixed(2), // 精准营销首期绩效
    f15: (300 + index * 60).toFixed(2), // 精准营销续期绩效
    f10: (200 + index * 40).toFixed(2), // 竞赛方案奖励
    f16: (600 + index * 120).toFixed(2), // 健康养老首期业务绩效
    f17: (450 + index * 90).toFixed(2), // 健康养老续期业务绩效
    f20: (150 + index * 30).toFixed(2), // 绩效佣金类加扣款
    totalperformance: (7550 + index * 1180).toFixed(2), // 绩效奖金合计
    sumpayable: (13150 + index * 1980).toFixed(2), // 应发合计
    f18: (12000 + index * 1500).toFixed(2), // 合并计税项
    summoney: (12000 + index * 1500).toFixed(2), // 计税金额合计
    k08: (1800 + index * 300).toFixed(2), // 个人所得税
    k01: (720 + index * 120).toFixed(2), // 增值税
    k02: (72 + index * 12).toFixed(2), // 城建税
    k03: (43 + index * 7).toFixed(2), // 教育附加税
    k04: (22 + index * 4).toFixed(2), // 地方教育附加税
    othertax: (40 + index * 10).toFixed(2), // 其他税费
    f19: (2697 + index * 453).toFixed(2), // 税后扣款
    currmoney: (10453 + index * 1527).toFixed(2) // 实发佣金
  }));

  return testData;
};

// 格式化的测试数据
const formattedTestData = computed(() => {
  return JSON.stringify(props.testData, null, 2);
});

// 复制JSON数据
const copyJsonData = async () => {
  try {
    await navigator.clipboard.writeText(formattedTestData.value);
    ElMessage.success('JSON数据已复制到剪贴板');
  } catch (error) {
    ElMessage.error('复制失败');
  }
};

// 参数类型相关方法
const getParamTypeTag = (paramType: string): TagType => {
  const typeMap: Record<string, TagType> = {
    'text': 'success',
    'list': 'warning',
    'conditionalList': 'warning',
    'nestedList': 'warning',
    'table': 'danger',
    'image': 'info'
  };
  return typeMap[paramType] || 'info';
};

const getParamTypeText = (paramType: string): string => {
  const nameMap: Record<string, string> = {
    'text': '文本',
    'list': '列表',
    'conditionalList': '条件列表',
    'nestedList': '嵌套列表',
    'table': '表格',
    'image': '图片'
  };
  return nameMap[paramType] || paramType;
};

// 生成预览
const handleGeneratePreview = () => {
  // 验证必填参数
  const missingParams = props.paramsList.filter((p) => p.isRequired === '1' && !hasValidValue(p.paramName)).map((p) => p.paramDesc || p.paramName);

  if (missingParams.length > 0) {
    ElMessage.warning(`请填写必填参数：${missingParams.join('、')}`);
    return;
  }

  emit('generate-preview');
};

// 检查参数是否有有效值
const hasValidValue = (paramName: string): boolean => {
  const value = props.testData[paramName];
  if (Array.isArray(value)) {
    return value.length > 0;
  }
  return value !== undefined && value !== null && value !== '';
};

// 下载文档
const handleDownloadDocument = () => {
  if (!props.previewUrl) {
    ElMessage.warning('请先生成预览');
    return;
  }
  emit('download-document');
};

// 测试数据变更
const handleTestDataChange = (paramName: string, value: any) => {
  emit('update-test-data', paramName, value);
};

// 预览加载完成
const handlePreviewLoad = () => {
};

// 监听参数列表变化，初始化列表项数量
watch(
  () => props.paramsList,
  (newParams) => {
    if (newParams && newParams.length > 0) {
      containerParamsList.value.forEach((container) => {
        if (!(container.paramName in listItemCounts)) {
          listItemCounts[container.paramName] = 1; // 默认1项
        }
      });
    }
  },
  { immediate: true }
);
</script>

<style scoped>
/* 测试数据容器样式 */
.test-data-container {
  max-height: 600px;
  overflow-y: auto;
  padding: 8px;
}

/* 容器头部样式 */
.container-header {
  background-color: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

/* 容器内容样式 */
.container-content {
  margin-left: 16px;
  padding-left: 16px;
  border-left: 2px solid #e9ecef;
}

/* 列表项样式 */
.list-item {
  background-color: #fafbfc;
  transition: all 0.2s ease;
}

.list-item:hover {
  background-color: #f1f3f4;
}

/* JSON预览样式 */
.json-preview {
  background-color: #f8f9fa;
  padding: 12px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 1.4;
  max-height: 300px;
  overflow-y: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* 预览容器样式 */
.preview-container {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
  height: 400px;
  position: relative;
  background-color: #f5f7fa;
}

.preview-content {
  height: 100%;
  width: 100%;
}

.preview-iframe {
  width: 100%;
  height: 100%;
  background-color: white;
}

.preview-placeholder {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
}

/* 表格样式优化 */
:deep(.el-table--small .el-table__cell) {
  padding: 6px 8px;
}

:deep(.el-input--small .el-input__inner) {
  height: 28px;
  line-height: 28px;
}

/* 标签样式优化 */
:deep(.el-tag--small) {
  height: 20px;
  padding: 0 5px;
  font-size: 12px;
}

/* 输入数字控件样式 */
:deep(.el-input-number--small) {
  width: 120px;
}

/* 虚线按钮样式 */
:deep(.el-button[type='dashed']) {
  border-style: dashed;
  color: #666;
}
</style>
