<!-- 通知服务风险控制组件 -->
<template>
  <el-card shadow="hover">
    <el-table :data="riskList" style="width: 100%">
      <el-table-column label="风控规则" align="center" prop="riskCode">
        <template #default="scope">
          <el-select
            v-model="scope.row.paramId"
            clearable
            filterable
            placeholder="风控规则"
            style="width: 260px"
            :disabled="props.disabled"
            @change="handleRiskCodeChange(scope.row)"
          >
            <el-option v-for="item in riskControlList" :key="item.paramId" :label="item.paramName" :value="item.paramId" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="风控规则参数" align="center" prop="riskParms">
        <template #default="scope">
          <el-input v-model="scope.row.riskParamsDisplay" placeholder="请选择风控规则并设置参数" readonly />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="删除" placement="top">
            <el-button
              v-hasPermi="['bfs:finItemDef:remove']"
              link
              type="primary"
              icon="Delete"
              :disabled="props.disabled"
              @click="handleDelete(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 10px">
      <el-button type="primary" :disabled="props.disabled" @click="addRow">+</el-button>
    </div>

    <!-- 参数设置弹窗 -->
    <el-dialog v-model="dialogVisible" title="设置风控规则参数" width="500px">
      <el-form :model="paramForm" label-width="120px">
        <template v-if="currentRiskType === 'timeRange'">
          <el-form-item label="起始时间">
            <el-time-picker v-model="paramForm.starttime" format="HH:mm" value-format="HH:mm" placeholder="选择时间" />
          </el-form-item>
          <el-form-item label="结束时间">
            <el-time-picker v-model="paramForm.endtime" format="HH:mm" value-format="HH:mm" placeholder="选择时间" />
          </el-form-item>
        </template>

        <template v-else-if="currentRiskType === 'holiday' || currentRiskType === 'legalHoliday'">
          <el-form-item label="发送方式">
            <el-select v-model="paramForm.sendtype" placeholder="请选择发送方式">
              <el-option label="发送" value="1" />
              <el-option label="不发送" value="2" />
            </el-select>
          </el-form-item>
        </template>

        <template v-else-if="currentRiskType === 'dateRange'">
          <el-form-item label="起始日期">
            <el-date-picker v-model="paramForm.startdate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="结束日期">
            <el-date-picker v-model="paramForm.enddate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="发送方式">
            <el-select v-model="paramForm.sendtype" placeholder="请选择发送方式">
              <el-option label="发送" value="1" />
              <el-option label="不发送" value="2" />
            </el-select>
          </el-form-item>
        </template>

        <template v-else-if="currentRiskType === 'sameTypeDailyLimit' || currentRiskType === 'dailyLimit'">
          <el-form-item label="最大发送次数">
            <el-input-number v-model="paramForm.number" :min="1" :max="100" />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmParams">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup name="MsgRiskControl" lang="ts">
import { getRiskControlList, queryTemplateRiskControl } from '@/api/msg/mestemp';
import { ref, getCurrentInstance } from 'vue';
import { useRoute } from 'vue-router';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const riskList = ref([]);
const riskControlList = ref([]);
const templateId = ref('');

// 弹窗相关状态
const dialogVisible = ref(false);
const currentRiskType = ref('');
const currentRow = ref(null);
const props = defineProps({
  disabled: {
    type: Boolean,
    default: false
  }
});
const paramForm = ref({
  starttime: '',
  endtime: '',
  sendtype: '',
  startdate: '',
  enddate: '',
  number: 1
});

// 风控规则类型映射
const riskTypeMap = {
  '每天{starttime}至{endtime}发送': 'timeRange',
  '节假日{sendtype}': 'holiday',
  '法定节假日{sendtype}': 'legalHoliday',
  '从{startdate}至{enddate}{sendtype}': 'dateRange',
  '同模板同一号码每天最多发送{number}次': 'sameTypeDailyLimit',
  '同一模板每天最多发送{number}次': 'dailyLimit'
};
// +++ 添加方法：检查风控规则是否有效 +++
const hasValidRules = () => {
  // 检查规则列表是否为空
  if (riskList.value.length === 0) {
    return false;
  }

  // 检查每条规则是否有效
  for (const rule of riskList.value) {
    // 规则必须选择了规则（paramId非空）并且设置了参数（riskParamsDisplay非空）
    if (!rule.paramId || !rule.riskParamsDisplay) {
      return false;
    }
  }
  return true;
};
const validateTimeRange = () => {
  if (currentRiskType.value === 'timeRange') {
    if (!paramForm.value.starttime || !paramForm.value.endtime) {
      proxy?.$modal.msgError('请填写完整的时间范围');
      return false;
    }
    if (paramForm.value.starttime >= paramForm.value.endtime) {
      proxy?.$modal.msgError('开始时间必须早于结束时间');
      return false;
    }
  }
  return true;
};

const validateDateRange = () => {
  if (currentRiskType.value === 'dateRange') {
    if (!paramForm.value.startdate || !paramForm.value.enddate || !paramForm.value.sendtype) {
      proxy?.$modal.msgError('请填写完整的日期范围和发送方式');
      return false;
    }
    if (paramForm.value.startdate > paramForm.value.enddate) {
      proxy?.$modal.msgError('开始日期必须早于结束日期');
      return false;
    }
  }
  return true;
};

const validateHoliday = () => {
  if (currentRiskType.value === 'holiday' || currentRiskType.value === 'legalHoliday') {
    if (!paramForm.value.sendtype) {
      proxy?.$modal.msgError('请选择发送方式');
      return false;
    }
  }
  return true;
};

const validateNumber = () => {
  if (currentRiskType.value === 'sameTypeDailyLimit' || currentRiskType.value === 'dailyLimit') {
    if (!paramForm.value.number) {
      proxy?.$modal.msgError('请填写发送次数');
      return false;
    }
  }
  return true;
};

const addRow = () => {
  // 检查最后一条规则是否已填写完整
  if (riskList.value.length > 0) {
    const lastRow = riskList.value[riskList.value.length - 1];
    if (!lastRow.paramId || !lastRow.riskParamsDisplay) {
      proxy?.$modal.msgWarning('请先完成当前行的风控规则设置');
      return;
    }
  }

  const newRow = {
    paramId: '',
    strategyId: '',
    riskParams: {},
    riskParamsDisplay: ''
  };
  riskList.value.push(newRow);
};

const handleRiskCodeChange = (row) => {
  if (!row.paramId) return;

  // 检查是否已存在相同的 paramId
  const isDuplicate = riskList.value.some((item) => item.paramId === row.paramId && item !== row);

  if (isDuplicate) {
    proxy?.$modal.msgError('该风控规则已存在，请勿重复添加');
    // 重置当前行的选择
    row.paramId = '';
    return;
  }

  // 获取选中的风控规则描述
  const selectedRisk = riskControlList.value.find((item) => item.paramId === row.paramId);
  if (!selectedRisk) return;

  row.strategyId = selectedRisk.strategyId;

  // 确定风控规则类型
  currentRiskType.value = riskTypeMap[selectedRisk.paramName] || '';
  currentRow.value = row;

  // 重置表单
  paramForm.value = {
    starttime: '',
    endtime: '',
    sendtype: '',
    startdate: '',
    enddate: '',
    number: 1
  };
  //  console.log(currentRiskType.value);

  // 显示弹窗
  dialogVisible.value = true;
};

const confirmParams = () => {
  if (!currentRow.value) return;

  // 验证输入
  let isValid = true;

  switch (currentRiskType.value) {
    case 'timeRange':
      isValid = validateTimeRange();
      break;
    case 'dateRange':
      isValid = validateDateRange();
      break;
    case 'holiday':
    case 'legalHoliday':
      isValid = validateHoliday();
      break;
    case 'sameTypeDailyLimit':
    case 'dailyLimit':
      isValid = validateNumber();
      break;
  }

  if (!isValid) return;

  // 再次确认没有重复规则
  const isDuplicate = riskList.value.some((item) => item.paramId === currentRow.value.paramId && item !== currentRow.value);

  if (isDuplicate) {
    proxy?.$modal.msgError('该风控规则已存在，请勿重复添加');
    currentRow.value.paramId = '';
    dialogVisible.value = false;
    return;
  }

  // 根据不同类型生成显示文本和参数对象
  let displayText = '';
  const params = {};

  switch (currentRiskType.value) {
    case 'timeRange':
      params.starttime = paramForm.value.starttime;
      params.endtime = paramForm.value.endtime;
      displayText = `每天${params.starttime}至${params.endtime}发送`;
      break;
    case 'holiday':
      params.sendtype = paramForm.value.sendtype;
      displayText = `节假日${params.sendtype === '1' ? '发送' : '不发送'}`;
      break;
    case 'legalHoliday':
      params.sendtype = paramForm.value.sendtype;
      displayText = `法定节假日${params.sendtype === '1' ? '发送' : '不发送'}`;
      break;
    case 'dateRange':
      params.startdate = paramForm.value.startdate;
      params.enddate = paramForm.value.enddate;
      params.sendtype = paramForm.value.sendtype;
      displayText = `从${params.startdate}至${params.enddate}${params.sendtype === '1' ? '发送' : '不发送'}`;
      break;
    case 'sameTypeDailyLimit':
      params.number = paramForm.value.number;
      displayText = `同类型同一号码每天最多发送${params.number}次`;
      break;
    case 'dailyLimit':
      params.number = paramForm.value.number;
      displayText = `每天最多发送${params.number}次`;
      break;
  }

  // 更新当前行数据
  currentRow.value.riskParams = params;
  currentRow.value.riskParamsDisplay = displayText;

  // 关闭弹窗
  dialogVisible.value = false;
};

const loadingPage = async (templateId) => {
  try {
    if (!templateId) {
      return;
    }

    // 加载已有风控规则
    const res = await queryTemplateRiskControl(templateId);

    // 清空现有数据
    riskList.value = [];

    // 按照 paramId 分组，因为一个规则可能有多个参数
    const groupedRules = res.data.reduce((acc, item) => {
      if (!acc[item.paramId]) {
        acc[item.paramId] = {
          paramId: item.paramId,
          strategyId: item.strategyId,
          riskParams: {},
          riskParamsDisplay: ''
        };
      }
      // 添加参数到对应规则
      acc[item.paramId].riskParams[item.riskParamName] = item.riskParamValue;
      return acc;
    }, {});

    // 转换分组后的数据并设置显示文本
    Object.values(groupedRules).forEach((rule) => {
      // 查找对应的规则模板
      const ruleTemplate = riskControlList.value.find((r) => r.paramId === rule.paramId);

      if (ruleTemplate) {
        // 根据规则类型生成显示文本
        switch (riskTypeMap[ruleTemplate.paramName]) {
          case 'timeRange':
            rule.riskParamsDisplay = `每天${rule.riskParams.starttime || ''}至${rule.riskParams.endtime || ''}发送`;
            break;
          case 'holiday':
          case 'legalHoliday':
            rule.riskParamsDisplay = `${ruleTemplate.paramName.includes('法定') ? '法定节假日' : '节假日'}${rule.riskParams.sendtype === '1' ? '发送' : '不发送'}`;
            break;
          case 'dateRange':
            rule.riskParamsDisplay = `从${rule.riskParams.startdate || ''}至${rule.riskParams.enddate || ''}${rule.riskParams.sendtype === '1' ? '发送' : '不发送'}`;
            break;
          case 'sameTypeDailyLimit':
          case 'dailyLimit':
            rule.riskParamsDisplay = ruleTemplate.paramName.replace('{number}', rule.riskParams.number || '');
            break;
          default:
            rule.riskParamsDisplay = ruleTemplate.paramName;
        }
      }

      riskList.value.push(rule);
    });

    //  console.log('加载的风控规则:', riskList.value);
  } catch (error) {

  }
};

const loadRiskControlList = async () => {
  try {
    // 加载风控规则列表
    const res = await getRiskControlList();
    riskControlList.value = res.data;

    // 如果已有templateId，则加载已有规则
    if (templateId.value) {
      await loadingPage(templateId.value);
    }
  } catch (error) {

  }
};

const handleDelete = (row) => {
  proxy?.$modal
    .confirm('确认删除该风控规则吗？')
    .then(() => {
      const index = riskList.value.findIndex((item) => item === row);
      if (index !== -1) {
        riskList.value.splice(index, 1);
        proxy?.$modal.msgSuccess('删除成功');
      }
    })
    .catch(() => {
      // 用户取消删除
    });
};

// 清空风控规则的方法
const resetRiskControls = () => {
  riskList.value = []; // 直接置空数组
};

// 暴露给父组件的数据和方法
defineExpose({
  riskList,
  getRiskData: () =>
    riskList.value.map((item) => ({
      paramId: item.paramId,
      strategyId: item.strategyId,
      riskParams: item.riskParams,
      riskParamsDisplay: item.riskParamsDisplay
    })),
  loadingPage,
  resetRiskControls,
  hasValidRules
});

onMounted(() => {
  const route = useRoute();
  templateId.value = route.params.templateId as string | undefined;

  // 只需要调用 loadRiskControlList，它会自动处理后续逻辑
  loadRiskControlList();
});
</script>
