<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--树数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <div style="width: 96%;display: flex;align-items: center;justify-content: space-between;">
            <span>营养信息分类</span>
            <span style="font-size: 24px;font-weight: 600;cursor: pointer;" @click.stop="() => appendTreeNode()">+</span>
          </div>
          <el-input
            v-model="keyWord"
            placeholder="请输入关键字进行搜索"
            clearable
            maxlength="50"
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>

        <div class="head-container">
          <el-tree style="height: 700px;overflow: scroll;"
            :data="cascaderOptions" :props="defaultProps"
            :show-checkbox="true" :default-expand-all="true"
            :expand-on-click-node="false" :filter-node-method="filterNode"
            ref="nutritionTypeTree" node-key="id" highlight-current @node-click="handleNodeClick" @check-change="handleCheckChange"
          >
              <span class="custom-tree-node" slot-scope="{ node, data }" @mousemove="onMousemove(data)" @mouseleave="onMouseleave()">
                <span v-if="isMousemoveId === data.id && node.label.length > 5">{{
                    node.label.slice(0, 5) + "..."
                  }}</span>
                <span v-else>{{ node.label }}</span>

                <span class="btn-items" v-if="isMousemoveId === data.id">
                  <el-button
                    type="text"
                    size="mini"
                    icon="el-icon-plus" v-if="data.level<1"
                    @click.stop="() => appendTreeNode(data)"
                  >
                  </el-button>
                  <el-button
                    type="text"
                    size="mini"
                    icon="el-icon-edit-outline"
                    style="color: #67c23a"
                    @click.stop="() => editTreeNode(data)"
                  >
                  </el-button>
                  <el-button
                    type="text"
                    size="mini"
                    icon="el-icon-delete"
                    style="color: #f56c6c" v-if="!data.children||data.children.length==0"
                    @click.stop="() => removeTreeNode(data)"
                  >
                  </el-button>
                </span>
              </span>
          </el-tree>
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="98px">   
          <el-form-item label="营养信息名称" prop="nutritionName">
            <el-input
              v-model="queryParams.nutritionName"
              placeholder="请输入营养信息名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['dish:nutritionInfo:add']"
            >新增</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="menuNutritionList" height="650"> 
          <el-table-column label="序号" align="center" width="80" type="index">
                <template slot-scope="scope">
                    <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
                </template>
          </el-table-column>
          <el-table-column label="食材编码" align="center" prop="nutritionCode" />
          <el-table-column label="食材大类" align="center" prop="bigTypeName" />
          <el-table-column label="食材小类" align="center" prop="smallTypeName" />
          <el-table-column label="营养信息名称" align="center" prop="nutritionName" /> 
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['dish:nutritionInfo:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['dish:nutritionInfo:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>




    <!-- 添加或修改类别对话框 -->
    <el-dialog :title="title+'-营养信息类别'" :visible.sync="openType" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="typeForm" :model="typeForm" :rules="typeRules" label-width="120px">
        <el-form-item label="父节点名称" prop="parentName" v-if="typeForm.parentName">
          <el-input v-model="typeForm.parentName" placeholder="请输入父节点名称" maxlength="30" disabled/>
        </el-form-item>  
        <el-form-item label="类别名称" prop="nutritionTypeName">
          <el-input v-model="typeForm.nutritionTypeName" placeholder="请输入类别名称" maxlength="15"/>
        </el-form-item> 
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="openType=false">取 消</el-button>
      </div>
    </el-dialog>
    

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title+'-营养信息'" :visible.sync="open" width="1330px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="180px"> 
        <el-row>
          <el-col :span="12">
            <el-form-item label="营养信息类别" prop="nutritionTypeId">
              <el-cascader
                v-model="form.nutritionTypeId"
                :options="cascaderOptions"
                :props="{  
                  emitPath: false,// 若设置 false，则只返回该节点的值，只返回最后选择的id
                  checkStrictly: false,//来设置父子节点取消选中关联，从而达到选择任意一级选项的目的
                  value:'id',label:'label'
                }"
                placeholder="请选择营养信息类别"
                clearable  @change="chosenType"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="营养信息名称" prop="nutritionName">
              <el-input
                v-model="form.nutritionName"
                placeholder="请输入营养信息名称"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="食材编码" prop="nutritionCode">
              <el-input
                v-model="form.nutritionCode"
                placeholder="请输入食材编码"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <div style="font-size: 18px;font-weight: bold;margin-bottom: 20px;">
          营养信息
        </div> 
        <el-row>
          <el-col :span="24">
            <el-table :data="formTable"  size="mini" >
              <el-table-column label="加工时间（min）" prop="processingTime" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.processingTime"
                        @input="handleNumericInput('processingTime', $event)"
                        @blur="formatNumericValue('processingTime')"
                        placeholder="请输入加工时间"
                      ></el-input> 
                    </template>
              </el-table-column>
              <el-table-column label="可食部分(g/100g)" prop="edible" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.edible"
                        @input="handleNumericInput('edible', $event)"
                        @blur="formatNumericValue('edible')"
                        placeholder="请输入可食部分"
                      ></el-input>
                    </template>
              </el-table-column>
              <el-table-column label="水分(g/100g)" prop="water" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.water"
                        @input="handleNumericInput('water', $event)"
                        @blur="formatNumericValue('water')"
                        placeholder="请输入水分"
                      ></el-input>
                    </template>
              </el-table-column>
              <el-table-column label="热量（千卡/100g）" prop="calories" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.calories"
                        @input="handleNumericInput('calories', $event)"
                        @blur="formatNumericValue('calories')"
                        placeholder="请输入热量"
                      ></el-input>
                    </template>
              </el-table-column>
              <el-table-column label="蛋白质(g/100g)" prop="protein" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.protein"
                        @input="handleNumericInput('protein', $event)"
                        @blur="formatNumericValue('protein')"
                        placeholder="请输入蛋白质"
                      ></el-input>
                    </template>
              </el-table-column>
              <el-table-column label="脂肪(g/100g)" prop="fat" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.fat"
                        @input="handleNumericInput('fat', $event)"
                        @blur="formatNumericValue('fat')"
                        placeholder="请输入脂肪"
                      ></el-input>
                    </template>
              </el-table-column> 
              <el-table-column label="碳水化合物(g/100g)" prop="carbohydrate" align="center" width="150">
                    <template slot-scope="scope">
                      <el-input
                          v-model="scope.row.carbohydrate"
                          @input="handleNumericInput('carbohydrate', $event)"
                          @blur="formatNumericValue('carbohydrate')"
                          placeholder="请输入碳水化合物"
                      ></el-input>
                    </template>
              </el-table-column>
              <el-table-column label="膳食纤维(g/100g)" prop="dietaryFiber" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.dietaryFiber"
                        @input="handleNumericInput('dietaryFiber', $event)"
                        @blur="formatNumericValue('dietaryFiber')"
                        placeholder="请输入膳食纤维"
                      ></el-input>
                    </template>
              </el-table-column> 
              <el-table-column label="胆固醇(mg/100g)" prop="cholesterol" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.cholesterol"
                        @input="handleNumericInput('cholesterol', $event)"
                        @blur="formatNumericValue('cholesterol')"
                        placeholder="请输入胆固醇"
                      ></el-input>
                    </template>
              </el-table-column> 
            </el-table>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-table :data="formTable"  size="mini" > 
              <el-table-column label="灰分(g/100g)" prop="ash" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.ash"
                        @input="handleNumericInput('ash', $event)"
                        @blur="formatNumericValue('ash')"
                        placeholder="请输入灰分"
                      ></el-input>
                    </template>
              </el-table-column>
              <el-table-column label="维生素A(μg/100g)" prop="vitaminA" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.vitaminA"
                        @input="handleNumericInput('vitaminA', $event)"
                        @blur="formatNumericValue('vitaminA')"
                        placeholder="请输入维生素A"
                      ></el-input>
                    </template>
              </el-table-column>
              <el-table-column label="胡萝卜素(μg/100g)" prop="carotene" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.carotene"
                        @input="handleNumericInput('carotene', $event)"
                        @blur="formatNumericValue('carotene')"
                        placeholder="请输入胡萝卜素"
                      ></el-input>
                    </template>
              </el-table-column>
              <el-table-column label="视黄醇(μg/100g)" prop="retinol" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.retinol"
                        @input="handleNumericInput('retinol', $event)"
                        @blur="formatNumericValue('retinol')"
                        placeholder="请输入视黄醇"
                      ></el-input>
                    </template>
              </el-table-column>
              <el-table-column label="硫胺素(mg/100g)" prop="thiamine" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.thiamine"
                        @input="handleNumericInput('thiamine', $event)"
                        @blur="formatNumericValue('thiamine')"
                        placeholder="请输入硫胺素"
                      ></el-input>
                    </template>
              </el-table-column>
              <el-table-column label="核黄素(mg/100g)" prop="riboflavin" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.riboflavin"
                        @input="handleNumericInput('riboflavin', $event)"
                        @blur="formatNumericValue('riboflavin')"
                        placeholder="请输入核黄素"
                      ></el-input>
                      
                    </template>
              </el-table-column>
              <el-table-column label="烟酸/尼克酸(mg/100g)" prop="niacin" align="center" width="150">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.niacin"
                        @input="handleNumericInput('niacin', $event)"
                        @blur="formatNumericValue('niacin')"
                        placeholder="请输入烟酸/尼克酸"
                      ></el-input>
                    </template>
              </el-table-column>
              <el-table-column label="维生素C(mg/100g)" prop="vitaminC" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.vitaminC"
                        @input="handleNumericInput('vitaminC', $event)"
                        @blur="formatNumericValue('vitaminC')"
                        placeholder="请输入维生素C"
                      ></el-input>
                    </template>
              </el-table-column>
              <el-table-column label="维生素D(μg/100g)" prop="vitaminD" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.vitaminD"
                        @input="handleNumericInput('vitaminD', $event)"
                        @blur="formatNumericValue('vitaminD')"
                        placeholder="请输入维生素D"
                      ></el-input>
                    </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-table :data="formTable"  size="mini" > 
              <el-table-column label="维生素E(mg/100g)" prop="vitaminE" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.vitaminE"
                        @input="handleNumericInput('vitaminE', $event)"
                        @blur="formatNumericValue('vitaminE')"
                        placeholder="请输入维生素E"
                      ></el-input>
                    </template>
              </el-table-column>
              <el-table-column label="钙(mg/100g)" prop="calcium" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.calcium"
                        @input="handleNumericInput('calcium', $event)"
                        @blur="formatNumericValue('calcium')"
                        placeholder="请输入钙"
                      ></el-input>
                    </template>
              </el-table-column>
              <el-table-column label="磷(mg/100g)" prop="phosphorus" align="center" width="140">
                    <template slot-scope="scope">
                       <el-input
                        v-model="scope.row.phosphorus"
                        @input="handleNumericInput('phosphorus', $event)"
                        @blur="formatNumericValue('phosphorus')"
                        placeholder="请输入磷"
                      ></el-input>
                    </template>
              </el-table-column>
              <el-table-column label="钾(mg/100g)" prop="kalium" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.kalium"
                        @input="handleNumericInput('kalium', $event)"
                        @blur="formatNumericValue('kalium')"
                        placeholder="请输入钾"
                      ></el-input>
                    </template>
              </el-table-column>
              <el-table-column label="钠 (mg/100g)" prop="sodium" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.sodium"
                        @input="handleNumericInput('sodium', $event)"
                        @blur="formatNumericValue('sodium')"
                        placeholder="请输入钠"
                      ></el-input>
                    </template>
              </el-table-column>
              <el-table-column label="镁(mg/100g)" prop="magnesium" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.magnesium"
                        @input="handleNumericInput('magnesium', $event)"
                        @blur="formatNumericValue('magnesium')"
                        placeholder="请输入镁"
                      ></el-input>
                    </template>
              </el-table-column>
              <el-table-column label="铁 (mg/100g)" prop="iron" align="center" width="150">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.iron"
                        @input="handleNumericInput('iron', $event)"
                        @blur="formatNumericValue('iron')"
                        placeholder="请输入铁"
                      ></el-input>
                    </template>
              </el-table-column>
              <el-table-column label="锌(mg/100g)" prop="zinc" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.zinc"
                        @input="handleNumericInput('zinc', $event)"
                        @blur="formatNumericValue('zinc')"
                        placeholder="请输入锌"
                      ></el-input>
                    </template>
              </el-table-column>
              <el-table-column label="硒(μg/100g)" prop="selenium" align="center" width="140">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.selenium"
                        @input="handleNumericInput('selenium', $event)"
                        @blur="formatNumericValue('selenium')"
                        placeholder="请输入硒"
                      ></el-input>
                    </template>
              </el-table-column> 
            </el-table>
          </el-col>
        </el-row> 
        <!-- <el-row>
          <el-col :span="12">
            <el-form-item label="加工时间（min）">
              <el-input
                v-model="form.processingTime"
                @input="handleNumericInput('processingTime', $event)"
                @blur="formatNumericValue('processingTime')"
                placeholder="请输入加工时间"
              ></el-input>
            </el-form-item>
          </el-col> 
          <el-col :span="12">
            <el-form-item label="可食部分(g/100g)" prop="edible">
              <el-input
                v-model="form.edible"
                @input="handleNumericInput('edible', $event)"
                @blur="formatNumericValue('edible')"
                placeholder="请输入可食部分"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row> 
        <el-row>
          <el-col :span="12">
            <el-form-item label="水分(g/100g)" prop="water">
              <el-input
                v-model="form.water"
                @input="handleNumericInput('water', $event)"
                @blur="formatNumericValue('water')"
                placeholder="请输入水分"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="热量（千卡/100g）" prop="calories">
              <el-input
                v-model="form.calories"
                @input="handleNumericInput('calories', $event)"
                @blur="formatNumericValue('calories')"
                placeholder="请输入热量"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row> 
        <el-row>
          <el-col :span="12">
            <el-form-item label="蛋白质(g/100g)" prop="protein">
              <el-input
                v-model="form.protein"
                @input="handleNumericInput('protein', $event)"
                @blur="formatNumericValue('protein')"
                placeholder="请输入蛋白质"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="脂肪(g/100g)" prop="fat">
              <el-input
                v-model="form.fat"
                @input="handleNumericInput('fat', $event)"
                @blur="formatNumericValue('fat')"
                placeholder="请输入脂肪"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row> 
        <el-row>
          <el-col :span="12">
            <el-form-item label="碳水化合物(g/100g)" prop="carbohydrate">
              <el-input
                v-model="form.carbohydrate"
                @input="handleNumericInput('carbohydrate', $event)"
                @blur="formatNumericValue('carbohydrate')"
                placeholder="请输入碳水化合物"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="膳食纤维(g/100g)" prop="dietaryFiber">
              <el-input
                v-model="form.dietaryFiber"
                @input="handleNumericInput('dietaryFiber', $event)"
                @blur="formatNumericValue('dietaryFiber')"
                placeholder="请输入膳食纤维"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row> 
        <el-row>
          <el-col :span="12">
            <el-form-item label="胆固醇(mg/100g)" prop="cholesterol">
              <el-input
                v-model="form.cholesterol"
                @input="handleNumericInput('cholesterol', $event)"
                @blur="formatNumericValue('cholesterol')"
                placeholder="请输入胆固醇"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="灰分(g/100g)" prop="ash">
              <el-input
                v-model="form.ash"
                @input="handleNumericInput('ash', $event)"
                @blur="formatNumericValue('ash')"
                placeholder="请输入灰分"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row> 
        <el-row>
          <el-col :span="12">
            <el-form-item label="维生素A(μg/100g)" prop="vitaminA">
              <el-input
                v-model="form.vitaminA"
                @input="handleNumericInput('vitaminA', $event)"
                @blur="formatNumericValue('vitaminA')"
                placeholder="请输入维生素A"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="胡萝卜素(μg/100g)" prop="carotene">
              <el-input
                v-model="form.carotene"
                @input="handleNumericInput('carotene', $event)"
                @blur="formatNumericValue('carotene')"
                placeholder="请输入胡萝卜素"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row> 
        <el-row>
          <el-col :span="12">
            <el-form-item label="视黄醇(μg/100g)" prop="retinol">
              <el-input
                v-model="form.retinol"
                @input="handleNumericInput('retinol', $event)"
                @blur="formatNumericValue('retinol')"
                placeholder="请输入视黄醇"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="硫胺素(mg/100g)" prop="thiamine">
              <el-input
                v-model="form.thiamine"
                @input="handleNumericInput('thiamine', $event)"
                @blur="formatNumericValue('thiamine')"
                placeholder="请输入硫胺素"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row> 
        <el-row>
          <el-col :span="12">
            <el-form-item label="核黄素(mg/100g)" prop="riboflavin">
              <el-input
                v-model="form.riboflavin"
                @input="handleNumericInput('riboflavin', $event)"
                @blur="formatNumericValue('riboflavin')"
                placeholder="请输入核黄素"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="烟酸/尼克酸(mg/100g)" prop="niacin">
              <el-input
                v-model="form.niacin"
                @input="handleNumericInput('niacin', $event)"
                @blur="formatNumericValue('niacin')"
                placeholder="请输入烟酸/尼克酸"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row> 
        <el-row>
          <el-col :span="12">
            <el-form-item label="维生素C(mg/100g)" prop="vitaminC">
              <el-input
                v-model="form.vitaminC"
                @input="handleNumericInput('vitaminC', $event)"
                @blur="formatNumericValue('vitaminC')"
                placeholder="请输入维生素C"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="维生素D(μg/100g)" prop="vitaminD">
              <el-input
                v-model="form.vitaminD"
                @input="handleNumericInput('vitaminD', $event)"
                @blur="formatNumericValue('vitaminD')"
                placeholder="请输入维生素D"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row> 
        <el-row>
          <el-col :span="12">
            <el-form-item label="维生素E(mg/100g)" prop="vitaminE">
              <el-input
                v-model="form.vitaminE"
                @input="handleNumericInput('vitaminE', $event)"
                @blur="formatNumericValue('vitaminE')"
                placeholder="请输入维生素E"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="钙(mg/100g)" prop="calcium">
              <el-input
                v-model="form.calcium"
                @input="handleNumericInput('calcium', $event)"
                @blur="formatNumericValue('calcium')"
                placeholder="请输入钙"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row> 
        <el-row>
          <el-col :span="12">
            <el-form-item label="磷(mg/100g)" prop="phosphorus">
              <el-input
                v-model="form.phosphorus"
                @input="handleNumericInput('phosphorus', $event)"
                @blur="formatNumericValue('phosphorus')"
                placeholder="请输入磷"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="	钾(mg/100g)" prop="kalium">
              <el-input
                v-model="form.kalium"
                @input="handleNumericInput('kalium', $event)"
                @blur="formatNumericValue('kalium')"
                placeholder="请输入钾"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row> 
        <el-row>
          <el-col :span="12">
            <el-form-item label="钠 (mg/100g)" prop="sodium">
              <el-input
                v-model="form.sodium"
                @input="handleNumericInput('sodium', $event)"
                @blur="formatNumericValue('sodium')"
                placeholder="请输入钠"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="	镁(mg/100g)" prop="magnesium">
              <el-input
                v-model="form.magnesium"
                @input="handleNumericInput('magnesium', $event)"
                @blur="formatNumericValue('magnesium')"
                placeholder="请输入镁"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row> 
        <el-row>
          <el-col :span="12">
            <el-form-item label="铁 (mg/100g)" prop="iron">
              <el-input
                v-model="form.iron"
                @input="handleNumericInput('iron', $event)"
                @blur="formatNumericValue('iron')"
                placeholder="请输入铁"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="锌(mg/100g)" prop="zinc">
              <el-input
                v-model="form.zinc"
                @input="handleNumericInput('zinc', $event)"
                @blur="formatNumericValue('zinc')"
                placeholder="请输入锌"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row> 
        <el-row>
          <el-col :span="24">
            <el-form-item label="硒(μg/100g)" prop="selenium">
              <el-input
                v-model="form.selenium"
                @input="handleNumericInput('selenium', $event)"
                @blur="formatNumericValue('selenium')"
                placeholder="请输入硒"
              ></el-input>
            </el-form-item>
          </el-col>


        </el-row>  -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { nutritionTypeListApi,nutritionTypeAddApi, nutritionTypeEditApi, nutritionTypeDelApi  } from "@/api/dish/nutritionInfo";
import { listNutrition, getNutritionInfo, delNutrition, addMenuNutrition, updateNutrition } from "@/api/dish/nutritionInfo";
import { cascaderMixin } from './cascaderMixin';

export default {
  name: "NutritionInfo",
  mixins: [cascaderMixin],
  /** @type {import('vue').ComponentOptions} */
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      menuNutritionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nutritionName: undefined, 
      },
      // 表单参数
      form: {
        nutritionTypeId: undefined, // 营养信息类别
        nutritionName: undefined, // 营养信息名称
        nutritionCode: undefined, // 食材编码
        processingTime: undefined, // 加工时间
        edible: undefined, // 可食部分
        water: undefined, // 水分
        calories: undefined, // 热量
        protein: undefined, // 蛋白质
        fat: undefined, // 脂肪
        carbohydrate: undefined, // 碳水化合物
        dietaryFiber: undefined, // 膳食纤维
        cholesterol: undefined, // 胆固醇
        ash: undefined, // 灰分
        vitaminA: undefined, // 维生素A
        carotene: undefined, // 胡萝卜素
        retinol: undefined, // 视黄醇
        thiamine: undefined, // 硫胺素
        riboflavin: undefined, // 核黄素
        niacin: undefined, // 烟酸/尼克酸
        vitaminC: undefined, // 维生素C
        vitaminD: undefined, // 维生素D
        vitaminE: undefined, // 维生素E
        calcium: undefined, // 钙
        phosphorus: undefined, // 磷
        kalium: undefined, // 钾
        sodium: undefined, // 钠
        magnesium: undefined, // 镁
        iron: undefined, // 铁
        zinc: undefined, // 锌
        selenium: undefined, // 硒
      },
      formTable:[],
      // 表单校验
      rules: {
        nutritionTypeId: [
          { required: true, message: "请选择营养信息类别", trigger: "change" }
        ],
        nutritionName: [
          { required: true, message: "营养信息名称不能为空", trigger: "blur" }
        ],
        nutritionCode: [
          { required: true, message: "食材编码不能为空", trigger: "blur" }
        ]
      },
      typeSelected: [], // 级联选择器的选中值
      typeTreeData:[],//类别接口返回数据（未处理）
      cascaderOptions: [], // 级联选择器的选项（已处理）
      defaultProps: {
        children: "children",
        label: "label",
        id: "id"
      },
      keyWord:"",//左侧树-关键字查询
      isMousemoveId: null,
      openType:false,
      typeForm:{},
      typeRules: {
        name: [
          { required: true, message: "类别名称不能为空", trigger: "change" }
        ], 
        // nutritionName: [
        //   { required: true, message: "营养信息名称不能为空", trigger: "blur" }
        // ],
        // nutritionCode: [
        //   { required: true, message: "食材编码不能为空", trigger: "blur" }
        // ]
      },
    };
  },
  mounted() {
    this.getNutritionTypeList();
    this.getList();
  },
  watch: {
    // 根据名称筛选部门树
    keyWord(val) {
      this.$refs.nutritionTypeTree.filter(val);
    },
  },
  methods: { 
    //获取营养信息类别 
    getNutritionTypeList() {
      nutritionTypeListApi().then(response => {
        this.typeTreeData = response.data;
        this.cascaderOptions = this.cascaderOptionsMethod();  
        console.log(this.cascaderOptions)
      }).catch(error => {
        console.error("Failed to fetch food types:", error);
      });
    },  
    //生成级联选择器的选项数据
    cascaderOptionsMethod() {
      if (this.typeTreeData.length==0) {
        return [];
      }
      return this.typeTreeData.map(item => ({
        id: item.id,
        label: item.name,
        parentId:0,
        level:0,
        children: item.littleTypeList.map(subItem => ({
          id: subItem.id,//父子类别value一致时选中识别不出来，加个#号区分
          label: subItem.name,
          bigType: item.name,
          parentId:item.id,
          level:1
        }))
      }));
    },
    // 筛选节点 - 左侧树
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件 - 左侧树
    async handleNodeClick(data, node) {
      console.log(data)
      // this.handleQuery();
    },
    handleCheckChange(data, checked, indeterminate) { 
      this.handleQuery();
    },
    /* 树节点增加 */
    appendTreeNode(data) { 
      this.resetForm("typeForm");
      if(data&&data.level==0){
        this.typeForm={}
        this.typeForm.parentId = data.id;
        this.typeForm.parentName = data.label; 
      }else{
        this.typeForm={}
        this.typeForm.parentId = 0;
      }
      this.openType = true;
      this.title = "新增";
    }, 
    /* 树节点修改 */
    editTreeNode(data) {
      console.log(data) 
      this.typeForm={}
      this.resetForm("typeForm");
      this.$set(this.typeForm,"parentId",data.parentId)
      this.$set(this.typeForm,"nutritionTypeId",data.id)
      this.$set(this.typeForm,"nutritionTypeName",data.label)
      // this.typeForm = {
      //   ...data
      // };
      this.openType = true;
      this.title = "修改";
    },
    /* 树节点删除 */
    removeTreeNode(data) {
      console.log(data, "删除时的数据源--");
      this.$modal
        .confirm("是否确认删除数据项？")
        .then(function () {
          return nutritionTypeDelApi({id:data.id});
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          // this.getList();
          this.getNutritionTypeList();
        })
        .catch(() => {});
    },
    onMousemove(data) {
      this.isMousemoveId = data.id;
    },
    onMouseleave() {
      this.isMousemoveId = null;
    },
    handleSubmit(){
      console.log(this.typeForm)
      this.$refs.typeForm.validate(valid => {
        if (valid) {
          if (this.typeForm.nutritionTypeId != undefined) {
            console.log('修改')
            nutritionTypeEditApi(this.typeForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openType = false;
              this.getNutritionTypeList();
            });
          } else {
            console.log('新增')
            // console.log(this.typeForm)
            nutritionTypeAddApi(this.typeForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.openType = false;
              this.getNutritionTypeList();
            });
          }
        }
      });
    }, 
    /** 查询列表 */
    getList() {
      this.loading = true;
      let arr = this.$refs.nutritionTypeTree.getCheckedKeys()||[]
      if(arr.length>0){
        this.queryParams.nutritionTypeIds = arr.join(",");
      }else{
        this.queryParams.nutritionTypeIds = null
      } 
      console.log(this.queryParams)
      listNutrition(this.queryParams).then(response => {
        this.menuNutritionList = response.rows;
        this.total = Number(response.total);
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        nutritionTypeId: undefined, // 营养信息类别
        nutritionName: undefined, // 营养信息名称
        nutritionCode: undefined, // 食材编码
        processingTime: undefined, // 加工时间
        edible: undefined, // 可食部分
        water: undefined, // 水分
        calories: undefined, // 热量
        protein: undefined, // 蛋白质
        fat: undefined, // 脂肪
        carbohydrate: undefined, // 碳水化合物
        dietaryFiber: undefined, // 膳食纤维
        cholesterol: undefined, // 胆固醇
        ash: undefined, // 灰分
        vitaminA: undefined, // 维生素A
        carotene: undefined, // 胡萝卜素
        retinol: undefined, // 视黄醇
        thiamine: undefined, // 硫胺素
        riboflavin: undefined, // 核黄素
        niacin: undefined, // 烟酸/尼克酸
        vitaminC: undefined, // 维生素C
        vitaminD: undefined, // 维生素D
        vitaminE: undefined, // 维生素E
        calcium: undefined, // 钙
        phosphorus: undefined, // 磷
        kalium: undefined, // 钾
        sodium: undefined, // 钠
        magnesium: undefined, // 镁
        iron: undefined, // 铁
        zinc: undefined, // 锌
        selenium: undefined, // 硒
      };
      this.resetForm("form");
      this.formTable = [this.form]
    },
    /**
     * 搜索按钮操作
     * @method handleQuery
     * @description 重置页码为1并获取列表数据
     */
    handleQuery() {
      this.queryParams.pageNum = 1; 
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.$refs.nutritionTypeTree.setCheckedNodes([]); 
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加营养信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset(); 
      var data = {
        nutritionId: row.nutritionId
      }
      getNutritionInfo(data).then(response => {
        this.form = response.data; 
        this.formTable = [this.form]
        this.$set(this.form,"nutritionTypeId",Number(response.data.smallTypeId))   
        this.open = true;
        this.title = "修改营养信息";
      });
    }, 
    chosenType(e){
      console.log(e) 
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const formData = { ...this.form };
          if (formData.nutritionId != undefined) {
            updateNutrition(formData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMenuNutrition(formData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // const nutritionIds = row.nutritionId;
      var data = {
        nutritionId:row.nutritionId
      }
      this.$modal.confirm('是否确认删除数据项？').then(function() {
        return delNutrition(data);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /**
     * 处理数值输入
     * @param {string} field - 字段名
     * @param {Event} event - 输入事件
     */
    handleNumericInput(field, event) {
      const value = event;
      // 只允许输入数字和小数点
      let newValue = value.replace(/[^\d.]/g, '');

      // 确保只有一个小数点
      const parts = newValue.split('.');
      if (parts.length > 2) {
        newValue = parts[0] + '.' + parts.slice(1).join('');
      }

      // 限制小数点后最多两位
      if (parts.length === 2 && parts[1].length > 2) {
        newValue = parts[0] + '.' + parts[1].substring(0, 2);
      }     
      if(field=='edible'||field=='water'||field=='protein'||field=='fat'||field=='carbohydrate'||field=='dietaryFiber'||field=='ash'){
        if (parseFloat(newValue) > 100) {
          newValue = '100';
        }
      }else{
        // 限制最大值为100
        if (parseFloat(newValue) > 99999) {
          newValue = '100000';
        }
      }
      this.form[field] = newValue;
      this.formTable[0][field] = newValue;
    },

    /**
     * 格式化数值
     * @param {string} field - 字段名
     */
    formatNumericValue(field) {
      let value = this.form[field]; 
      if (!value || value === '' || value === '.') {
        this.form[field] = '0.00';
        return;
      }

      value = parseFloat(value);
      if (isNaN(value)) {
        value = 0;
      }

      // 限制最大值为100
      if (value > 99999) {
        value = 100000;
      }
      // 格式化为两位小数
      this.form[field] = value.toFixed(2);
      this.formTable[0][field] = value.toFixed(2);
    }

  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  max-height: calc(90vh - 120px);
  overflow-y: auto;
  padding: 20px;
}


::v-deep.el-table .fixed-width .el-button--mini {
  width: 60px !important;
  margin-bottom: 10px;
}

::v-deep .btn-items .el-button + .el-button {
  margin-left: 6px;
}
.btn-items {
  margin-left: 4px;
  .el-button--text {
    font-size: 16px;
  }
}
// ::v-deep .el-tree .el-tree-node__expand-icon.expanded {
//   -webkit-transform: rotate(0deg);
//   transform: rotate(0deg);
// }
// ::v-deep .el-tree .el-icon-caret-right:before {
//   content: "\e783";
//   font-size: 16px;
// }
// ::v-deep
// .el-tree
// .el-tree-node__expand-icon.expanded.el-icon-caret-right:before {
//   content: "\e781";
//   font-size: 16px;
//   color: #1890ff;
// }

// ::v-deep .el-tree-node__content > .el-tree-node__expand-icon {
//   color: #1890ff !important;
// }
// ::v-deep .el-tree-node__expand-icon.is-leaf {
//   color: transparent !important;
// }

// ::v-deep
// .el-tree--highlight-current
// .el-tree-node.is-current
// > .el-tree-node__content {
//   background-color: #8decf1;
// }

::v-deep .el-dialog .material-dialog {
  // 表单标签文字样式
  .el-form-item__label {
    font-size: 14px;
    color: #606266;
    font-weight: 500;
    line-height: 1.5;
  }

  // 输入框文字样式
  .el-input__inner {
    font-size: 14px;
    color: #303133;

    &::placeholder {
      font-size: 13px;
      color: #c0c4cc;
    }
  }

  // 单位文字样式
  span {
    font-size: 14px;
    // color: #606266;
    margin-left: 8px;
  }

  // 下拉选择框文字样式
  .el-select {
    .el-input__inner {
      font-size: 14px;
      color: #303133;
    }
  }

  // 只读输入框样式
  .el-input.is-disabled .el-input__inner {
    background-color: #f5f7fa;
    border-color: #e4e7ed;
    color: #606266;
    cursor: not-allowed;
  }
}

// 表格内文字样式
::v-deep .el-table {
  font-size: 14px;

  th {
    font-weight: 500;
    color: #303133;
  }

  td {
    color: #606266;
  }
}

// 按钮文字样式
::v-deep .el-button {
  font-size: 14px;

  &--text {
    font-size: 13px;
  }
}

// 树节点文字样式
::v-deep .el-tree-node__label {
  font-size: 14px;
  color: #606266;
}

// 搜索框文字样式
::v-deep .el-input--small {
  .el-input__inner {
    font-size: 13px;

    &::placeholder {
      font-size: 13px;
      color: #c0c4cc;
    }
  }
}
</style>
