<template>
  <div class="container">
    <div class="header-bar">
      <el-button @click="goBack" type="primary" plain class="back-btn">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
      <span class="title">智能推荐</span>
    </div>

    <!-- 基本信息 -->
    <el-card class="content-card">
      <div class="card-title">基本信息</div>
      <div class="form-content">
        <div class="diet-type">
          <span class="required">基本膳食</span>
          <el-checkbox-group :model-value="dietTypes">
            <el-checkbox v-for="item in dietOptions" :key="item" :label="item" @click="(e) => onDietTypesChange(item, e)">
              {{ item }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
        <div class="forbidden-food">
          <span>禁忌食材</span>
          <div class="food-select" @click="openFoodDialog">
            <div v-if="forbiddenFoods" class="selected-foods">
              <el-tag v-for="food in forbiddenFoods.split(',')" :key="food" size="small" closable @close="removeForbiddenFood(food)">
                {{ food }}
              </el-tag>
            </div>
            <div v-else class="placeholder">请选择</div>
            <el-icon class="select-icon"><ArrowDown /></el-icon>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 热量计算 -->
    <el-card class="content-card">
      <div class="card-title">热量计算</div>
      <div class="form-content">
        <div class="form-row">
          <div class="form-item">
            <span class="required">身高</span>
            <div class="input-with-unit">
              <el-input v-model="height" placeholder="请输入" />
              <span class="unit">cm</span>
            </div>
          </div>
          <div class="form-item">
            <span class="required">体重</span>
            <div class="input-with-unit">
              <el-input v-model="weight" placeholder="请输入" />
              <span class="unit">kg</span>
            </div>
          </div>
          <div class="form-item">
            <span>理想体重：</span>
            <span class="value">{{ idealWeight }}kg</span>
          </div>
        </div>

        <div class="form-row">
          <div class="form-item physical-activity">
            <span class="required">体力活动</span>
            <el-radio-group :model-value="activityLevel">
              <el-radio label="静养活动" @click="(e) => onActivityLevelChange('静养活动', e)">静养活动</el-radio>
              <el-radio label="轻体力活动" @click="(e) => onActivityLevelChange('轻体力活动', e)">轻体力活动</el-radio>
              <el-radio label="中体力活动" @click="(e) => onActivityLevelChange('中体力活动', e)">中体力活动</el-radio>
              <el-radio label="重体力活动" @click="(e) => onActivityLevelChange('重体力活动', e)">重体力活动</el-radio>
            </el-radio-group>
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <span class="required">热量</span>
            <el-input v-model="calories" placeholder="请输入" style="width: 120px" />
            <span class="unit">kcal/(kg*d)</span>
          </div>
          <div class="form-item">
            <span>参考范围</span>
            <el-icon class="info-icon"><QuestionFilled /></el-icon>
          </div>
          <div class="form-item">
            <span>总热量</span>
            <span class="value">{{ totalCalories }} kcal/d</span>
          </div>
          <div class="form-item">
            <span>体质指标（BMI）：</span>
            <span class="value">{{ bmi }}</span>
            <span class="status" :style="{color: bmiColor}">正常</span>
          </div>
          <div class="form-item bmi-slider">
            <el-slider
              v-model="bmiValue"
              :min="18.5"
              :max="23.9"
              :step="0.1"
              :show-tooltip="false"
              :marks="{
                18.5: '18.5',
                23.9: '23.9'
              }"
              style="width: 160px"
            />
            <div class="bmi-status-text">
              <span>20.20(正常)</span>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 比例设置 -->
    <el-card class="content-card">
      <div class="card-title">比例设置</div>
      <div class="form-content">
        <div class="ratio-section">
          <div class="ratio-header">
            <span>各餐比例：</span>
            <el-progress :stroke-width="10" :percentage="100" :format="() => '100.00%'" :color="'#00B42A'" :striped="true" :striped-flow="true" />
          </div>

          <div class="meal-ratios">
            <div class="ratio-items">
              <div class="ratio-item">
                <span>早餐</span>
                <div class="input-with-unit">
                  <el-input v-model="breakfast" style="width: 120px" />
                  <span class="unit">%</span>
                </div>
              </div>
              <div class="ratio-item">
                <span>早加</span>
                <div class="input-with-unit">
                  <el-input v-model="morningSnack" style="width: 120px" />
                  <span class="unit">%</span>
                </div>
              </div>
              <div class="ratio-item">
                <span>中餐</span>
                <div class="input-with-unit">
                  <el-input v-model="lunch" style="width: 120px" />
                  <span class="unit">%</span>
                </div>
              </div>
              <div class="ratio-item">
                <span>中加</span>
                <div class="input-with-unit">
                  <el-input v-model="afternoonSnack" style="width: 120px" />
                  <span class="unit">%</span>
                </div>
              </div>
              <div class="ratio-item">
                <span>晚餐</span>
                <div class="input-with-unit">
                  <el-input v-model="dinner" style="width: 120px" />
                  <span class="unit">%</span>
                </div>
              </div>
              <div class="ratio-item">
                <span>晚加</span>
                <div class="input-with-unit">
                  <el-input v-model="eveningSnack" style="width: 120px" />
                  <span class="unit">%</span>
                </div>
              </div>
            </div>
          </div>

          <div class="nutrition-ratio">
            <span>三大营养素供能比：</span>
            <el-progress :stroke-width="10" :percentage="95" :format="() => '95%'" :color="'#00B42A'" :striped="true" :striped-flow="true" />
          </div>

          <div class="nutrition-ratios">
            <div class="ratio-item">
              <span>碳水化合物</span>
              <div class="input-with-unit">
                <el-input v-model="carbs" style="width: 120px" />
                <span class="unit">%</span>
              </div>
            </div>
            <div class="ratio-item">
              <span>蛋白质</span>
              <div class="input-with-unit">
                <el-input v-model="protein" style="width: 120px" />
                <span class="unit">%</span>
              </div>
            </div>
            <div class="ratio-item">
              <span>脂肪</span>
              <div class="input-with-unit">
                <el-input v-model="fat" style="width: 120px" />
                <span class="unit">%</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 底部按钮 -->
    <div class="bottom-btn-card">
      <div class="btn-wrapper">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleGenerate">生成推荐方案</el-button>
      </div>
    </div>

    <!-- 添加食材选择弹窗 -->
    <common-dialog ref="foodDialogRef" type="food" title="添加食材" @confirm="handleFoodConfirm" @cancel="handleFoodCancel" />
  </div>
</template>

<script setup lang="ts">
import {ref, computed} from 'vue';
import {ArrowLeft, CircleCheck, QuestionFilled, ArrowDown} from '@element-plus/icons-vue';
import CommonDialog from './components/CommonDialog.vue';

// 基本信息
const dietTypes = ref<string[]>(['普食']); // 确保是数组类型
const dietOptions = ['普食', '软食', '半流食', '流食'];
const forbiddenFoods = ref('');

const foodDialogRef = ref();

// 打开食材选择弹窗
const openFoodDialog = () => {
  // 将当前已选择的食材传入
  const currentFoods = forbiddenFoods.value ? forbiddenFoods.value.split(',').map((name) => ({name: name.trim()})) : [];
  foodDialogRef.value?.openDialog('food', currentFoods);
};

// 处理食材选择确认
const handleFoodConfirm = (selectedFoods: any[]) => {
  forbiddenFoods.value = selectedFoods.map((item) => item.name).join(',');
};

// 处理食材选择取消
const handleFoodCancel = () => {
  console.log('取消选择食材');
};

// 移除禁忌食材
const removeForbiddenFood = (food: string) => {
  const foods = forbiddenFoods.value.split(',');
  forbiddenFoods.value = foods.filter((f) => f !== food).join(',');
};

// 热量计算
const height = ref('165.00');
const weight = ref('55.00');
const idealWeight = ref(60);
const activityLevel = ref('静养活动');
const calories = ref('15.00');
const totalCalories = computed(() => {
  const cal = parseFloat(calories.value) || 0;
  const w = parseFloat(weight.value) || 0;
  return (cal * w).toFixed(2);
});

// BMI计算
const bmi = computed(() => {
  const h = parseFloat(height.value) || 0;
  const w = parseFloat(weight.value) || 0;
  if (!h || !w) return '0.00';
  return (w / Math.pow(h / 100, 2)).toFixed(2);
});

const bmiStatus = computed(() => {
  const bmiValue = parseFloat(bmi.value);
  if (bmiValue < 18.5) return '偏瘦';
  if (bmiValue <= 23.9) return '正常';
  return '偏胖';
});

const bmiPercentage = computed(() => {
  const bmiValue = parseFloat(bmi.value);
  return Math.min(Math.max(((bmiValue - 18.5) / (23.9 - 18.5)) * 100, 0), 100);
});

const bmiColor = computed(() => {
  const bmiValue = parseFloat(bmi.value);
  if (bmiValue < 18.5) return '#FF9900';
  if (bmiValue <= 23.9) return '#00B42A';
  return '#FF3A00';
});

// 比例设置
const breakfast = ref('30.00');
const morningSnack = ref('0.00');
const lunch = ref('40.00');
const afternoonSnack = ref('0.00');
const dinner = ref('30.00');
const eveningSnack = ref('0.00');

// 营养素比例
const carbs = ref('50.00');
const protein = ref('15.00');
const fat = ref('30.00');

const bmiValue = ref(20.2);

const emit = defineEmits(['goBack']);
// 返回上一页
const goBack = () => {
  emit('goBack');
};

const onDietTypesChange = (item: string, e: Event) => {
  e.stopPropagation();
  e.preventDefault();
  const newVals = toRaw(dietTypes.value);
  if (newVals.includes(item)) {
    newVals.splice(newVals.indexOf(item), 1);
  } else {
    newVals.push(item);
  }
  dietTypes.value = [...new Set(newVals)];
};

const onActivityLevelChange = (val: string, e: Event) => {
  e.stopPropagation();
  e.preventDefault();
  activityLevel.value = val;
};

// 按钮处理函数
const handleCancel = () => {
  // 取消操作
  goBack();
};

const handleGenerate = () => {
  // 生成推荐方案
  console.log('生成推荐方案');
};
</script>

<style lang="scss" scoped>
.container {
  padding-bottom: 76px;
}

.header-bar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;

  .back-btn {
    margin-right: 16px;
    display: flex;
    align-items: center;
    .el-icon {
      margin-right: 4px;
    }
  }

  .title {
    font-size: 20px;
    font-weight: 600;
  }
}

.content-card {
  margin-bottom: 16px;

  .card-title {
    font-size: 16px;
    font-weight: 600;
    color: #1d2129;
    margin-bottom: 16px;
    position: relative;
    padding-left: 12px;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 16px;
      background-color: #165dff;
      border-radius: 2px;
    }
  }

  .form-content {
    padding: 0 12px;

    .form-row {
      display: flex;
      align-items: center;
      margin-bottom: 24px;
      gap: 32px;

      &:last-child {
        margin-bottom: 0;
      }

      .form-item {
        display: flex;
        align-items: center;
        gap: 8px;

        &:not(.physical-activity) {
          min-width: auto;
        }

        .input-with-unit {
          display: flex;
          align-items: center;
          gap: 8px;

          .el-input {
            width: 160px;
          }

          .unit {
            color: #4e5969;
            font-size: 14px;
            white-space: nowrap;
          }
        }

        .value {
          color: #1d2129;
          font-weight: 600;
        }

        .info-icon {
          color: #86909c;
          cursor: pointer;
        }

        .bmi-status {
          font-size: 14px;
        }
      }
    }
  }
}

.diet-type {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 16px;

  :deep(.el-checkbox-group) {
    display: flex;
    gap: 24px;
  }

  :deep(.el-checkbox) {
    margin-right: 0;
    height: 32px;

    .el-checkbox__label {
      font-size: 14px;
      color: #4e5969;
    }

    .el-checkbox__input {
      &.is-checked {
        .el-checkbox__inner {
          background-color: #409eff;
          border-color: #409eff;
        }
      }

      .el-checkbox__inner {
        &:hover {
          border-color: #409eff;
        }
      }
    }

    &:hover {
      .el-checkbox__label {
        color: #409eff;
      }
    }
  }
}

.forbidden-food {
  display: flex;
  align-items: flex-start;
  gap: 16px;

  span {
    min-width: 70px;
    line-height: 32px;
  }

  .food-select {
    flex: 1;
    min-height: 32px;
    padding: 4px 30px 4px 12px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    cursor: pointer;
    position: relative;
    background-color: #fff;

    &:hover {
      border-color: #409eff;
    }

    .selected-foods {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }

    .placeholder {
      color: #909399;
      line-height: 24px;
    }

    .select-icon {
      position: absolute;
      right: 8px;
      top: 50%;
      transform: translateY(-50%);
      font-size: 14px;
      color: #c0c4cc;
    }
  }
}

.form-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;

  .input-with-unit {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .unit {
    color: #4e5969;
    font-size: 14px;
  }

  .value {
    color: #1d2129;
    font-weight: 600;
  }

  .info-icon {
    color: #86909c;
    cursor: pointer;
  }
}

.required {
  position: relative;
  padding-left: 8px;

  &::before {
    content: '*';
    color: #ff3a00;
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
  }
}

.physical-activity {
  width: 100%;

  :deep(.el-radio-group) {
    display: flex;
    gap: 32px;
  }

  :deep(.el-radio) {
    margin-right: 0;
    height: 32px;
    .el-radio__label {
      font-size: 14px;
      color: #4e5969;
    }
  }
}

.calorie-info {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  gap: 32px;
  margin-bottom: 16px;

  .info-item {
    display: flex;
    align-items: center;
    gap: 8px;
    white-space: nowrap;
    color: #4e5969;
    font-size: 14px;

    .required {
      position: relative;
      padding-left: 8px;

      &::before {
        content: '*';
        color: #ff3a00;
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
      }
    }

    .unit {
      color: #4e5969;
    }

    .value {
      color: #1d2129;
      font-weight: 600;
    }

    .info-icon {
      color: #86909c;
      cursor: pointer;
    }

    .status {
      color: #00b42a;
    }
  }
}

.bmi-info {
  width: 600px;
  margin: 0 auto;

  .bmi-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;

    .value {
      color: #1d2129;
      font-weight: 600;
    }

    .bmi-status {
      font-size: 14px;
    }
  }

  .bmi-progress {
    margin-bottom: 4px;

    :deep(.el-progress) {
      .el-progress-bar__outer {
        background-color: #e5e6eb;
        height: 8px;
        border-radius: 4px;
      }
    }

    .bmi-range {
      display: flex;
      justify-content: space-between;
      color: #86909c;
      font-size: 13px;
      margin-top: 4px;
    }
  }

  .bmi-status-text {
    display: flex;
    align-items: center;
    gap: 4px;
    color: #00b42a;
    font-size: 13px;
    justify-content: flex-end;
  }
}

.total-ratio,
.nutrition-ratio {
  margin-bottom: 24px;

  :deep(.el-progress) {
    margin-top: 8px;
    .el-progress-bar__outer {
      background-color: #e5e6eb;
      height: 8px;
    }
  }
}

.ratio-section {
  .ratio-header {
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    gap: 8px;

    span {
      color: #1d2129;
      white-space: nowrap;
    }

    :deep(.el-progress) {
      width: 240px;
      .el-progress-bar__outer {
        background-color: #e5e6eb;
        height: 10px;
        border-radius: 20px;
      }
      .el-progress-bar__inner {
        border-radius: 20px;
        background-color: rgb(28, 202, 141) !important;
      }
      .el-progress__text {
        font-size: 13px !important;
        color: #fff;
        margin-left: 4px;
        background: #2cda9b;
        padding: 2px 8px;
        border-radius: 10px;
      }
    }
  }

  .meal-ratios {
    margin-bottom: 24px;

    .ratio-items {
      display: flex;
      flex-wrap: nowrap;
      gap: 16px;
      align-items: flex-start;
    }

    .ratio-item {
      display: flex;
      flex-direction: column;
      gap: 8px;
      flex: 0 0 auto;

      span {
        color: #4e5969;
        font-size: 14px;
      }

      .input-with-unit {
        display: flex;
        align-items: center;
        gap: 8px;

        .el-input {
          width: 120px;
        }

        .unit {
          color: #4e5969;
          font-size: 14px;
        }
      }
    }
  }

  .nutrition-ratio {
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    gap: 8px;

    span {
      color: #1d2129;
      white-space: nowrap;
    }

    :deep(.el-progress) {
      width: 240px;
      .el-progress-bar__outer {
        background-color: #e5e6eb;
        height: 10px;
        border-radius: 20px;
      }
      .el-progress-bar__inner {
        border-radius: 20px;
        background-color: rgb(28, 202, 141) !important;
      }
      .el-progress__text {
        font-size: 13px !important;
        color: #fff;
        margin-left: 4px;
        background: #2cda9b;
        padding: 2px 8px;
        border-radius: 10px;
      }
    }
  }

  .nutrition-ratios {
    display: flex;
    gap: 80px;
  }
}

.bottom-btn-card {
  position: fixed;
  left: 228px;
  right: 0;
  bottom: 50px;
  padding: 8px 16px;
  background: #fff;
  box-shadow: 0 -2px 8px rgba(64, 158, 255, 0.08);
  z-index: 2000;

  .btn-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 16px;

    .el-button {
      min-width: 120px;
      height: 44px;
      padding: 0 24px;
    }
  }
}

.food-dialog-content {
  .search-bar {
    margin-bottom: 16px;

    .el-input {
      width: 100%;
    }
  }

  .food-select-container {
    display: flex;
    gap: 16px;
    min-height: 400px;
    margin-bottom: 16px;

    .food-categories {
      width: 200px;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      overflow-y: auto;
    }

    .food-list {
      flex: 1;
      display: flex;
      flex-direction: column;

      :deep(.el-table) {
        flex: 1;

        .selected-row {
          background-color: #f0f7ff;
        }
      }

      .pagination {
        margin-top: 16px;
        display: flex;
        justify-content: flex-end;
      }
    }
  }

  .selected-tags {
    border-top: 1px solid #e4e7ed;
    padding-top: 16px;
    min-height: 32px;

    .selected-title {
      color: #606266;
      margin-bottom: 8px;
    }

    .tags-container {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .selected-tag {
        margin-right: 8px;
        margin-bottom: 8px;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
}
</style>
