<template>
  <div class="protocol-config-setting">
    <div class="setting-body">
      <!-- 一级 Tab：平台 -->
      <el-tabs v-model="activePlatform" class="platform-tabs" @tab-change="handlePlatformChange">
        <el-tab-pane label="好萌友" name="haomengyou" />
        <el-tab-pane label="履约守护" name="fulfiller" />
      </el-tabs>

      <!-- 二级 Tab：协议类型 -->
      <el-tabs v-model="activeProtocol" class="protocol-tabs" @tab-change="handleProtocolChange">
        <el-tab-pane v-for="item in currentProtocols" :key="item.id" :label="item.label" :name="String(item.id)" />
      </el-tabs>

      <!-- 配置表单区 -->
      <el-form ref="protocolFormRef" :model="form" :rules="rules" label-width="140px" label-position="right"
        class="premium-setting-form" :key="currentId">

        <el-form-item label="协议标题：" prop="title">
          <el-input v-model="form.title" placeholder="请输入协议标题" class="config-input" />
        </el-form-item>

        <el-form-item label="协议内容：" prop="content">
          <Editor v-model="form.content" :min-height="400" class="config-editor" />
          <div class="form-tip">协议内容将以 HTML 格式保存，支持图片和视频插入。</div>
        </el-form-item>

        <el-form-item class="action-item">
          <el-button type="primary" class="save-btn" :loading="buttonLoading" @click="submitForm">保存设置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup name="ProtocolConfig" lang="ts">
import { ref, reactive, computed, onMounted, getCurrentInstance, ComponentInternalInstance } from 'vue';
import { getAgreement, editAgreement } from '@/api/system/agreement';
import { ElForm } from 'element-plus';
import Editor from '@/components/Editor/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const buttonLoading = ref(false);
const protocolFormRef = ref<InstanceType<typeof ElForm>>();
const activePlatform = ref('haomengyou');
const currentId = ref(1);

interface ProtocolItem {
  id: number;
  label: string;
}

const haomengyouProtocols: ProtocolItem[] = [
  { id: 1, label: '用户协议' },
  { id: 2, label: '隐私政策' },
  // { id: 4, label: '托运协议' },
  // { id: 5, label: '宠物洗护服务规范' }
];

const fulfillerProtocols: ProtocolItem[] = [
  { id: 6, label: '用户协议' },
  { id: 7, label: '隐私政策' },
  { id: 3, label: '履约者说明' }
];

const currentProtocols = computed<ProtocolItem[]>(() => {
  return activePlatform.value === 'haomengyou' ? haomengyouProtocols : fulfillerProtocols;
});

const activeProtocol = ref('1');

const form = reactive({
  id: undefined,
  title: '',
  content: ''
});

const rules = {
  title: [{ required: true, message: "协议标题不能为空", trigger: "blur" }],
  content: [{ required: true, message: "协议内容不能为空", trigger: "blur" }],
};

const loadProtocolConfig = async (id: number) => {
  try {
    const res = await getAgreement(id);
    if (res.data) {
      Object.assign(form, res.data);
    }
  } catch (error) {
    console.error('获取协议信息失败', error);
  }
};

const handlePlatformChange = () => {
  const first = currentProtocols.value[0];
  if (first) {
    activeProtocol.value = String(first.id);
    currentId.value = first.id;
    loadProtocolConfig(first.id);
  }
};

const handleProtocolChange = (val: string | number) => {
  const id = Number(val);
  currentId.value = id;
  loadProtocolConfig(id);
};

const submitForm = () => {
  protocolFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        const contentBase64 = btoa(unescape(encodeURIComponent(form.content)));

        const submitData = {
          id: form.id || currentId.value,
          title: form.title,
          content: contentBase64
        };

        await editAgreement(submitData);
        proxy?.$modal.msgSuccess("保存成功");
        await loadProtocolConfig(currentId.value);
      } catch (error) {
        console.error('保存协议信息失败', error);
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

onMounted(() => {
  loadProtocolConfig(currentId.value);
});
</script>

<style scoped lang="scss">
.protocol-config-setting {
  padding: 8px 0;
}

.setting-body {
  padding-left: 20px;
}

.platform-tabs {
  margin-bottom: 4px;

  :deep(.el-tabs__header) {
    margin-bottom: 8px;
  }

  :deep(.el-tabs__item) {
    font-size: 15px;
    font-weight: 500;
  }
}

.protocol-tabs {
  margin-bottom: 24px;

  :deep(.el-tabs__header) {
    margin-bottom: 0;
  }
}

.premium-setting-form {
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #4e5969;
    padding-right: 24px;
  }

  .config-input {
    max-width: 520px;

    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 1px #e5e6eb inset;
      padding: 4px 12px;
      border-radius: 6px;

      &.is-focus {
        box-shadow: 0 0 0 1px #409eff inset;
      }
    }
  }

  .config-editor {
    width: 100%;
    max-width: 1000px;
  }

  .form-tip {
    font-size: 13px;
    color: #86909c;
    margin-top: 8px;
    line-height: 1.4;
  }

  .action-item {
    margin-top: 40px;
  }

  .save-btn {
    padding: 12px 32px;
    height: auto;
    font-size: 15px;
    font-weight: 500;
    border-radius: 6px;
    box-shadow: 0 4px 10px rgba(64, 158, 255, 0.2);
  }
}
</style>
