<template>
  <div class="store-label-container">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="140px" class="store-label-form">
      <!-- 头部：固定标题 -->
      <div class="form-header">
        <div class="form-left">
          <h3 class="section-title">基础信息—顾客必看</h3>
        </div>
        <div class="form-right">
          <h3 class="section-title">门店介绍-顾客想看</h3>
        </div>
      </div>

      <!-- 中间：可滚动的内容区域 -->
      <div class="form-content">
        <!-- 左侧：基础信息 -->
        <div class="form-left">
          <!-- 动态渲染标签卡片 -->
          <template v-for="(tagGroup, groupIndex) in leftTagGroups" :key="groupIndex">
            <div class="tag-card">
              <div class="card-header">
                <span class="header-icon" />
                <span class="header-title">{{ tagGroup.labelName }}</span>
              </div>
              <div class="card-content">
                <template v-for="(item, itemIndex) in tagGroup.list" :key="itemIndex">
                  <!-- radioDouble类型：组合按钮（例如：卫生间、停车场、大桌、包厢） -->
                  <div v-if="item.labelButtonType === 'radioDouble'" class="form-item-wrapper">
                    <el-form-item :label="item.label">
                      <div class="radio-double-wrapper">
                        <div class="first-option">
                          <el-radio-group v-model="formData[item.field_1]" @change="handleFormChange">
                            <el-radio
                              v-for="(option, optIndex) in item.labelButtonOption_1"
                              :key="optIndex"
                              :label="option.value"
                              :value="option.value"
                            >
                              {{ option.name }}
                            </el-radio>
                          </el-radio-group>
                        </div>
                        <!-- 判断卫生间、停车场、大桌、包厢，这几项只有选择"有"的时候才显示下方的选项 -->
                        <div
                          v-if="
                            (item.field_1 && formData[item.field_1] == 1) ||
                            (item.field_5 && formData[item.field_5] == 1) ||
                            (item.field_7 && formData[item.field_7] == 1) ||
                            (item.field_11 && formData[item.field_11] == 1)
                          "
                          class="second-option"
                        >
                          <div class="sub-label">
                            {{ item.tips }}
                          </div>
                          <el-radio-group v-if="item.field_2" v-model="formData[item.field_2]" @change="handleFormChange">
                            <el-radio
                              v-for="(option, optIndex) in item.labelButtonOption_2"
                              :key="optIndex"
                              :label="option.value"
                              :value="option.value"
                            >
                              {{ option.name }}
                            </el-radio>
                          </el-radio-group>
                        </div>
                      </div>
                    </el-form-item>
                  </div>

                  <!-- radio类型：单选有无（例如：wifi、室内空调等） -->
                  <div v-if="item.labelButtonType === 'radio'" class="form-item-wrapper">
                    <el-form-item :label="item.label" :class="{ 'vertical-layout': item.label === '吸烟' }">
                      <el-radio-group v-model="formData[item.field_1]" @change="handleFormChange">
                        <el-radio
                          v-for="(option, optIndex) in item.labelButtonOption_1"
                          :key="optIndex"
                          :label="option.value"
                          :value="option.value"
                        >
                          {{ option.name }}
                        </el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </div>

                  <!-- radios类型：单选（例如：位置类型、装修风格等） -->
                  <div v-if="item.labelButtonType === 'radios'" class="form-item-wrapper">
                    <el-form-item :label="item.label">
                      <el-radio-group v-model="formData[item.field_1]" @change="handleFormChange">
                        <el-radio
                          v-for="(option, optIndex) in item.labelButtonOption_1"
                          :key="optIndex"
                          :label="option.value"
                          :value="option.value"
                        >
                          {{ option.name }}
                        </el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </div>

                  <!-- checkbox类型：多选（多列显示） -->
                  <div v-if="item.labelButtonType === 'checkbox'" class="form-item-wrapper">
                    <el-form-item :label="item.label">
                      <div class="checkbox-grid">
                        <el-checkbox-group v-model="formData[item.field_1]" @change="handleCheckboxChange(item.field_1, $event)">
                          <el-checkbox
                            v-for="(option, optIndex) in item.labelButtonOption_1"
                            :key="optIndex"
                            :label="option.value"
                            :value="option.value"
                          >
                            {{ option.name }}
                          </el-checkbox>
                        </el-checkbox-group>
                      </div>
                    </el-form-item>
                  </div>

                  <!-- 分隔线 -->
                  <el-divider v-if="itemIndex !== tagGroup.list.length - 1 && item.label" />
                </template>
              </div>
            </div>
          </template>
        </div>

        <!-- 右侧：门店介绍 -->
        <div class="form-right">
          <!-- 动态渲染标签卡片 -->
          <template v-for="(tagGroup, groupIndex) in rightTagGroups" :key="groupIndex">
            <div class="tag-card">
              <div class="card-header">
                <span class="header-icon" />
                <span class="header-title">{{ tagGroup.labelName }}</span>
              </div>
              <div class="card-content">
                <template v-for="(item, itemIndex) in tagGroup.list" :key="itemIndex">
                  <!-- radioDouble类型：组合按钮 -->
                  <div v-if="item.labelButtonType === 'radioDouble'" class="form-item-wrapper">
                    <el-form-item :label="item.label">
                      <div class="radio-double-wrapper">
                        <div class="first-option">
                          <el-radio-group v-model="formData[item.field_1]" @change="handleFormChange">
                            <el-radio
                              v-for="(option, optIndex) in item.labelButtonOption_1"
                              :key="optIndex"
                              :label="option.value"
                              :value="option.value"
                            >
                              {{ option.name }}
                            </el-radio>
                          </el-radio-group>
                        </div>
                        <div
                          v-if="
                            (item.field_1 && formData[item.field_1] == 1) ||
                            (item.field_5 && formData[item.field_5] == 1) ||
                            (item.field_7 && formData[item.field_7] == 1) ||
                            (item.field_11 && formData[item.field_11] == 1)
                          "
                          class="second-option"
                        >
                          <div class="sub-label">
                            {{ item.tips }}
                          </div>
                          <el-radio-group v-if="item.field_2" v-model="formData[item.field_2]" @change="handleFormChange">
                            <el-radio
                              v-for="(option, optIndex) in item.labelButtonOption_2"
                              :key="optIndex"
                              :label="option.value"
                              :value="option.value"
                            >
                              {{ option.name }}
                            </el-radio>
                          </el-radio-group>
                        </div>
                      </div>
                    </el-form-item>
                  </div>

                  <!-- radio类型：单选有无 -->
                  <div v-if="item.labelButtonType === 'radio'" class="form-item-wrapper">
                    <el-form-item :label="item.label" :class="{ 'vertical-layout': item.label === '吸烟' }">
                      <el-radio-group v-model="formData[item.field_1]" @change="handleFormChange">
                        <el-radio
                          v-for="(option, optIndex) in item.labelButtonOption_1"
                          :key="optIndex"
                          :label="option.value"
                          :value="option.value"
                        >
                          {{ option.name }}
                        </el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </div>

                  <!-- radios类型：单选 -->
                  <div v-if="item.labelButtonType === 'radios'" class="form-item-wrapper">
                    <el-form-item :label="item.label">
                      <el-radio-group v-model="formData[item.field_1]" @change="handleFormChange">
                        <el-radio
                          v-for="(option, optIndex) in item.labelButtonOption_1"
                          :key="optIndex"
                          :label="option.value"
                          :value="option.value"
                        >
                          {{ option.name }}
                        </el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </div>

                  <!-- checkbox类型：多选（多列显示） -->
                  <div v-if="item.labelButtonType === 'checkbox'" class="form-item-wrapper">
                    <el-form-item :label="item.label">
                      <div class="checkbox-grid">
                        <el-checkbox-group v-model="formData[item.field_1]" @change="handleCheckboxChange(item.field_1, $event)">
                          <el-checkbox
                            v-for="(option, optIndex) in item.labelButtonOption_1"
                            :key="optIndex"
                            :label="option.value"
                            :value="option.value"
                          >
                            {{ option.name }}
                          </el-checkbox>
                        </el-checkbox-group>
                      </div>
                    </el-form-item>
                  </div>

                  <!-- 分隔线 -->
                  <el-divider v-if="itemIndex !== tagGroup.list.length - 1 && item.label" />
                </template>
              </div>
            </div>
          </template>
        </div>
      </div>

      <!-- 保存按钮 -->
      <div class="form-footer">
        <el-button type="primary" size="large" :loading="loading" @click="handleSave"> 保存 </el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { localGet } from "@/utils";
import { getTagList, getAllTag, saveTag } from "@/api/modules/storeDecoration";

const loading = ref(false);
const formRef = ref<FormInstance>();

// 标签分组数据
const tagGroups = ref<
  Array<{
    labelName: string;
    list: Array<{
      label: string;
      labelButtonType: "radioDouble" | "radio" | "radios" | "checkbox";
      field_1: string;
      field_2?: string;
      field_5?: string;
      field_7?: string;
      field_11?: string;
      tips?: string;
      labelButtonOption_1: Array<{ name: string; value: string | number }>;
      labelButtonOption_2?: Array<{ name: string; value: string | number }>;
    }>;
  }>
>([]);

// 左侧标签组（基础信息）
const leftTagGroups = computed(() => {
  return tagGroups.value.filter(group => group.labelName === "基础设施");
});

// 右侧标签组（门店介绍）
const rightTagGroups = computed(() => {
  return tagGroups.value.filter(group => group.labelName === "门店介绍");
});

// 表单数据（动态字段）
const formData = reactive<Record<string, any>>({});

// 表单校验规则
const rules = reactive<FormRules>({});

// 处理表单变化
const handleFormChange = () => {
  // 表单数据变化时的处理逻辑
};

// 处理多选框变化（保持为数组）
const handleCheckboxChange = (fieldName: string, value: any[]) => {
  formData[fieldName] = value;
  handleFormChange();
};

// 保存数据
const handleSave = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
  } catch (error) {
    ElMessage.warning("请完善表单信息");
    return;
  }

  loading.value = true;
  try {
    const userInfo: any = localGet("geeker-user")?.userInfo || {};
    const storeId = userInfo.storeId;
    if (!storeId) {
      ElMessage.error("未找到店铺ID");
      loading.value = false;
      return;
    }

    // 调用保存门店标签接口 saveTag API
    // 在保存前，将checkbox类型的数组字段转换为字符串
    const params: any = {
      ...formData,
      storeId: Number(storeId)
    };

    // 遍历所有checkbox字段，将数组转换为逗号分隔的字符串
    tagGroups.value.forEach(group => {
      group.list.forEach(item => {
        if (item.labelButtonType === "checkbox" && item.field_1) {
          const fieldName = item.field_1;
          if (Array.isArray(params[fieldName])) {
            params[fieldName] = params[fieldName].join(",");
          } else if (!params[fieldName]) {
            params[fieldName] = "";
          }
        }
      });
    });

    const res: any = await saveTag(params);
    if (res && (res.code === 200 || res.code === "200")) {
      ElMessage.success("保存成功");
    } else {
      ElMessage.error(res?.msg || "保存失败");
    }
  } catch (error: any) {
    console.error("保存失败:", error);
    ElMessage.error(error?.msg || "保存失败，请重试");
  } finally {
    loading.value = false;
  }
};

/** 解析 getTagList 记录里的 labelButtonOptionOne / Two（JSON 字符串） */
function parseLabelButtonOptions(jsonStr: unknown): Array<{ name: string; value: string | number }> {
  if (jsonStr == null || jsonStr === "") return [];
  if (typeof jsonStr !== "string") return [];
  try {
    const arr = JSON.parse(jsonStr);
    if (!Array.isArray(arr)) return [];
    return arr.map((o: any) => ({
      name: o?.name ?? "",
      value: o?.value ?? ""
    }));
  } catch {
    return [];
  }
}

const FORM_BUTTON_TYPES = ["radioDouble", "radio", "radios", "checkbox"] as const;

/** 将 getTagList 单条 record 转为模板使用的 list 项 */
function mapTagListRecordToItem(raw: Record<string, any>) {
  const bt = raw.labelButtonType;
  const labelButtonType = (FORM_BUTTON_TYPES as readonly string[]).includes(bt) ? bt : "radio";
  const opt2 = parseLabelButtonOptions(raw.labelButtonOptionTwo);
  const item: {
    label: string;
    labelButtonType: (typeof FORM_BUTTON_TYPES)[number];
    field_1: string;
    field_2?: string;
    field_5?: string;
    field_7?: string;
    field_11?: string;
    tips?: string;
    labelButtonOption_1: Array<{ name: string; value: string | number }>;
    labelButtonOption_2?: Array<{ name: string; value: string | number }>;
  } = {
    label: raw.label ?? "",
    labelButtonType: labelButtonType as (typeof FORM_BUTTON_TYPES)[number],
    field_1: raw.field_1 ?? "",
    tips: raw.labelDescribe || "",
    labelButtonOption_1: parseLabelButtonOptions(raw.labelButtonOptionOne)
  };
  if (raw.field_2) item.field_2 = raw.field_2;
  if (opt2.length) item.labelButtonOption_2 = opt2;
  return item;
}

/** 根据 getTagList 分页 data 构建 tagGroups（左：基础设施 / 右：门店介绍） */
function buildTagGroupsFromListPageData(data: Record<string, any> | null | undefined) {
  const records = Array.isArray(data?.records) ? [...data!.records] : [];
  records.sort((a: any, b: any) => (Number(a?.tagSort) || 0) - (Number(b?.tagSort) || 0));
  const infraList: ReturnType<typeof mapTagListRecordToItem>[] = [];
  const introList: ReturnType<typeof mapTagListRecordToItem>[] = [];
  for (const r of records) {
    if (!r || typeof r !== "object") continue;
    const item = mapTagListRecordToItem(r as Record<string, any>);
    const lt = (r as Record<string, any>).labelType;
    if (lt === "infrastructure") infraList.push(item);
    else if (lt === "storeIntroduction") introList.push(item);
  }
  const groups: typeof tagGroups.value = [];
  if (infraList.length) groups.push({ labelName: "基础设施", list: infraList });
  if (introList.length) groups.push({ labelName: "门店介绍", list: introList });
  return groups;
}

// 初始化表单数据（门店已选值：与标签定义分离，仍走原门店关系接口）
const initFormData = async () => {
  try {
    const userInfo: any = localGet("geeker-user")?.userInfo || {};
    const storeId = userInfo.storeId;
    if (!storeId) {
      console.warn("未找到店铺ID");
      return;
    }

    const res: any = await getAllTag({ storeId: Number(storeId) });
    if (res && (res.code === 200 || res.code === "200") && res.data) {
      Object.assign(formData, res.data);
      tagGroups.value.forEach(group => {
        group.list.forEach(item => {
          if (item.labelButtonType === "checkbox" && item.field_1) {
            const fieldName = item.field_1;
            const value = formData[fieldName];
            if (value && typeof value === "string") {
              formData[fieldName] = value.split(",").filter(Boolean);
            } else if (!value) {
              formData[fieldName] = [];
            }
          } else if (item.field_1 && formData[item.field_1] === undefined) {
            formData[item.field_1] = "";
          }
        });
      });
    }
  } catch (error) {
    console.error("获取门店标签数据失败:", error);
  }
};

// 初始化标签结构（渲染用）：来自 getTagList 的 records
const initTagOptions = async () => {
  try {
    const first: any = await getTagList({ pageNum: 1, pageSize: 1 });
    if (!(first && (first.code === 200 || first.code === "200") && first.data)) {
      return;
    }
    const recLen = first.data.records?.length ?? 0;
    const apiTotal = Number(first.data.total);
    const targetSize = Number.isFinite(apiTotal) && apiTotal > 0 ? Math.min(apiTotal, 500) : Math.min(Math.max(recLen, 1), 500);
    let pageData = first.data;
    if (targetSize > recLen) {
      const full: any = await getTagList({ pageNum: 1, pageSize: targetSize });
      if (full && (full.code === 200 || full.code === "200") && full.data) {
        pageData = full.data;
      }
    }
    tagGroups.value = buildTagGroupsFromListPageData(pageData);
  } catch (error) {
    console.error("获取标签列表失败:", error);
  }
};

// 页面初始化
onMounted(async () => {
  // 先初始化标签选项
  await initTagOptions();
  // 再初始化表单数据（需要先有标签选项，才能正确处理checkbox数据）
  await initFormData();
});
</script>

<style scoped lang="scss">
.store-label-container {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  height: 85vh;
  padding: 20px;
  overflow: hidden;
  background-color: white;
  .store-label-form {
    display: flex;
    flex-direction: column;
    height: 100%;
    min-height: 0;
    overflow: hidden;

    // 头部：固定标题
    .form-header {
      z-index: 10;
      display: flex;
      flex-shrink: 0;
      gap: 40px;
      padding-bottom: 20px;
      background-color: white;
      border-bottom: 1px solid #f0f0f0;
      .form-left,
      .form-right {
        flex: 1;
        .section-title {
          padding-bottom: 12px;
          margin-bottom: 0;
          font-size: 16px;
          font-weight: bold;
          color: #000000;
          border-bottom: none;
        }
      }
    }

    // 中间：可滚动的内容区域
    .form-content {
      display: flex;
      flex: 1;
      gap: 40px;
      min-height: 0;
      padding-top: 20px;
      padding-right: 10px;
      margin-right: -10px;
      overflow: hidden auto;

      // 自定义滚动条样式
      &::-webkit-scrollbar {
        width: 8px;
      }
      &::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 4px;
      }
      &::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 4px;
        &:hover {
          background: #a8a8a8;
        }
      }
      .form-left,
      .form-right {
        flex: 1;
        .tag-card {
          padding: 20px;
          margin-bottom: 24px;
          background: #ffffff;
          border-radius: 8px;
          box-shadow: 0 2px 12px 0 rgb(0 0 0 / 6%);
          .card-header {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
            font-size: 16px;
            font-weight: bold;
            color: #334154;
            .header-icon {
              display: inline-block;
              width: 4px;
              height: 18px;
              margin-right: 12px;
              background-color: #6c8ff8;
              border-radius: 2px;
            }
            .header-title {
              font-size: 16px;
              font-weight: bold;
              color: #334154;
            }
          }
          .card-content {
            padding: 20px 10px;
            background: #ffffff;
            border-radius: 8px;
            box-shadow: 0 -2px 12px 0 rgb(86 125 244 / 5%);
            .form-item-wrapper {
              margin-bottom: 20px;
              &:last-child {
                margin-bottom: 0;
              }
            }
          }
        }
      }
    }
    .form-footer {
      display: flex;
      flex-shrink: 0;
      justify-content: center;
      padding: 24px 0;
      margin-top: 20px;
      background-color: white;
      border-top: 1px solid #f0f0f0;
    }
  }
}

// 表单样式
:deep(.el-form-item) {
  margin-bottom: 24px;
  .el-form-item__label {
    font-weight: 500;
    color: #606266;
  }
  &.vertical-layout {
    .el-form-item__content {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
    }
  }
}
.radio-double-wrapper {
  .first-option {
    margin-bottom: 12px;
  }
  .second-option {
    padding: 20px;
    margin-top: 12px;
    background: #f8f9ff;
    border-radius: 8px;
    .sub-label {
      margin-bottom: 12px;
      font-size: 14px;
      font-weight: 500;
      color: #666666;
    }
  }
}
:deep(.el-radio-group) {
  display: flex;
  flex-flow: row wrap;
  gap: 12px;
  width: 100%;
  .el-radio {
    margin-right: 0;
    margin-bottom: 0;
    white-space: nowrap;
    .el-radio__label {
      padding-left: 8px;
    }
  }
}
:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.checkbox-grid {
  :deep(.el-checkbox-group) {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px 20px;
  }
}
:deep(.el-divider) {
  margin: 20px 0;
}
</style>
