<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加食谱"
    width="1100px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="true"
    append-to-body
  >
    <div class="recipe-template-dialog">
      <!-- 顶部tab和搜索 -->
      <div class="header-bar">
        <el-tabs v-model="activeTab" class="tabs">
          <el-tab-pane label="日食谱" name="day"></el-tab-pane>
          <el-tab-pane label="周食谱" name="week"></el-tab-pane>
        </el-tabs>
        <div class="search-bar">
          <el-input v-model="search" placeholder="请输入食谱名称" class="search-input">
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" class="search-btn">查询</el-button>
        </div>
      </div>
      <div class="main-content">
        <!-- 左侧树 -->
        <div class="left-panel">
          <el-scrollbar>
            <el-tree
              ref="treeRef"
              :data="treeData"
              :show-checkbox="activeTab === 'day'"
              node-key="id"
              :default-expand-all="true"
              :props="treeProps"
              :highlight-current="activeTab === 'week'"
              :expand-on-click-node="activeTab === 'week'"
              @check="updateSelectedLeafNodes"
              @node-click="handleNodeClick"
              class="tree-block"
            />
          </el-scrollbar>
        </div>
        <!-- 右侧分组明细表格 -->
        <div class="right-content">
          <!-- 周食谱顶部tab -->
          <div v-if="activeTab === 'week'" class="week-tabs">
            <el-tabs v-model="activeWeekTab" class="recipe-tabs" @tab-change="handleWeekTabChange">
              <el-tab-pane v-for="tab in weekTabs" :key="tab" :label="tab" :name="tab"></el-tab-pane>
            </el-tabs>
          </div>
          <el-scrollbar>
            <el-table
              v-if="groupedDetail.length"
              :data="groupedDetail"
              class="detail-table"
              :row-class-name="groupRowClassName"
              :span-method="groupSpanMethod"
              :border="false"
              :show-header="false"
              size="small"
              style="width: 580px"
            >
              <el-table-column prop="meal" label="餐次" min-width="200">
                <template #default="{row}">
                  <div v-if="row._isGroup" class="group-header">
                    <span class="meal-name">{{ row.meal }}</span>
                    <span class="total-kcal">{{ row.kcalSum.toFixed(4) }}kcal</span>
                  </div>
                  <span v-else>{{ row.meal }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="weight" label="克" width="160" align="right">
                <template #default="{row}">
                  {{ row._isGroup ? '' : row.weight }}
                </template>
              </el-table-column>
              <el-table-column prop="kcal" label="千卡" width="160" align="right">
                <template #default="{row}">
                  {{ row._isGroup ? '' : row.kcal }}
                </template>
              </el-table-column>
            </el-table>
            <div v-else class="empty-data">暂无数据</div>
          </el-scrollbar>
        </div>
      </div>
      <!-- 底部已选 -->
      <div class="selected-bar">
        <span>已选({{ selected.length }}):</span>
        <div class="selected-tags">
          <el-tag v-for="item in selected" :key="item.id" closable @close="removeSelected(item)" size="small">{{ item.label }}</el-tag>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="footer-btns">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="confirmDialog">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {ref, defineExpose, nextTick, computed} from 'vue';
import {Search} from '@element-plus/icons-vue';
import {ElMessage} from 'element-plus';

interface RecipeDetail {
  meal: string;
  dish: string;
  weight: string;
  kcal: string;
}

interface Recipe {
  label: string;
  detail?: RecipeDetail[];
}

const emit = defineEmits<{
  (
    e: 'confirm',
    data: Array<{
      name: string;
      meals: Array<{
        meal: string;
        dish: string;
        weight: string;
        kcal: string;
      }>;
    }>
  ): void;
  (e: 'cancel'): void;
}>();

const dialogVisible = ref(false);
const activeTab = ref('day');
const search = ref('');
const activeWeekTab = ref('食谱一');
const weekTabs = ['食谱一', '食谱二', '食谱三', '食谱四', '食谱五', '食谱六', '食谱七'];

// 当前选中的节点
const currentNode = ref<any>(null);

// 模拟周食谱数据
const weekRecipeDetail = {
  '东北地区夏季糖尿病食谱': {
    '食谱一': [
      {meal: '早餐', dish: '蒸南瓜（大份）', weight: '200.0000g', kcal: '37.4000kcal'},
      {meal: '早餐', dish: '纯牛奶', weight: '250.0000g', kcal: '125.0000kcal'},
      {meal: '早餐', dish: '皮蛋豆腐', weight: '100.0000g', kcal: '116.5950kcal'},
      {meal: '中餐', dish: '鸡汤面', weight: '130.0000g', kcal: '374.5000kcal'},
      {meal: '中餐', dish: '豌豆胡萝卜', weight: '70.0000g', kcal: '163.6040kcal'},
      {meal: '中餐', dish: '蘑菇青菜炒肉', weight: '85.0000g', kcal: '88.0150kcal'},
      {meal: '中加', dish: '水果', weight: '150.0000g', kcal: '36.8000kcal'}
    ],
    '食谱二': [
      {meal: '早餐', dish: '小米粥', weight: '200.0000g', kcal: '180.0000kcal'},
      {meal: '早餐', dish: '煮鸡蛋', weight: '50.0000g', kcal: '77.0000kcal'},
      {meal: '早餐', dish: '生菜', weight: '100.0000g', kcal: '15.0000kcal'},
      {meal: '中餐', dish: '糙米饭', weight: '150.0000g', kcal: '165.0000kcal'},
      {meal: '中餐', dish: '清炒小白菜', weight: '200.0000g', kcal: '42.0000kcal'},
      {meal: '中餐', dish: '红烧带鱼', weight: '150.0000g', kcal: '195.0000kcal'},
      {meal: '中加', dish: '酸奶', weight: '200.0000g', kcal: '120.0000kcal'}
    ]
  }
};

// 处理树节点点击
const handleNodeClick = (node: any) => {
  if (activeTab.value === 'week') {
    currentNode.value = node;
    // 如果是叶子节点，更新右侧表格数据
    if (!node.children || !node.children.length) {
      const recipeData = weekRecipeDetail[node.label]?.[activeWeekTab.value] || [];
      selectedDetail.value = recipeData;
    }
  }
};

// 监听周食谱tab切换
const handleWeekTabChange = (tab: string) => {
  if (currentNode.value && (!currentNode.value.children || !currentNode.value.children.length)) {
    const recipeData = weekRecipeDetail[currentNode.value.label]?.[tab] || [];
    selectedDetail.value = recipeData;
  }
};

// 更新树形数据结构
const treeData = ref([
  {
    id: 1,
    label: '基础公共模版',
    children: [
      {
        id: 2,
        label: '糖尿病周食谱（东北地区）分类',
        children: [
          {
            id: 3,
            label: '东北地区冬季糖尿病食谱',
            detail: [
              {meal: '早餐', dish: '蒸芋头', weight: '50.0000g', kcal: '33.1800kcal'},
              {meal: '早餐', dish: '豆腐脑', weight: '200.0000g', kcal: '20.0000kcal'},
              {meal: '早餐', dish: '西兰花木耳', weight: '105.0000g', kcal: '72.6650kcal'},
              {meal: '中餐', dish: '杂粮饭', weight: '60.0000g', kcal: '203.0000kcal'},
              {meal: '中餐', dish: '尖椒牛肉', weight: '100.0000g', kcal: '146.2800kcal'},
              {meal: '中餐', dish: '老黄瓜羊肉汤', weight: '240.0000g', kcal: '78.7800kcal'},
              {meal: '中餐', dish: '蕾蒿菜', weight: '50.0000g', kcal: '7.6960kcal'}
            ]
          },
          {
            id: 4,
            label: '东北地区夏季糖尿病食谱',
            detail: [
              // ... 其他食谱数据 ...
            ]
          },
          {
            id: 5,
            label: '东北地区春季糖尿病食谱',
            detail: [
              // ... 其他食谱数据 ...
            ]
          },
          {
            id: 6,
            label: '东北地区秋季糖尿病食谱',
            detail: [
              // ... 其他食谱数据 ...
            ]
          }
        ]
      },
      {
        id: 7,
        label: '减脂周食谱分类',
        children: [
          {
            id: 8,
            label: '中速食谱方案',
            detail: [
              // ... 其他食谱数据 ...
            ]
          },
          {
            id: 9,
            label: '低速食谱方案',
            detail: [
              // ... 其他食谱数据 ...
            ]
          }
        ]
      },
      {
        id: 10,
        label: '普食周食谱分类',
        children: [
          {
            id: 11,
            label: '低碳周食谱一',
            detail: [
              // ... 其他食谱数据 ...
            ]
          },
          {
            id: 12,
            label: '低蛋白周食谱一',
            detail: [
              // ... 其他食谱数据 ...
            ]
          },
          {
            id: 13,
            label: '无渣(少渣)食谱一',
            detail: [
              // ... 其他食谱数据 ...
            ]
          }
        ]
      }
    ]
  }
]);
const treeProps = {children: 'children', label: 'label'};
const treeRef = ref();

const selected = ref<any[]>([]);
const selectedDetail = ref<any[]>([]);

// 分组明细数据
const groupedDetail = computed(() => {
  if (activeTab.value === 'week') {
    const all = selectedDetail.value;
    if (!all.length) return [];

    // 按meal分组
    const groupMap: Record<string, {meal: string; kcalSum: number; rows: any[]}> = {};
    all.forEach((row) => {
      if (!groupMap[row.meal]) {
        groupMap[row.meal] = {meal: row.meal, kcalSum: 0, rows: []};
      }
      const kcal = parseFloat((row.kcal || '').replace(/[^\d.]/g, '')) || 0;
      groupMap[row.meal].kcalSum += kcal;
      groupMap[row.meal].rows.push(row);
    });

    // 展平成表格数据，插入分组行
    const result: any[] = [];
    Object.values(groupMap).forEach((group) => {
      result.push({_isGroup: true, meal: `${group.meal}`, kcalSum: group.kcalSum});
      result.push(...group.rows);
    });
    return result;
  } else {
    // 原有的日食谱数据处理逻辑
    const all = selectedDetail.value;
    if (!all.length) return [];
    const groupMap: Record<string, {meal: string; kcalSum: number; rows: any[]}> = {};
    all.forEach((row) => {
      if (!groupMap[row.meal]) {
        groupMap[row.meal] = {meal: row.meal, kcalSum: 0, rows: []};
      }
      const kcal = parseFloat((row.kcal || '').replace(/[^\d.]/g, '')) || 0;
      groupMap[row.meal].kcalSum += kcal;
      groupMap[row.meal].rows.push(row);
    });
    const result: any[] = [];
    Object.values(groupMap).forEach((group) => {
      result.push({_isGroup: true, meal: group.meal, kcalSum: group.kcalSum});
      result.push(...group.rows);
    });
    return result;
  }
});

function groupRowClassName({row}: any) {
  return row._isGroup ? 'group-row' : '';
}
function groupSpanMethod({row, column, rowIndex, columnIndex}: any) {
  if (row._isGroup) {
    if (columnIndex === 0) return [1, 4];
    return [0, 0];
  }
}

function updateSelectedLeafNodes() {
  const checkedNodes = treeRef.value?.getCheckedNodes(true) || [];
  selected.value = checkedNodes.filter((node: any) => !node.children || node.children.length === 0);
  selectedDetail.value = selected.value.flatMap((tpl) => tpl.detail || []);
}
function removeSelected(item: any) {
  treeRef.value?.setChecked(item, false, true);
  updateSelectedLeafNodes();
}
function openDialog() {
  dialogVisible.value = true;
  nextTick(() => updateSelectedLeafNodes());
}
function closeDialog() {
  dialogVisible.value = false;
}
function confirmDialog() {
  if (!selected.value.length) {
    ElMessage.warning('请选择食谱');
    return;
  }

  // 获取选中食谱的详细数据
  const selectedRecipeData = selected.value.map((recipe) => {
    const detail = recipe.detail || [];
    return {
      name: recipe.label,
      meals: detail.map((item) => ({
        meal: item.meal,
        dish: item.dish,
        weight: item.weight,
        kcal: item.kcal
      }))
    };
  });

  emit('confirm', selectedRecipeData);
  dialogVisible.value = false;
  selected.value = [];
  selectedDetail.value = [];
}
defineExpose({openDialog, closeDialog});
</script>

<style lang="scss" scoped>
.recipe-template-dialog {
  background: #fff;
  display: flex;
  flex-direction: column;
  height: 600px;

  .header-bar {
    padding: 0 20px;
    .tabs {
      :deep(.el-tabs__nav) {
        width: 100%;
        display: flex;
        .el-tabs__item {
          flex: 1;
          text-align: center;
          font-size: 15px;
          height: 40px;
          line-height: 40px;
          &.is-active {
            font-weight: 500;
          }
        }
      }
    }
    .search-bar {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 12px 0;
      .search-input {
        flex: 1;
        :deep(.el-input__wrapper) {
          box-shadow: 0 0 0 1px #dcdfe6 inset;
          &:hover {
            box-shadow: 0 0 0 1px #c0c4cc inset;
          }
        }
      }
      .search-btn {
        min-width: 80px;
      }
    }
  }

  .main-content {
    display: flex;
    flex: 1;
    padding: 0 20px;
    min-height: 400px;
    gap: 20px;
    overflow: hidden;

    .left-panel {
      width: 360px;
      border-right: 1px solid #ebeef5;
      padding-right: 20px;
      .tree-block {
        :deep(.el-tree-node__content) {
          height: 32px;
          &:hover {
            background-color: #f5f7fa;
          }
          &.is-current {
            background-color: #ecf5ff;
            color: #409eff;
          }
        }
        :deep(.el-tree-node__children) {
          padding-left: 22px;
        }
        :deep(.el-checkbox__inner) {
          border-radius: 2px;
          &:hover {
            border-color: #409eff;
          }
        }
        :deep(.el-tree-node__expand-icon) {
          &.expanded {
            transform: rotate(90deg);
          }
          &.is-leaf {
            color: transparent;
          }
        }
      }
    }

    .right-content {
      flex: 1;
      display: flex;
      flex-direction: column;

      .week-tabs {
        margin-bottom: 16px;
        .recipe-tabs {
          :deep(.el-tabs__nav) {
            background-color: #f5f7fa;
            padding: 4px;
            border-radius: 4px;
            .el-tabs__item {
              padding: 0 20px;
              height: 32px;
              line-height: 32px;
              border-radius: 4px;
              &.is-active {
                background-color: #fff;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
              }
            }
          }
        }
      }

      .detail-table {
        :deep(.el-table__inner-wrapper) {
          &::before {
            display: none;
          }
        }
        :deep(.group-row) {
          background: #f5f7fa;
          td {
            background: #f5f7fa !important;
            padding: 8px 0;
            border-bottom: 1px solid #ebeef5;

            .group-header {
              display: flex;
              align-items: center;
              justify-content: space-between;
              padding: 0 20px;
              height: 40px;

              .meal-name {
                font-size: 14px;
                font-weight: 500;
                color: #333;
              }

              .total-kcal {
                font-size: 14px;
                color: #333;
              }
            }
          }
        }
        :deep(.content-row) {
          td {
            height: 40px;
            padding: 8px 20px;
            color: #606266;
            font-size: 14px;
            border-bottom: 1px solid #ebeef5;
            background: #fff !important;
          }
          &:hover > td {
            background-color: #f5f7fa !important;
          }
        }
        :deep(.el-table__row) {
          td {
            transition: background-color 0.25s ease;
          }
        }
      }
    }
  }

  .selected-bar {
    flex: none;
    min-height: 32px;
    border-top: 1px solid #ebeef5;
    margin-top: 12px;
    padding: 12px 20px;
    display: flex;
    align-items: flex-start;
    gap: 8px;
    > span {
      color: #606266;
      line-height: 24px;
    }
    .selected-tags {
      flex: 1;
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      :deep(.el-tag) {
        margin: 0;
        border-radius: 2px;
        .el-tag__close {
          color: #909399;
          &:hover {
            color: #409eff;
            background-color: transparent;
          }
        }
      }
    }
  }

  :deep(.el-scrollbar) {
    height: 100%;
    .el-scrollbar__wrap {
      overflow-x: hidden;
    }
    .el-scrollbar__bar {
      &.is-horizontal {
        display: none;
      }
    }
  }
}

:deep(.el-dialog) {
  margin-top: 8vh !important;
  .el-dialog__header {
    margin: 0;
    padding: 16px 20px;
    border-bottom: 1px solid #ebeef5;
    .el-dialog__title {
      font-size: 16px;
      font-weight: 500;
    }
  }
  .el-dialog__body {
    padding: 0;
  }
  .el-dialog__footer {
    border-top: 1px solid #ebeef5;
    padding: 12px 20px;
  }
}
</style>
