<template>
  <div class="apps-form">
    <el-dialog :title="(!state.ruleForm.id ? '批量' : '') + '修改营销配置'" width="880" v-model="visible"
      :close-on-click-modal="false" :destroy-on-close="true" draggable>
      <el-form ref="appDialogFormRef" :rules="dataRules" :model="state.ruleForm" class="demo-form-inline"
        v-loading="loading">
        <el-form-item v-if="state.ruleForm.appName" :label="t('marketingApps.name')" prop="appName">
          <el-input style="width: 200px;" v-model="state.ruleForm.appName" disabled />
        </el-form-item>
        <el-row :gutter="20" class="mb18">
          <el-col :span="12">
            <el-form-item :label="'营销开关'" prop="launch">
              <el-switch v-model="state.ruleForm.launch" style="--el-switch-on-color: rgb(48, 185, 113);" inline-prompt
                :active-value="true" :inactive-value="false" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="'域名限制'" prop="domainLimit">
              <el-switch v-model="state.ruleForm.domainLimit" style="--el-switch-on-color: rgb(48, 185, 113);"
                inline-prompt :active-value="true" :inactive-value="false" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="'触发频率'" prop="triggerNumFormat">
              <el-input style="width: 200px;" v-model="state.ruleForm.triggerNumFormat" :placeholder="'请输入触发频率'" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="'触发规则'" prop="triggerRule">
              <el-select style="width: 200px;" v-model="state.ruleForm.triggerRule" placeholder="">
                <el-option v-for="item in triggerRules" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="mt-7">
          <IpCollapse :data=state.ruleForm.ips @ips="updateIps" @delIps="updateDelIps"></IpCollapse>
        </div>
        <div class="mt-7">
          <DomainCollapse :data=state.ruleForm.domains @domains="updateDomains" @delDomains="updateDelDomains">
          </DomainCollapse>
        </div>
        <div class="title">{{ t('marketingApps.remark') }}</div>
        <el-form-item>
          <el-input :rows="4" v-model="state.ruleForm.remark" type="textarea" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">{{ t('common.cancelButtonText') }}</el-button>
          <el-button type="primary" @click="onSubmit" :disabled="loading">{{ t('common.confirmButtonText')
          }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
const DomainCollapse = defineAsyncComponent(() => import('./domainCollapse.vue'));
const IpCollapse = defineAsyncComponent(() => import('./ipCollapse.vue'));
import { useMessage } from '/@/hooks/message';
import { useI18n } from 'vue-i18n';
import { appUpdate } from '/@/api/marketing/apps';
import { AppData, DomainItem, IpItem } from '../types';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const { t } = useI18n();

// 定义变量内容
const visible = ref(false);
const loading = ref(false);
const appDialogFormRef = ref();
const domains = ref<DomainItem[]>();
const delDomains = ref<string[]>([]);
const childIps = ref<IpItem[]>();
const delIps = ref<string[]>([]);
// 批量操作
const rows = ref<AppData[]>([]);

const triggerRules = [
  {
    label: '仅一次',
    value: 1,
  },
  {
    label: '多次',
    value: 2,
  },
]

// 定义需要的数据
const state = reactive({
  ruleForm: {
    remark: "",
    domainLimit: true,
    launch: true,
    triggerNum: "",
    triggerNumFormat: "",
    triggerRule: 1,
  } as AppData,
});

watch(() => state.ruleForm, async (val) => {
  console.log('val', val);
})

const updateIps = (data: IpItem[]) => {
  childIps.value = data;
}
const updateDelIps = (data: string[]) => {
  delIps.value = data;
}

const updateDomains = (data: DomainItem[]) => {
  domains.value = data;
}
const updateDelDomains = (data: string[]) => {
  delDomains.value = data;
}

// 格式化数据展示
const formatNum = (value: string | number = 0) => {
  let num = Number(value);
  if(num > 0 && num < 1) {
    return (num * 100).toFixed(0) + '%';
  }else if (num >= 1 && num < 10000) {
    return num;
  }
  return ''
}

// 打开弹窗
const openDialog = async (type: string, row: any) => {
  visible.value = true;
  if(row instanceof Array){
    state.ruleForm = {
      remark: "",
      domainLimit: true,
      launch: true,
      triggerNum: "",
      triggerRule: 1,
    } as AppData;
    rows.value = row;
  }else if(row instanceof Object) {
    if(row.triggerNum) {
      row.triggerNumFormat = formatNum(row.triggerNum);
    }
    state.ruleForm = row;
    rows.value = [row]
  }
  domains.value = [];
  delDomains.value = [];
  console.log(row);
};

// 表单校验规则
const dataRules = reactive({
  triggerNumFormat: [
    { required: true, message: '触发频率不能为空', trigger: 'blur' },
    {
      pattern: /^(10000|[1-9]\d{0,3}|0)$|^(100%|[1-9]?\d%|0%)$/,
      message: '请输入 0-10000 的正整数或 0%-100% 的百分比',
      trigger: 'blur',
    },
  ],
});

/**
 * 处理数字字符串的方法
 * @param input - 输入值（字符串或空值）
 * @param defaultValue - 默认值（默认为0）
 * @returns 数值类型结果
 */
function processNumberString(
  input: string | null | undefined, 
  defaultValue: number = 0
): number {
  input = input?.toString() || '';
  // 处理空值情况
  if (input === null || input === undefined || input.trim() === '') {
    return defaultValue;
  }

  // 去除前后空格
  const trimmedInput = input.trim();

  // 检查是否为百分比格式
  if (trimmedInput.endsWith('%')) {
    const percentStr = trimmedInput.slice(0, -1);
    const percentValue = parseFloat(percentStr);
    
    // 验证是有效的0-100%数字
    if (!isNaN(percentValue) && percentValue >= 0 && percentValue <= 100) {
      return percentValue / 100;
    }
    return defaultValue; // 无效百分比返回默认值
  }
  
  // 处理普通数字字符串
  const numValue = parseFloat(trimmedInput);
  
  // 验证是0-10000的有效数字
  if (!isNaN(numValue) && numValue >= 0 && numValue <= 10000) {
    return numValue;
  }
  
  return defaultValue; // 无效数字返回默认值
}

// 保存数据
const onSubmit = async () => {

  const valid = await appDialogFormRef.value.validate();
  console.log('valid', valid);
  
  try {
    loading.value = true;
    const data:AppData[] = [];
    rows.value.forEach(async (item) => {
      data.push({
        ...item,
        domains: domains.value,
        delDomains: state.ruleForm.id ? delDomains.value : item.domains.map((item: DomainItem) => item.id),
        ips: childIps.value,
        delIps: state.ruleForm.id ? delIps.value : item.ips.map((item: IpItem) => item.id),
        remark: state.ruleForm.remark,
        domainLimit: state.ruleForm.domainLimit,
        launch: state.ruleForm.launch,
        triggerNum: `${processNumberString(state.ruleForm.triggerNumFormat)}`,
        triggerRule: state.ruleForm.triggerRule,
      })
    })
    console.log('rows.value', data);
    
    await appUpdate(data);
    useMessage().success(t('marketingApps.submitSuccess'));
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(t('marketingApps.submitFail'));
    console.error(err);
  } finally {
    loading.value = false;
  }
};

// 暴露变量 只有暴漏出来的变量 父组件才能使用
defineExpose({
  openDialog,
});
</script>
<style lang="scss">
.apps-form {
  .collapse-group {
    display: flex;
    justify-content: start;
    align-items: first baseline;
  }

  .tag-content {
    flex: 1;
  }

  .el-overlay {
    .el-overlay-dialog {
      .el-dialog {
        .el-dialog__body {
          padding: 0 !important;
        }
      }
    }
  }

  .title {
    line-height: 20px;
    font-family: Source Han Sans SC;
    font-size: 14px;
    color: rgba(18, 18, 18, 1);
    margin: 25px 0 12px;
  }
}
</style>