<!-- アンケート照会 -->
<template>
  <div class="app-container">
    <p>アンケートフォーム作成</p>
    <div class="form-container">
      <el-form ref="queryRef"
               :model="queryParams"
               label-width="140px"
               label-position="top">
        <el-form-item label="タイトル"  style="margin-left: 30px;margin-top: -35px;">
          <el-input v-model="queryParams.title"  class="table-input" :maxlength="100"  disabled></el-input>
        </el-form-item>
        <el-form-item label="説明文" style="margin-left: 30px;margin-top: -15px;" >
          <el-input
              v-model="queryParams.description"
              class="table-input"
              :maxlength="255"
              type="textarea"
              :rows="2"
              disabled
          ></el-input>
        </el-form-item>
        <div style=" padding-left: 29px;margin-top: -15px;">公開範囲</div>
        <el-form-item label="FC" prop="brandCode" style="margin-left: 60px; display: flex; align-items: center; margin-top: 10px;">
          <div class="el-form-item__label" style="flex-shrink: 0; margin-right: 20px;"></div>
          <el-checkbox-group v-model="queryParams.brandCode">
            <el-checkbox disabled v-for="dict in yamada_fc_brand" :key="dict.value" :label="dict.value" style="margin-right: 60px;">{{ dict.label }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="業種" prop="businessTypeCode" class="el-form-item__businessTypeCode">
          <div class="el-form-item__label" style="flex-shrink: 0; margin-right: 14px;"></div>
          <el-checkbox-group v-model="queryParams.businessTypeCode">
            <el-checkbox disabled v-for="dict in yamada_business_type" :key="dict.value" :label="dict.value" style="margin-right: 32px;">{{ dict.label }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <div class="container">
          <div class="area-header-row">
            <h1 class="area-title">エリア</h1>
            <RegionTree class="region-tree-container"  :treeData="regionTree" @check-change="handleCheckChange" disabled />
          </div>
        </div>
        <!-- 公開期間 -->
        <div class="form-section">公開期間</div>
        <!-- 垂直排列的单选框组 -->
        <el-form-item class="radio-group-vertical">
          <div class="radio-container"> <!-- 新增容器用于控制布局 -->
            <el-radio
                label="immediate"
                v-model="queryParams.releaseType"
                class="vertical-radio"
                disabled
            >即時公開</el-radio>
            <el-radio
                label="scheduled"
                v-model="queryParams.releaseType"
                class="scheduled-radio"
                disabled
            >期間指定</el-radio>
            <div class="scheduled-row">
              <!-- 期間指定时显示的日期选择（同行） -->
              <div class="date-group"  >
                <!-- 日期选择器代码保持不变 -->
                <el-select v-model="queryParams.startYear" placeholder="" class="date-select"   disabled @change="formatDate">
                  <el-option v-for="year in years" :key="year" :label="year" :value="year"></el-option>
                </el-select>
                <span class="date-label">年</span>
                <el-select
                    v-model="queryParams.startMonth"
                    placeholder=""
                    class="date-select-small"
                    @change="formatDate"
                    disabled
                >
                  <el-option
                      v-for="month in months"
                      :key="month"
                      :label="month"
                      :value="month"
                  ></el-option>
                </el-select>
                <span class="date-label">月</span>
                <el-select
                    v-model="queryParams.startDay"
                    placeholder=""
                    class="date-select-small"
                    @change="formatDate"
                    disabled
                >
                  <el-option
                      v-for="day in days"
                      :key="day"
                      :label="day"
                      :value="day"
                  ></el-option>
                </el-select>
                <span class="date-label">日</span>
                <span class="date-label">～</span>
                <el-select
                    v-model="queryParams.endYear"
                    placeholder=""
                    class="date-select"
                    @change="formatDate"
                    disabled
                >
                  <el-option
                      v-for="year in years"
                      :key="year"
                      :label="year"
                      :value="year"
                  ></el-option>
                </el-select>
                <span class="date-label">年</span>
                <el-select
                    v-model="queryParams.endMonth"
                    placeholder=""
                    class="date-select-small"
                    @change="formatDate"
                    disabled
                >
                  <el-option
                      v-for="month in months"
                      :key="month"
                      :label="month"
                      :value="month"
                  ></el-option>
                </el-select>
                <span class="date-label">月</span>
                <el-select
                    v-model="queryParams.endDay"
                    placeholder=""
                    class="date-select-small"
                    @change="formatDate"
                    disabled
                >
                  <el-option
                      v-for="day in days"
                      :key="day"
                      :label="day"
                      :value="day"
                  ></el-option>
                </el-select>
                <span class="date-label">日</span>
              </div>
            </div>
          </div>
        </el-form-item>
        <div style="margin-left: 25px; margin-top: 15px;">自由作成フォーム</div>

        <div v-for="(question, index) in questions" :key="question.sortOrder" class="question-block">
          <el-form-item style="margin-left: 50px; margin-top: 3px;">
            <el-button disabled class="append-button" @click="addQuestionAbove(index)">この上に設問を追加</el-button>
          </el-form-item>
          <el-form-item style="margin-left: 55px;">
            <template #label>
              <div style="display: flex; align-items: center;margin-top: -20px">
                <span style="color: #606266; font-weight: bold">設問文</span>
                <span style="color: #666; margin-left: 8px;">: {{ question.sortOrder }}</span>
              </div>
            </template>
            <el-input disabled  v-model="question.questionText" class="small-input" type="textarea" :rows="2" :maxlength="255"></el-input>
          </el-form-item>
          <el-form-item label="回答型" style="margin-left: 55px;margin-top: -15px">
            <el-radio-group disabled v-model="question.questionTypeStr" class="custom-radio-group" @change="handleQuestionTypeChange(question, $event)">
              <el-radio label="INPUT_BOX_50">入力ボックス（50文字）</el-radio>
              <el-radio label="INPUT_BOX_100">入力ボックス（100文字）</el-radio>
              <el-radio label="CHECK_BOX">チェックボックス</el-radio>
              <el-radio label="RADIO_BUTTON">ラジオボタン</el-radio>
              <el-radio label="NUMBER_SELECT">数字選択（プルダウン）</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-input
                v-if="question.questionTypeStr === 'INPUT_BOX_50'"
                v-model="question.input50"
                :maxlength="50"
                class="textarea-input"
                type="textarea"
                :rows="2"
                disabled
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
                v-if="question.questionTypeStr === 'INPUT_BOX_100'"
                v-model="question.input100"
                :maxlength="100"
                class="textarea-input100"
                type="textarea"
                :rows="2"
                disabled
            ></el-input>
          </el-form-item>
          <el-form-item v-if="question.questionTypeStr === 'CHECK_BOX'" style="margin-left: 125px;margin-top: -60px;">
            <!-- 循环渲染每一行：复选框 + 输入框 + 削除按钮 -->
            <div
                v-for="(item, itemIndex) in question.checkboxItems"
                :key="itemIndex"
                class="checkbox-row"
            >
              <div style="display: flex; align-items: center; width: 100%;">
                <span style="min-width: 30px; color: #666;">{{ item.sortOrder || itemIndex + 1 }}</span>
                <el-checkbox
                    v-model="item.checked"
                    class="checkbox-item"
                    disabled
                ></el-checkbox>
                <el-input
                    v-model="item.optionText"
                    class="input-item"
                    disabled
                ></el-input>
                <el-button
                    type="text"
                    class="delete-btn"
                    @click="deleteCheckboxItem(index, itemIndex)"
                    disabled
                >削除</el-button>
              </div>
            </div>
            <el-button
                class="append-btn"
                @click="addCheckboxItem(index)"
                disabled
            >追加</el-button>
          </el-form-item>
          <el-form-item v-if="question.questionTypeStr === 'RADIO_BUTTON'" style="margin-left: 125px;margin-top: -60px;">
            <!-- 循环渲染每一行：单选按钮 + 输入框 + 削除按钮 -->
            <div
                v-for="(item, itemIndex) in question.radioItems"
                :key="itemIndex"
                class="checkbox-row"
            >
              <div style="display: flex; align-items: center; width: 100%;">
                <span style="min-width: 30px; color: #666;">{{ item.sortOrder || itemIndex + 1 }}</span>
                <el-radio
                    :label="item.value"
                    v-model="question.radioGroupValue"
                    class="hidden-label-radio"
                    disabled
                ></el-radio>
                <el-input
                    v-model="item.optionText"
                    class="radio-item"
                    disabled
                ></el-input>
                <el-button
                    type="text"
                    class="radio-btn"
                    @click="deleteRadioItem(index, itemIndex)"
                    disabled
                >削除</el-button>
              </div>
            </div>
            <el-button
                class="append-btn"
                @click="addRadioItem(index)"
                disabled
            >追加</el-button>
          </el-form-item>
          <el-form-item v-if="question.questionTypeStr === 'NUMBER_SELECT'" style="margin-left: 120px;margin-top: -50px">
            <div style="display: flex; flex-direction: column; gap: 10px; width: 100%;">
              <!-- 選択肢部分 -->
              <div style="display: flex; align-items: center;  width: 100%;">
                <span>選択肢</span>
                <div style="width: 35px;"></div>
                <el-input type="number" disabled min="0" max="999" v-model="question.numberSelectStart" class="mx-2"
                          style="width: 60px;margin-right: 10px;"></el-input>
                <span>～</span>
                <el-input disabled type="number" min="0"  max="999" v-model="question.numberSelectEnd" class="mx-2"  style="width: 60px;margin-left: 10px;"></el-input>
              </div>
              <!-- 単位部分 -->
              <div style="display: flex; align-items: center; width: 100%; flex-wrap: nowrap; white-space: nowrap;">
                <span>単位</span>
                <el-radio-group disabled v-model="question.unitHas" class="mx-radio-group">
                  <el-radio :label="false" class="radio-group">なし</el-radio>
                  <el-radio :label="true">あり</el-radio>
                </el-radio-group>
                <el-input
                    v-model="question.questionUnit"
                    :maxlength="20"
                    style="width: 85px; margin-left: 10px;"
                    :disabled="!question.unitHas"
                ></el-input>
              </div>
            </div>
          </el-form-item>
          <el-form-item style="margin-left: 50px; margin-top: -10px;">
            <el-button class="append-button" disabled @click="addQuestionBelow(index)">この下に設問を追加</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>


<script name="SurveyDetail" setup>

import { getRegionTree,listSurveyDetail} from "@/api/fcbi/survey.js"
import { reactive, toRefs, ref, watch, onMounted } from 'vue';
import RegionTree from '../../../components/RegionTree.vue';
import { ElMessage } from "element-plus";
import {useRoute, useRouter} from 'vue-router';
import useSurveyStore from '@/store/modules/survey';

const { proxy } = getCurrentInstance();
const surveyStore = useSurveyStore()
// アップロード対象を取得
const { yamada_fc_brand } = proxy.useDict('yamada_fc_brand');
surveyStore.setBrandCode(yamada_fc_brand)
const { yamada_business_type } = proxy.useDict('yamada_business_type');
surveyStore.setBusinessTypeCode(yamada_business_type)
const error = ref('');

const regionTree = ref([]);
const selectedRegions = ref([]);
const router = useRouter();
const route= useRoute()
const surveyId = route.params.surveyId

/**
 * コンポーネントの状態を管理するリアクティブオブジェクト
 */
const data = reactive({
  form: {},
  // 検索条件を格納するオブジェクト
  queryParams: {
    title: null,
    description: null,
    brandCode: [],
    businessTypeCode: [],
    releaseType: 'immediate',
    startYear: '',
    startMonth: '',
    startDay: '',
    endYear: '',
    endMonth: '',
    endDay: '',
    publicStartTime: '',
    publicEndTime: '',
    publicMode: '',
    insertFlag: 1,
    regions: []
  },
  questions: [
    {
      questionText: '',
      questionTypeStr: 'INPUT_BOX_50',
      oldQuestionTypeStr: 'INPUT_BOX_50',
      input50: '',
      input100: '',
      checkboxItems: [
        { checked: false, optionText: '', sortOrder: 1 },
        { checked: false, optionText: '', sortOrder: 2 },
        { checked: false, optionText: '', sortOrder: 3 },
      ],
      radioItems: [
        { value: 'option1', optionText: '', sortOrder: 1 },
        { value: 'option2', optionText: '', sortOrder: 2 },
        { value: 'option3', optionText: '', sortOrder: 3 },
      ],
      radioGroupValue: null,
      numberSelectStart: '',
      numberSelectEnd: '',
      unitHas: false,
      sortOrder: 1,
      questionUnit: ''
    }
  ]
});

// 問題を動的に追加する方法
const addQuestionAbove = (index) => {
  const newSortOrder = data.questions[index].sortOrder;
  // 指定した場所に新しい問題を追加する
  data.questions.splice(index, 0, {
    questionText: '',
    questionType: 'INPUT_BOX_50',
    oldQuestionType: 'INPUT_BOX_50',
    input50: '',
    input100: '',
    checkboxItems: [
      { checked: false, optionText: '', sortOrder: 1 },
      { checked: false, optionText: '', sortOrder: 2 },
      { checked: false, optionText: '', sortOrder: 3 },
    ],
    radioItems: [
      { value: 'option1', optionText: '', sortOrder: 1 },
      { value: 'option2', optionText: '', sortOrder: 2 },
      { value: 'option3', optionText: '', sortOrder: 3 },
    ],
    radioGroupValue: null,
    numberSelectStart: '',
    numberSelectEnd: '',
    unitHas: false,
    sortOrder: newSortOrder,
    questionUnit: ''
  });
  adjustSortOrders(index);
};

const addQuestionBelow  = (index) => {
  const newSortOrder = data.questions[index].sortOrder + 1;
  // 指定した場所の下に新しい問題を追加する
  data.questions.splice(index + 1, 0, {
    questionText: '',
    questionType: 'INPUT_BOX_50',
    oldQuestionType: 'INPUT_BOX_50',
    input50: '',
    input100: '',
    checkboxItems: [
      { checked: false, optionText: '', sortOrder: 1 },
      { checked: false, optionText: '', sortOrder: 2 },
      { checked: false, optionText: '', sortOrder: 3 },
    ],
    radioItems: [
      { value: 'option1', optionText: '', sortOrder: 1 },
      { value: 'option2', optionText: '', sortOrder: 2 },
      { value: 'option3', optionText: '', sortOrder: 3 },
    ],
    radioGroupValue: null,
    numberSelectStart: '',
    numberSelectEnd: '',
    unitHas: false,
    sortOrder: newSortOrder,
    questionUnit: ''
  });
  adjustSortOrders(index + 1);
};

// 問題のソートの調整
const adjustSortOrders = (startIndex) => {
  for (let i = startIndex; i < data.questions.length; i++) {
    data.questions[i].sortOrder = i + 1;
  }
};

// 回答类型切换时重置前一类型的状态
const handleQuestionTypeChange = (question, newType) => {
  // 保存旧类型用于判断需要重置哪些数据
  const oldType = question.questionTypeStr;

  // 如果类型未变化，不执行重置
  if (oldType === newType) return;

  // 根据旧类型重置对应的数据（回到初始状态）
  switch (oldType) {
    case 'INPUT_BOX_50':
      question.input50 = ''; // 重置50文字输入框
      break;
    case 'INPUT_BOX_100':
      question.input100 = ''; // 重置100文字输入框
      break;
    case 'CHECK_BOX':
      // 重置复选框选项（保留3个空选项）
      question.checkboxItems = [
        { checked: false, optionText: '', sortOrder: 1 },
        { checked: false, optionText: '', sortOrder: 2 },
        { checked: false, optionText: '', sortOrder: 3 },
      ];
      break;
    case 'RADIO_BUTTON':
      // 重置单选按钮选项（保留3个空选项）
      question.radioItems = [
        { value: 'option1', optionText: '', sortOrder: 1 },
        { value: 'option2', optionText: '', sortOrder: 2 },
        { value: 'option3', optionText: '', sortOrder: 3 },
      ];
      question.radioGroupValue = null; // 重置选中状态
      break;
    case 'NUMBER_SELECT':
      // 重置数字选择器相关数据
      question.numberSelectStart = '';
      question.numberSelectEnd = '';
      question.unitHas = false; // 重置单位选择
      question.questionUnit = ''; // 重置单位输入框
      break;
  }

  // 更新为新类型（确保数据同步）
  question.questionTypeStr  = newType;
};

//ボタンの追加方法
const addCheckboxItem = (questionIndex) => {
  const question = data.questions[questionIndex];
  const newSortOrder = question.checkboxItems.length + 1;
  question.checkboxItems.push({
    checked: false,
    optionText: '',
    sortOrder: newSortOrder
  });
};

const addRadioItem = (questionIndex) => {
  const question = data.questions[questionIndex];
  const newId = question.radioItems.length + 1;
  const newSortOrder = question.radioItems.length + 1;
  question.radioItems.push({
    value: `option${newId}`,
    optionText: '',
    sortOrder: newSortOrder
  });
};


//消去ボタンの方法
const deleteRadioItem = (questionIndex, itemIndex) => {
  const question = data.questions[questionIndex];
  if (question.radioItems.length <= 3) {
    ElMessage.warning('少なくとも3つの選択肢を残してください');
    return;
  }
  question.radioItems.splice(itemIndex, 1);
  question.radioItems.forEach((item, index) => {
    item.sortOrder = index + 1;
  });
};

const deleteCheckboxItem = (questionIndex, itemIndex) => {
  const question = data.questions[questionIndex];
  if (question.checkboxItems.length <= 3) {
    ElMessage.warning('少なくとも3つの選択肢を残してください');
    return;
  }
  question.checkboxItems.splice(itemIndex, 1);
  question.checkboxItems.forEach((item, index) => {
    item.sortOrder = index + 1;
  });
};


// リアクティブオブジェクトからプロパティを参照可能なオブジェクトに変換
const { queryParams, questions } = toRefs(data);
const currentYear = new Date().getFullYear();
const years = Array.from({ length: 11 }, (_, i) => currentYear + i);
const months = Array.from({ length: 12 }, (_, i) => i + 1);
const days = Array.from({ length: 31 }, (_, i) => i + 1);

const formatDate = () => {
  if (queryParams.value.releaseType === 'scheduled') {
    const publicStartTime = `${queryParams.value.startYear}-${String(queryParams.value.startMonth).padStart(2, '0')}-${String(queryParams.value.startDay).padStart(2, '0')}`;
    const publicEndTime = `${queryParams.value.endYear}-${String(queryParams.value.endMonth).padStart(2, '0')}-${String(queryParams.value.endDay).padStart(2, '0')}`;
    queryParams.publicStartTime = publicStartTime;
    queryParams.publicEndTime = publicEndTime;
    queryParams.publicMode = 'PERIOD';
  } else {
    queryParams.publicStartTime = '';
    queryParams.publicEndTime = '';
    queryParams.value.startYear = '';
    queryParams.value.startMonth = '';
    queryParams.value.startDay = '';
    queryParams.value.endYear = '';
    queryParams.value.endMonth = '';
    queryParams.value.endDay = '';
    queryParams.publicMode = 'INSTANT';
  }
};

watch(() => queryParams.value.releaseType, () => {
  formatDate();
});

watch(regionTree, () => {
  if (regionTree.value.length > 0) {
    updateSelectedRegions(regionTree.value);
  }
}, { deep: true });

watch(
    () => data.questions.map(q => q.unitHas),
    (newValues, oldValues) => {
      data.questions.forEach((question, index) => {
        if (newValues[index] === false && oldValues[index] === true) {
          question.questionUnit = '';
        }
      });
    },
    { deep: true }
);

watch(
    () => data.questions.map(q => q.questionTypeStr),
    (newTypes, oldTypes) => {
      data.questions.forEach((question, index) => {
        const newType = newTypes[index];
        const oldType = oldTypes[index];
        if (newType === oldType) return;
        resetOldTypeData(question, oldType);
        question.oldQuestionTypeStr = oldType; // 记录旧类型
      });
    },
    { deep: true }
);
// 重置旧类型对应的所有数据
const resetOldTypeData = (question, oldType) => {
  switch (oldType) {
    case 'INPUT_BOX_50':
      question.input50 = '';
      break;
    case 'INPUT_BOX_100':
      question.input100 = '';
      break;
    case 'CHECK_BOX':
      question.checkboxItems = [
        { checked: false, optionText: '', sortOrder: 1 },
        { checked: false, optionText: '', sortOrder: 2 },
        { checked: false, optionText: '', sortOrder: 3 },
      ];
      break;
    case 'RADIO_BUTTON':
      question.radioItems = [
        { value: 'option1', optionText: '', sortOrder: 1 },
        { value: 'option2', optionText: '', sortOrder: 2 },
        { value: 'option3', optionText: '', sortOrder: 3 },
      ];
      question.radioGroupValue = null;
      break;
    case 'NUMBER_SELECT':
      question.numberSelectStart = '';
      question.numberSelectEnd = '';
      question.unitHas = false;
      question.questionUnit = '';
      break;
  }
};

onMounted(async () => {
  // 先加载地区数据
  const regionResponse = await getRegionTree();
  if (regionResponse?.success) {
    const regions = regionResponse.data.regions || []
    regionTree.value = regions
    surveyStore.setRegionTree(regions)
    if (regionTree.value.length > 0) {
      updateSelectedRegions(regionTree.value);
    }
  } else {
    error.value = regionResponse?.message || '地域データの取得に失敗しました';
    console.error('地域データの取得に失敗しました:', regionResponse);
  }

  // 加载问卷详情数据
  if (surveyId) {
    try {
      const requestData = { surveyId };
      const surveyResponse = await listSurveyDetail(requestData);

      if (surveyResponse.code === 200) {
        // 从返回结果中获取问卷数据（假设rows是数组，取第一个元素）
        const surveyData = surveyResponse.rows?.[0] || {};

        // 绑定基本信息（标题、描述、公开范围等）
        bindSurveyBasicInfo(surveyData);

        // 处理问题数据（后端返回的是JSON字符串）
        let questionArray = [];
        if (surveyData.question) {
          try {
            // 解析JSON字符串为数组
            questionArray = JSON.parse(surveyData.question);

            // 验证解析结果是否为数组
            if (!Array.isArray(questionArray)) {
              console.warn('question字段解析后不是数组，已初始化为空数组');
              questionArray = [];
            }
          } catch (e) {
            // 处理JSON解析错误
            console.error('question字段JSON解析失败:', e);
            console.error('原始字符串内容:', surveyData.question);
            ElMessage.error('アンケートの問題データ形式が無効です');
            questionArray = [];
          }
        } else {
          // 处理question字段为空的情况
          console.log('question字段为空，初始化为空数组');
          questionArray = [];
        }

        // 绑定问题列表
        bindSurveyQuestions(questionArray);

        // 绑定地区选择
        bindSelectedRegions(surveyData.region || []);

      } else {
        // 处理接口返回错误状态
        ElMessage.error(surveyResponse?.message || 'アンケートデータの取得に失敗しました');
      }
    } catch (err) {
      // 处理接口调用异常
      console.error('アンケートデータの取得中にエラーが発生しました:', err);
      ElMessage.error('アンケートデータの取得中にエラーが発生しました');
    }
  }
});

const bindSurveyBasicInfo = (surveyData) => {
  // 标题和描述
  queryParams.value.title = surveyData.title || '';
  queryParams.value.description = surveyData.description || '';

  // 公开范围 - FC
  if (surveyData.brandCode) {
    queryParams.value.brandCode = typeof surveyData.brandCode === 'string'
        ? JSON.parse(surveyData.brandCode)
        : (surveyData.brandCode || []);
  } else {
    queryParams.value.brandCode = [];
  }

  // 公开范围 - 業種
  if (surveyData.businessTypeCode) {
    queryParams.value.businessTypeCode = typeof surveyData.businessTypeCode === 'string'
        ? JSON.parse(surveyData.businessTypeCode)
        : (surveyData.businessTypeCode || []);
  } else {
    queryParams.value.businessTypeCode = [];
  }

  // 公开期间
  if (surveyData.publicMode === 'INSTANT') {
    queryParams.value.releaseType = 'immediate';
  } else if (surveyData.publicMode === 'PERIOD') {
    queryParams.value.releaseType = 'scheduled';
    // 解析开始日期
    if (surveyData.publicStartTime) {
      const startDate = new Date(surveyData.publicStartTime);
      queryParams.value.startYear = startDate.getFullYear();
      queryParams.value.startMonth = startDate.getMonth() + 1;
      queryParams.value.startDay = startDate.getDate();
    }
    // 解析结束日期
    if (surveyData.publicEndTime) {
      const endDate = new Date(surveyData.publicEndTime);
      queryParams.value.endYear = endDate.getFullYear();
      queryParams.value.endMonth = endDate.getMonth() + 1;
      queryParams.value.endDay = endDate.getDate();
    }
    formatDate();
  }
};

const bindSurveyQuestions = (questionsData) => {
  if (!questionsData.length) return;

  // 清空现有问题
  data.questions = [];

  // 绑定每个问题
  questionsData.forEach((q, index) => {
    const question = {
      questionText: q.questionText || '',
      questionTypeStr: q.questionTypeStr || 'INPUT_BOX_50',
      oldQuestionTypeStr: q.questionTypeStr || 'INPUT_BOX_50',
      input50: '',
      input100: '',
      checkboxItems: [],
      radioItems: [],
      radioGroupValue: null,
      numberSelectStart: '',
      numberSelectEnd: '',
      unitHas: false,
      sortOrder: index + 1,
      questionUnit: ''
    };

    // 根据问题类型绑定不同的内容
    switch (question.questionTypeStr) {
      case 'INPUT_BOX_50':
        question.input50 = q.input50 || '';
        break;
      case 'INPUT_BOX_100':
        question.input100 = q.input100 || '';
        break;
      case 'CHECK_BOX':
        question.checkboxItems = q.checkboxItems || [
          { checked: false, optionText: '', sortOrder: 1 },
          { checked: false, optionText: '', sortOrder: 2 },
          { checked: false, optionText: '', sortOrder: 3 },
        ];
        break;
      case 'RADIO_BUTTON':
        question.radioItems = q.radioItems || [
          { value: 'option1', optionText: '', sortOrder: 1 },
          { value: 'option2', optionText: '', sortOrder: 2 },
          { value: 'option3', optionText: '', sortOrder: 3 },
        ];
        question.radioGroupValue = q.radioGroupValue || null;
        break;
      case 'NUMBER_SELECT':
        question.numberSelectStart = q.numberSelectStart || '';
        question.numberSelectEnd = q.numberSelectEnd || '';
        question.unitHas = q.unitHas || false;
        question.questionUnit = q.questionUnit || '';
        break;
    }

    data.questions.push(question);
  });
};

const bindSelectedRegions = (region) => {

  const regionData = typeof region === 'string' ? JSON.parse(region) : region;

  selectedRegions.value = [...regionData];
  queryParams.value.regions = [...regionData];

  regionData.forEach(region => {
    checkRegionNode(regionTree.value, region.regionCode);
  });
};

const checkRegionNode = (nodes, regionCode, parentNode = null) => {
  for (const node of nodes) {
    if (node.regionCode === regionCode) {
      node.checked = true;
      // 子节点选中后，更新其父节点状态
      updateParentNodeStatus(parentNode);
      return true;
    }
    if (node.children && node.children.length > 0) {
      // 递归查找子节点时，将当前节点作为父节点传入
      const found = checkRegionNode(node.children, regionCode, node);
      if (found) return true;
    }
  }
  return false;
};

const updateParentNodeStatus = (parentNode) => {
  if (!parentNode) return; // 没有父节点则终止

  const children = parentNode.children || [];
  // 统计子节点中选中的数量
  const checkedCount = children.filter(child => child.checked).length;

  if (checkedCount === 0) {
    // 没有子节点选中：父节点不选中，也不是半选
    parentNode.checked = false;
    parentNode.indeterminate = false;
  } else if (checkedCount === children.length) {
    // 所有子节点都选中：父节点选中，不是半选
    parentNode.checked = true;
    parentNode.indeterminate = false;
  } else {
    // 部分子节点选中：父节点不选中，但为半选
    parentNode.checked = false;
    parentNode.indeterminate = true;
  }

  // 继续向上更新父节点的父节点（递归）
  updateParentNodeStatus(parentNode.parent);
};




// 選択した状態変更の処理
const handleCheckChange = (regionId, isChecked) => {
  const region = findRegionById(regionTree.value, regionId);
  if (region) {
    if (isChecked) {
      if (!selectedRegions.value.some(r => r.regionCode === region.regionCode)) {
        selectedRegions.value.push({
          regionCode: region.regionCode  // 字段名修改
        });
      }
    } else {
      selectedRegions.value = selectedRegions.value.filter(r => r.regionCode !== region.regionCode);
    }
    queryParams.value.regions = selectedRegions.value;
  }
};

const findRegionById = (nodes, id) => {
  for (const node of nodes) {
    if (node.id === id) {
      return node;
    }
    if (node.children && node.children.length > 0) {
      const found = findRegionById(node.children, id);
      if (found) {
        return found;
      }
    }
  }
  return null;
};

// 選択したすべての領域を再帰的に更新し、サブノードのみを収集
const updateSelectedRegions = (nodes) => {
  selectedRegions.value = [];
  // 最上位ノードは親ノードとしてマークされ、再帰的になる
  collectSelectedRegions(nodes, true);
  queryParams.value.regions = selectedRegions.value;
};

// 選択したすべてのサブエリアオブジェクトを再帰的に収集する（親ノードをスキップ）
const collectSelectedRegions = (nodes, isParent = false) => {
  nodes.forEach(node => {
    if (isParent) {
      if (node.children && node.children.length > 0) {
        collectSelectedRegions(node.children, false);
      }
      return;
    }
    if (node.checked) {
      selectedRegions.value.push({
        regionCode: node.regionCode
      });
    }
    if (node.children && node.children.length > 0) {
      collectSelectedRegions(node.children, false);
    }
  });
};
</script>


<style>
/* 小さい入力框样式（設問文输入框） */
.small-input {
  width: 600px;
  margin-left: 20px;
  margin-top: -10px;
}
/* 表格输入框样式（タイトル和説明文输入框） */
.table-input{
  width: 600px;
  margin-left: 20px;
  margin-top: -5px;
}
/* 确认按钮样式 */
.confirm-button{
  background-color: #FF0066;
  color: white;
  width:300px;
  margin-left: 160px;
}
/* 追加按钮样式（この上に設問を追加/この下に設問を追加按钮） */
.append-button{
  background-color: #FF0066;
  color: white;
}
/* 表单容器整体样式 */
.form-container {
  margin-top: 40px;
}
/* 段落样式调整 */
p {
  margin-bottom: 10px;
}
/* 表单区块标题样式（公開期間、エリア等标题） */
.form-section {
  font-size: 14px;
  font-weight: bold;
  margin: -10px 0 5px 27px;
}
/* 垂直排列的单选框组容器样式 */
.radio-group-vertical {
  margin-left: 65px;
}
/* 移动端垂直排列的单选框组容器样式适配 */
@media (max-width:48em) {
  .radio-group-vertical  {
    margin-left: 7%;
  }
}
/* 单选框容器布局控制 */
.radio-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
/* 即時公開单选框样式 */
.vertical-radio {
  display: flex;
  align-items: center;
}
/* 期間指定单选框样式 */
.scheduled-radio{
  display: flex;
  align-items: center;
  margin-top: -15px;
}
/* 日期选择区域布局 */
.scheduled-row {
  display: flex;
  align-items: center;
  margin-left: 88px;
  margin-top: -45px;
}
/* 移动端日期选择区域布局适配 */
@media (max-width:48em) {
  .scheduled-row  {
    margin-left: 13%;
    width: 80%;
  }
}
/* 日期选择器组合样式 */
.date-group {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: 8px;
}
/* 年份选择器宽度 */
.date-select {
  min-width: 80px;
}
/* 月/日选择器宽度 */
.date-select-small {
  min-width: 60px;
}
/* 日期单位文本样式（年/月/日） */
.date-label {
  font-size: 14px;
  color: #666;
}
/* 地区选择区域布局 */
.area-header-row {
  display: flex;
  align-items: flex-start;
}
/* 地区标题与选择器间距 */
.area-header-row h1 {
  margin: -8px 20px 0 0;
}
/* 地区标题样式 */
.area-title {
  font-size: 14px;
  margin-left: 57px !important;
}
/* 移动端地区标题适配 */
@media (max-width:48em) {
  .area-title  {
    margin-left:13% !important;
  }
}
/* 回答类型单选框组布局 */
.custom-radio-group {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-left: 35px !important;
}
/* 前4个回答类型单选框间距 */
.custom-radio-group > .el-radio:nth-child(-n+4) {
  margin-right: 20px;
}
/* 第5个回答类型单选框（数字選択）强制换行 */
.custom-radio-group > .el-radio:nth-child(5) {
  width: 100%;
}
/* 50文字输入框样式 */
.textarea-input{
  width: 600px;
  margin-left: 105px !important;
  margin-top: -20px;
}
/* 100文字输入框样式 */
.textarea-input100{
  width: 600px;
  margin-left: 105px !important;
  margin-top: -40px;
}
/* 复选框选项行布局 */
.checkbox-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;
}
/* 复选框与输入框间距 */
.checkbox-item {
  margin-right: 8px;
}
/* 单选框样式（隐藏原生标签） */
.hidden-label-radio {
  margin-right: 8px;
}
.hidden-label-radio .el-radio__label {
  display: none !important;
}
/* 复选框选项输入框宽度 */
.input-item {
  margin: 0 8px;
  width: 15%;
}
/* 移动端复选框输入框适配 */
@media (max-width:48em) {
  .input-item {
    width: 60%;
  }
}
/* 单选框选项输入框宽度 */
.radio-item{
  width: 15%;
}
/* 移动端单选框输入框适配 */
@media (max-width:48em) {
  .radio-item {
    width: 60%;
  }
}
/* 复选框删除按钮样式 */
.delete-btn {
  color: #409eff;
  text-decoration: underline;
}
/* 单选框删除按钮样式 */
.radio-btn{
  margin-left: 8px;
  color: #409eff;
  text-decoration: underline;
}
/* 选项追加按钮样式 */
.append-btn {
  display: inline-block;
  background-color: black;
  color: white;
  margin-left:18%;
}
/* 移动端追加按钮适配 */
@media (max-width:48em) {
  .append-btn  {
    margin-left:80%;
  }
}
/* 地区选择树样式 */
.region-tree-container {
  margin-top: -12px;
  margin-left: -2px;
}
/* 業種复选框组布局 */
.el-form-item__businessTypeCode{
  margin-left: 55px;
  display: flex;
  align-items: center;
  margin-top: -15px;
}
/* 移动端業種复选框组适配 */
@media (max-width:48em) {
  .el-form-item__businessTypeCode  {
    margin-left:13%;
  }
}
/* 数字选择器单位单选框组样式 */
.mx-radio-group{
  margin-left: 60px;
  min-width: 120px;
}
/* 移动端数字选择器单位适配 */
@media (max-width:48em) {
  .mx-radio-group  {
    margin-left: 45px;
    min-width: 110px;
  }
}
/* 单位单选框间距 */
.radio-group{
  margin-right: 50px;
}
/* 移动端单位单选框间距适配 */
@media (max-width:48em) {
  .radio-group  {
    margin-right: 10px;
  }
}
</style>
