<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import type { FormInstance } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import { VxeUI } from 'vxe-pc-ui';
import { PlusOutlined, ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons-vue';
import type { SatisfactionModel } from '@/model/satisfaction.model';
import { addSatisfactionMethod } from '@/request/api/satisfaction.api';
import { useRequest } from 'alova/client';
import { notification } from 'ant-design-vue';
const props = defineProps<{
  data?: any;
}>();

const emits = defineEmits<{
  submit: [data?: any];
  back: [];
}>();
const { loading: submitting, send: onSubmit } = useRequest(addSatisfactionMethod, { immediate: false });
const formRef = ref<FormInstance>();
const loading = ref<boolean>(false);

// 表单数据
const form = reactive<Partial<SatisfactionModel['satisfiesyContent']>>({
  name: '',
  startSentence: '',
  endSentence: '',
  suggestion: '',
  groups: [
    {
      name: '',
      items: [
        {
          name: '',
          score: '',
        },
      ],
    },
  ],
});

// 表单验证规则
const getRules = (): Record<string, Rule[]> => {
  const baseRules: Record<string, Rule[]> = {
    name: [
      {
        validator: (_rule: any, value: any) => {
          if (!value || (typeof value === 'string' && !value.trim())) {
            return Promise.reject('请输入问卷名称');
          }
          return Promise.resolve();
        },
        trigger: 'blur',
      },
    ],
    startSentence: [
      {
        validator: (_rule: any, value: any) => {
          if (!value || (typeof value === 'string' && !value.trim())) {
            return Promise.reject('请输入开头语');
          }
          return Promise.resolve();
        },
        trigger: 'blur',
      },
    ],
    endSentence: [
      {
        validator: (_rule: any, value: any) => {
          if (!value || (typeof value === 'string' && !value.trim())) {
            return Promise.reject('请输入结束语');
          }
          return Promise.resolve();
        },
        trigger: 'blur',
      },
    ],
  };

  return baseRules;
};

const rules = computed(() => getRules());

// 验证规则辅助函数
const groupNameValidator = (_rule: any, value: any) => {
  if (!value || (typeof value === 'string' && !value.trim())) {
    return Promise.reject('请输入问题分组名称');
  }
  return Promise.resolve();
};

const questionNameValidator = (_rule: any, value: any) => {
  if (!value || (typeof value === 'string' && !value.trim())) {
    return Promise.reject('请输入问题');
  }
  return Promise.resolve();
};

// 初始化数据
onMounted(() => {
  if (props.data) {
    Object.assign(form, props.data);
  }
});

// 添加问题分组
const addQuestionGroup = () => {
  const newGroup = {
    name: '',
    items: [
      {
        name: '',
        score: '',
      },
    ],
  };
  form.groups?.push(newGroup);
};

// 添加问题
const addQuestion = (groupIndex: number) => {
  const group = form.groups?.[groupIndex];
  if (group) {
    const newQuestion = {
      name: '',
      score: '',
    };
    group.items.push(newQuestion);
  }
};

// 保存
const handleSave = async () => {
  try {
    await formRef.value?.validate();
    loading.value = true;
    const submitData = {
      ...form,
    };
    onSubmit(submitData).then(() => {
      notification.success({
        message: '保存成功',
      });
      emits('submit', submitData);
    });
  } catch (error) {
    console.log(error, 'error===error');
  } finally {
    loading.value = false;
  }
};

// 返回
const handleBack = () => {
  emits('back');
  VxeUI.modal.close(`edit-questionnaire-modal`);
};
</script>

<template>
  <div class="questionnaire-form-container">
    <!-- 表单内容 -->
    <div class="form-content">
      <a-form ref="formRef" :model="form" :rules="rules" layout="horizontal" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        <!-- 问卷名称 -->
        <a-form-item name="name">
          <template #label>
            <span style="color: #ff4d4f">*</span> 问卷名称
          </template>
          <a-input v-model:value="form.name" placeholder="请输入" />
        </a-form-item>

        <!-- 开头语 -->
        <a-form-item name="startSentence">
          <template #label>
            <span style="color: #ff4d4f">*</span> 开头语
          </template>
          <a-textarea v-model:value="form.startSentence" placeholder="请输入开头语" :rows="4" />
        </a-form-item>

        <!-- 结束语 -->
        <a-form-item name="endSentence">
          <template #label>
            <span style="color: #ff4d4f">*</span> 结束语
          </template>
          <a-textarea v-model:value="form.endSentence" placeholder="请输入结束语" :rows="4" />
        </a-form-item>

        <!-- 问题分组列表 -->
        <div class="question-groups-section">
          <div v-for="(group, groupIndex) in form.groups" :key="`group-${groupIndex}`" class="question-group-item">
            <!-- 问题分组 -->
            <a-form-item
              :name="['groups', groupIndex, 'name']"
              :rules="[
                {
                  validator: groupNameValidator,
                  trigger: 'blur',
                },
              ]"
            >
              <template #label>
                <span style="color: #ff4d4f">*</span> 问题分组{{ groupIndex + 1 }}
              </template>
              <div class="group-input-wrapper">
                <a-input v-model:value="group.name" placeholder="请输入问题分组名称" />
                <button class="add-btn" @click="addQuestionGroup">
                  <PlusOutlined />
                </button>
              </div>
            </a-form-item>

            <!-- 问题列表 -->
            <div class="questions-list">
              <div v-for="(question, questionIndex) in group.items" :key="`question-${groupIndex}-${questionIndex}`" class="question-item">
                <a-form-item
                  :name="['groups', groupIndex, 'items', questionIndex, 'name']"
                  :rules="[
                    {
                      validator: questionNameValidator,
                      trigger: 'blur',
                    },
                  ]"
                >
                  <template #label>
                    <span style="color: #ff4d4f">*</span> 问题{{ questionIndex + 1 }}
                  </template>
                  <div class="question-input-wrapper">
                    <a-input v-model:value="question.name" placeholder="请输入" />
                    <button class="add-btn" @click="addQuestion(groupIndex)">
                      <PlusOutlined />
                    </button>
                  </div>
                </a-form-item>
              </div>
            </div>
          </div>
        </div>
      </a-form>
    </div>

    <!-- 底部按钮 -->
    <div class="footer-actions">
      <vxe-button type="default" @click="handleBack">
        <template #icon>
          <ArrowLeftOutlined />
        </template>
        取消
      </vxe-button>
      <vxe-button type="primary" status="warning" @click="handleSave" :loading="submitting">
        <template #icon>
          <SaveOutlined />
        </template>
        保存
      </vxe-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.questionnaire-form-container {
  padding: 24px;
  background: #fff;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.form-content {
  flex: 1;
  overflow: auto;
  margin-bottom: 24px;
}

// 问题分组部分
.question-groups-section {
  display: flex;
  flex-direction: column;
  gap: 0;
}

.question-group-item {
  margin-bottom: 0;
}

// 输入框包装器（包含输入框和加号按钮）
.group-input-wrapper,
.question-input-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;

  :deep(.ant-input) {
    flex: 1;
  }
}

// 加号按钮
.add-btn {
  width: 32px;
  height: 32px;
  border: 1px dashed #d9d9d9;
  background: #fff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: rgba(0, 0, 0, 0.65);
  transition: all 0.3s;
  flex-shrink: 0;
  padding: 0;

  &:hover {
    border-color: #ff7a45;
    color: #ff7a45;
  }

  &:focus {
    outline: none;
  }
}

// 问题列表
.questions-list {
  margin-left: 0;
  padding-left: 0;
}

.question-item {
  margin-bottom: 0;
}

// 底部按钮
.footer-actions {
  display: flex;
  justify-content: center;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;

  :deep(.ant-btn-primary) {
    background: #ff7a45;
    border-color: #ff7a45;

    &:hover {
      background: #ff9256;
      border-color: #ff9256;
    }
  }

  :deep(.ant-btn-default) {
    color: #1890ff;
    border-color: #1890ff;

    &:hover {
      color: #40a9ff;
      border-color: #40a9ff;
    }
  }
}

:deep(.ant-form-item-label > label.ant-form-item-required:not(.ant-form-item-required-mark-optional)) {
  &::before {
    display: inline-block;
    margin-right: 4px;
    color: #ff4d4f;
    font-size: 14px;
    font-family: SimSun, sans-serif;
    line-height: 1;
    content: '*';
  }
}

:deep(.ant-form-item) {
  margin-bottom: 24px;
}

:deep(.ant-input),
:deep(.ant-textarea),
:deep(.ant-select-selector),
:deep(.ant-picker) {
  border-color: #d9d9d9;
}
</style>
